opencrater 1.4.0 → 1.4.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/dist/cli.js +8 -8
- package/dist/hook.js +7 -7
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/index.mjs +3 -3
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var crypto=require('crypto'),m=require('fs'),
|
|
3
|
-
`,"utf8");for(let s=0;;s++)try{m__namespace.renameSync(f,o);return}catch(c){let l=c.code??"";if(s>=4||!
|
|
4
|
-
`,"utf8"),m__namespace.renameSync(o,e);}function
|
|
2
|
+
'use strict';var crypto=require('crypto'),m=require('fs'),U=require('os'),u=require('path'),child_process=require('child_process'),ye=require('readline');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var m__namespace=/*#__PURE__*/_interopNamespace(m);var U__namespace=/*#__PURE__*/_interopNamespace(U);var u__namespace=/*#__PURE__*/_interopNamespace(u);var ye__namespace=/*#__PURE__*/_interopNamespace(ye);var K=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var oe=360*60*1e3;function je(e=process.env){return u__namespace.join(U__namespace.homedir(),".config","opencrater")}function E(e=process.env){return u__namespace.join(je(e),"state.json")}function H(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function h(e){return typeof e=="number"&&Number.isFinite(e)}var re=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function se(e){for(let t=0;;t++)try{return {text:m__namespace.readFileSync(e,"utf8")}}catch(n){let o=n.code??"";if(!(o==="ENOENT"||re.has(o)))return {locked:true};if(t>=4)return o==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(t+1));}catch{}}}function xe(e){if(typeof e!="object"||e===null)return null;let t=e;return !h(t.minIntervalSeconds)||!h(t.serveTimeoutMs)||!h(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:h(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function Ce(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n,i=o.blip;if(!h(o.renderBy)||typeof i!="object"||i===null||typeof i.impressionId!="string"||typeof i.clickUrl!="string"||typeof i.sponsorLabel!="string"||typeof i.creative!="object"||i.creative===null)continue;let r=i.creative;typeof r.title!="string"||typeof r.body!="string"||t.push({blip:{impressionId:i.impressionId,...typeof i.campaignId=="string"?{campaignId:i.campaignId}:{},clickUrl:i.clickUrl,sponsorLabel:i.sponsorLabel,creative:{format:"text",title:r.title,body:r.body,...typeof r.cta=="string"?{cta:r.cta}:{}}},renderBy:o.renderBy});}return t}function Oe(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let t={};for(let[n,o]of Object.entries(e)){if(!Array.isArray(o))continue;let i=o.filter(r=>typeof r=="string"&&r.length<=64);t[n]=i.slice(0,64);}return t}function Ae(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n;if(!(typeof o.topic!="string"||!h(o.at))&&(t.push({topic:o.topic.slice(0,32),at:o.at}),t.length>=24))break}return t}function Re(e){if(!Array.isArray(e))return [];let t=[],n=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let i=o;if(typeof i.key!="string"||typeof i.package!="string"||i.key===""||i.package==="")continue;let r=`${i.package}\0${i.key}`;if(!n.has(r)&&(n.add(r),t.push({key:i.key,package:i.package}),t.length>=32))break}return t}function Pe(e){if(typeof e!="object"||e===null)return null;let t=e,n={};if(typeof t.savedEnv=="object"&&t.savedEnv!==null)for(let[o,i]of Object.entries(t.savedEnv))(typeof i=="string"||i===null)&&(n[o]=i);return {active:t.active===true,savedEnv:n}}function Ee(e){if(typeof e!="object"||e===null)return null;let t=e,n=o=>h(o)&&o>=0?o:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function Te(e){let t=e.attrTagsAt,n=e.attrTagsCwd;return !h(t)||Date.now()-t>oe||typeof n!="string"||n.length===0||n.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(i=>typeof i=="string"&&i.length<=40).slice(0,48):[],attrTagsCwd:n,attrTagsAt:t}}function $e(e){let t=H();if(typeof e!="object"||e===null)return t;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:t.installId,lastShownAt:h(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:xe(n.cachedConfig),allowedPlacements:Oe(n.allowedPlacements),sessionTopics:Ae(n.sessionTopics),integrations:Re(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Pe(n.computeRouting),computeCards:Ee(n.computeCards),configFetchedAt:h(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:Ce(n.pool),...Te(n)}}function g(e=process.env){let t=E(e),n=se(t);if(n.text!==void 0)try{return $e(JSON.parse(n.text))}catch{let o=H();try{P(o,e);}catch{}return o}if(n.missing){let o=H();try{P(o,e);}catch{}return o}return H()}function P(e,t=process.env,n={}){let o=E(t),i=u__namespace.dirname(o);m__namespace.mkdirSync(i,{recursive:true});let r=se(o),a=null;if(r.text!==void 0)try{a=JSON.parse(r.text);}catch{a=null;}if(a)typeof a.lastShownAt=="number"&&a.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:a.lastShownAt}),!n.allowClearToken&&typeof a.devToken=="string"&&e.devToken==null&&(e={...e,devToken:a.devToken}),typeof a.installId=="string"&&a.installId.length>0&&a.installId!==e.installId&&(e={...e,installId:a.installId});else if(!n.allowClearToken&&e.devToken==null&&r.text===void 0&&!r.missing)return;let f=u__namespace.join(i,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);m__namespace.writeFileSync(f,JSON.stringify(e,null,2)+`
|
|
3
|
+
`,"utf8");for(let s=0;;s++)try{m__namespace.renameSync(f,o);return}catch(c){let l=c.code??"";if(s>=4||!re.has(l)){try{m__namespace.rmSync(f,{force:!0});}catch{}if(s>=4)return;throw c}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(s+1));}catch{}}}function x(e,t=process.env){let n={...g(t),...e};return P(n,t),n}var ae={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],antigravity:["PreToolUse","PostToolUse","PreInvocation","PostInvocation","Stop"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var S=["claude_code","codex","antigravity","copilot_cli","grok_cli"];function w(e){return e.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(e)}function Ie(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ne(e,t){return w(e)&&new RegExp(`--package ['"]?${Ie(t)}['"]?`).test(e)}function X(e,t){return t?Ne(e,t):w(e)&&!/--package\b/.test(e)}function q(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var L='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',ce="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function T(e,t,n,o){let i=`--placement ${t}`;return n&&(i+=` --key ${q(n)}`),o&&(i+=` --package ${q(o)}`),i+=` --host ${e}`,`{ if [ -f ${L} ]; then node ${L} ${i}; else npx -y -p opencrater opencrater-hook ${i}; fi; } 2>/dev/null || true`}function _e(e,t,n){if(process.platform!=="win32")return T("grok_cli",e,t,n);let o=`--placement ${e}`;t&&(o+=` --key ${t}`),n&&(o+=` --package ${n}`),o+=" --host grok_cli";let i=`${U__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${i}") { node "${i}" ${o} } else { npx -y -p opencrater opencrater-hook ${o} } } catch {}`}function We(e,t,n){let o=`--placement ${e}`;return t&&(o+=` --key ${q(t)}`),n&&(o+=` --package ${q(n)}`),o+=" --host antigravity",`{ if [ -f ${L} ]; then node ${L} ${o}; else npx -y -p opencrater opencrater-hook ${o}; fi; } >/dev/null 2>&1; echo '{}'`}function fe(e,t,n,o){let i=`--placement ${t}`;return n&&(i+=` --key '${n}'`),o&&(i+=` --package '${o}'`),i+=` --host ${e}`,`try { if (Test-Path "${ce}") { node "${ce}" ${i} } else { npx -y -p opencrater opencrater-hook ${i} } } catch {}`}function Me(e,t,n){if(process.platform!=="win32")return T("claude_code",e,t,n);let o=`--placement ${e}`;return t&&(o+=` --key ${t}`),n&&(o+=` --package ${n}`),o+=" --host claude_code",`node "${`${U__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${o}; exit 0`}function Y(e,t,n,o){if(e==="grok_cli")return {type:"command",command:_e(t,n,o),timeout:15};let r={type:"command",command:e==="claude_code"?Me(t,n,o):T(e,t,n,o)};return e==="codex"&&(r.commandWindows=fe(e,t,n,o)),r}function B(e,t){let n=U__namespace.homedir();switch(e){case "claude_code":{let o=t.CLAUDE_CONFIG_DIR;return o&&o.trim()!==""?o:u__namespace.join(n,".claude")}case "codex":{let o=t.CODEX_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".codex")}case "antigravity":return u__namespace.join(n,".gemini");case "copilot_cli":{let o=t.COPILOT_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".copilot")}case "grok_cli":{let o=t.GROK_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".grok")}default:return u__namespace.join(n,".opencrater-unknown")}}function $(e,t=process.env){let n=B(e,t);switch(e){case "claude_code":return u__namespace.join(n,"settings.json");case "codex":return u__namespace.join(n,"hooks.json");case "antigravity":return u__namespace.join(n,"config","hooks.json");case "copilot_cli":return u__namespace.join(n,"hooks","hooks.json");case "grok_cli":return u__namespace.join(n,"hooks","opencrater.json");default:return u__namespace.join(n,"hooks.json")}}var He={claude_code:["claude"],codex:["codex"],antigravity:["agy"],copilot_cli:["copilot"],grok_cli:["grok"]};function qe(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(u__namespace.delimiter).filter(Boolean),o=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let i of n)for(let r of e)for(let a of o)try{if(m__namespace.existsSync(u__namespace.join(i,r+a)))return !0}catch{}return false}function Le(e,t=process.env){try{if(m__namespace.existsSync(B(e,t)))return !0}catch{}return qe(He[e]??[],t)}function Q(e=process.env){return S.filter(t=>Le(t,e))}function O(e){let t;try{t=m__namespace.readFileSync(e,"utf8");}catch{return {}}let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n}function C(e,t){let n=u__namespace.dirname(e);m__namespace.mkdirSync(n,{recursive:true});let o=u__namespace.join(n,`.${u__namespace.basename(e)}.${process.pid}.tmp`);m__namespace.writeFileSync(o,JSON.stringify(t,null,2)+`
|
|
4
|
+
`,"utf8"),m__namespace.renameSync(o,e);}function Ue(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&X(n.command,t))}function Be(e,t,n,o){let i=$(e),r=O(i),a=r.hooks&&typeof r.hooks=="object"?r.hooks:{};if(o.every(s=>{let c=Y(e,s,t,n);return (Array.isArray(a[s])?a[s]:[]).some(l=>Array.isArray(l.hooks)&&l.hooks.some(d=>d.command===c.command&&d.commandWindows===c.commandWindows))}))return "nochange";for(let s of o){let l=(Array.isArray(a[s])?a[s]:[]).filter(p=>!Ue(p,n)),d=e==="grok_cli"?{hooks:[Y(e,s,t,n)]}:{matcher:"",hooks:[Y(e,s,t,n)]};l.push(d),a[s]=l;}return r.hooks=a,C(i,r),"wrote"}var Fe=15;function De(e){return e?`opencrater-${e}`:"opencrater-compute"}function ze(e,t){if(!e||typeof e!="object")return false;for(let n of Object.values(e))for(let o of Array.isArray(n)?n:[])if(Array.isArray(o.hooks)&&o.hooks.some(i=>typeof i.command=="string"&&X(i.command,t)))return true;return false}function ue(e){try{let t=u__namespace.join(B("antigravity",e),"settings.json"),n;try{n=O(t);}catch{return}let o=!1,i=n.hooks;if(i&&typeof i=="object"&&!Array.isArray(i)){let r=i;for(let a of Object.keys(r)){let f=Array.isArray(r[a])?r[a]:[],s=f.filter(c=>!(Array.isArray(c.hooks)&&c.hooks.some(l=>typeof l.command=="string"&&w(l.command))));s.length!==f.length&&(o=!0,s.length>0?r[a]=s:delete r[a]);}Object.keys(r).length===0&&(delete n.hooks,o=!0);}n["json-hooks-enabled"]===!0&&(delete n["json-hooks-enabled"],o=!0),o&&C(t,n);}catch{}}function Ge(e,t,n){let o=$("antigravity"),i=O(o),r=De(t),a={};for(let c of n)a[c]=[{hooks:[{type:"command",command:We(c,e,t),timeout:Fe}]}];let f=JSON.stringify(a),s=false;JSON.stringify(i[r]??null)!==f&&(i[r]=a,s=true);for(let c of Object.keys(i))c!==r&&ze(i[c],t)&&(delete i[c],s=true);return ue(process.env),s?(C(o,i),"wrote"):"nochange"}var le=12;function Je(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&X(n,t))}function Ke(e,t,n,o){let i=$(e),r=O(i);typeof r.version!="number"&&(r.version=1);let a=r.hooks&&typeof r.hooks=="object"?r.hooks:{};if(o.every(s=>{let c=T(e,s,t,n);return (Array.isArray(a[s])?a[s]:[]).some(l=>l.bash===c&&l.timeoutSec===le)}))return "nochange";for(let s of o){let l=(Array.isArray(a[s])?a[s]:[]).filter(d=>!Je(d,n));l.push({type:"command",bash:T(e,s,t,n),powershell:fe(e,s,t,n),timeoutSec:le}),a[s]=l;}return r.hooks=a,C(i,r),"wrote"}function F(e){return [...ae[e]]}function Ve(e){let t=e;for(let n of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${n}\\]`,"m").test(t))continue;let o=t.length===0?"":t.endsWith(`
|
|
5
5
|
`)?`
|
|
6
6
|
`:`
|
|
7
7
|
|
|
8
8
|
`;t+=`${o}[compat.${n}]
|
|
9
9
|
hooks = false
|
|
10
|
-
`;}return t}function
|
|
11
|
-
`),
|
|
12
|
-
\u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${_(n.balanceMicroUsd)}${W(n)} \xB7 tier: ${n.trustTier}`);let o=
|
|
10
|
+
`;}return t}function Ye(e){try{let t=u__namespace.join(B("grok_cli",e),"config.toml"),n="";try{n=m__namespace.readFileSync(t,"utf8");}catch{}let o=Ve(n);if(o===n)return;m__namespace.mkdirSync(u__namespace.dirname(t),{recursive:!0}),m__namespace.writeFileSync(t,o,"utf8");}catch{}}function D(e,t,n){let o=F(e);return o.length===0?"nochange":(e==="grok_cli"&&Ye(process.env),e==="copilot_cli"?Ke(e,t,n,o):e==="antigravity"?Ge(t,n,o):Be(e,t,n,o))}function I(e,t,n=process.env){return Q(n).map(o=>{try{let i=D(o,e,t);return {host:o,status:i,events:F(o)}}catch(i){return {host:o,status:"error",events:[],error:i.message}}})}function Z(e=process.env){let t=[];for(let n of S){let o;try{o=O($(n,e));}catch{continue}if(n==="antigravity"){for(let r of Object.values(o))if(!(!r||typeof r!="object"))for(let[a,f]of Object.entries(r))for(let s of Array.isArray(f)?f:[]){let c=s,l=Array.isArray(c.hooks)?c.hooks.find(d=>typeof d.command=="string"&&w(d.command))?.command:void 0;l&&t.push({host:n,event:a,command:l});}continue}let i=o.hooks;if(!(!i||typeof i!="object"))for(let[r,a]of Object.entries(i))for(let f of Array.isArray(a)?a:[]){let s=f,c=Array.isArray(s.hooks)?s.hooks.find(p=>typeof p.command=="string"&&w(p.command))?.command:void 0,l=[s.bash,s.command,s.powershell].find(p=>typeof p=="string"&&w(p)),d=c??l;d&&t.push({host:n,event:r,command:d});}}return t}function de(e=process.env){let t=0;for(let n of S){let o=$(n,e),i;try{i=O(o);}catch{continue}if(n==="antigravity"){let s=false;for(let c of Object.keys(i)){let l=i[c];if(!l||typeof l!="object"||Array.isArray(l))continue;let d=l;for(let p of Object.keys(d)){let R=Array.isArray(d[p])?d[p]:[],k=R.filter(be=>{let ee=be,ne=Array.isArray(ee.hooks)&&ee.hooks.some(te=>typeof te.command=="string"&&w(te.command));return ne&&t++,!ne});k.length!==R.length&&(s=true,k.length>0?d[p]=k:delete d[p]);}Object.keys(d).length===0&&(delete i[c],s=true);}if(s)try{Object.keys(i).length===0?m__namespace.rmSync(o,{force:!0}):C(o,i);}catch{}ue(e);continue}let r=i.hooks;if(!r||typeof r!="object")continue;let a=r,f=false;for(let s of Object.keys(a)){let c=Array.isArray(a[s])?a[s]:[],l=c.filter(d=>{let p=d,R=Array.isArray(p.hooks)&&p.hooks.some(k=>typeof k.command=="string"&&w(k.command))||[p.bash,p.powershell,p.command].some(k=>typeof k=="string"&&w(k));return R&&t++,!R});l.length!==c.length&&(f=true,l.length>0?a[s]=l:delete a[s]);}if(f)try{let s=Object.keys(i).filter(l=>l!=="version"&&l!=="hooks"),c=n==="copilot_cli"||n==="codex";Object.keys(a).length===0&&s.length===0&&c?m__namespace.rmSync(o,{force:!0}):C(o,i);}catch{}}return t}var N="1.4.1";var Xe="https://api.opencrater.to";function A(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:Xe)).replace(/\/+$/,"")}function Ze(){return u__namespace.join(U__namespace.homedir(),".config","opencrater","runtime")}function en(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function z(e=Ze()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",en(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}function nn(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):A().replace("//api.","//").replace(/\/$/,"")}function tn(e){try{let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";child_process.spawn(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref();}catch{}}function on(e){let t=ye__namespace.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>t.question(e,o=>(t.close(),n(o))))}function _(e){return `${Math.round(e/1e3).toLocaleString()} tokens`}function rn(e){let t=e/1e3;return t>0&&t<10?`${(Math.round(t*10)/10).toFixed(1)} tokens`:`${Math.round(t).toLocaleString()} tokens`}function W(e){let t=e?.pendingMicroUsd??0;return t>0?` \xB7 +${rn(t)} pending`:""}async function M(e,t){try{let n=new URL(`${A()}/v1/dev/me`);t&&n.searchParams.set("installId",t);let o=await fetch(n,{headers:{authorization:`Bearer ${e}`}});return o.ok?await o.json():null}catch{return null}}async function sn(){let e=`${nn()}/dev/link`;console.log("Sign in and generate a CLI token here (we tried to open it):"),console.log(` ${e}
|
|
11
|
+
`),tn(e);let t=(await on("Paste your token (ocd_\u2026): ")).trim();if(!t.startsWith("ocd_"))return console.error("That doesn't look like a token (should start with ocd_)."),1;let n=await M(t,g().installId);if(!n)return console.error("Couldn't verify that token \u2014 check it and try again."),1;x({devToken:t}),console.log(`
|
|
12
|
+
\u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${_(n.balanceMicroUsd)}${W(n)} \xB7 tier: ${n.trustTier}`);let o=I().filter(i=>i.status!=="error").map(i=>i.host);return o.length?(console.log(` Wired into: ${o.join(", ")}`),process.stdout.write(" Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(z()?"\u2713":"skipped (hooks use npx fallback)")):console.log(" No supported AI CLIs detected yet \u2014 they'll wire automatically once you install one."),console.log(" See Blips in your sessions to earn your weekly compute."),0}async function an(){let e=g().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let t=await M(e,g().installId);return t?(console.log(`Compute balance: ${_(t.balanceMicroUsd)}${W(t)}`),console.log(` signed in as: ${t.displayName} \xB7 tier: ${t.trustTier}`),0):(console.error("Couldn't reach OpenCrater (or your session expired \u2014 try: opencrater login)."),1)}function cn(){return P({...g(),devToken:null},process.env,{allowClearToken:true}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function ln(e){let t=g().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await M(t,g().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${A().replace(/\/$/,"")}/gateway`,i=u__namespace.join(u__namespace.dirname(E()),"claude-gateway.settings.json");try{m__namespace.mkdirSync(u__namespace.dirname(i),{recursive:!0}),m__namespace.writeFileSync(i,JSON.stringify({apiKeyHelper:`echo ${t}`}),{mode:384});}catch(f){return console.error(`Couldn't write gateway settings: ${f.message}`),1}n&&console.log(`Launching Claude Code on OpenCrater compute \xB7 balance ${_(n.balanceMicroUsd)}${W(n)}`);let r={...process.env,ANTHROPIC_BASE_URL:o,OPENCRATER_ON_GATEWAY:"1"};delete r.ANTHROPIC_API_KEY;let a=child_process.spawn("claude",[...e,"--settings",i],{stdio:"inherit",env:r,shell:process.platform==="win32"});return await new Promise(f=>{a.on("exit",s=>f(s??0)),a.on("error",s=>{console.error(`Couldn't launch claude: ${s.message}`),console.error("Is Claude Code installed? https://claude.com/claude-code"),f(127);});})}async function fn(e){let t=g().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await M(t,g().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${A().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Codex on OpenCrater compute \xB7 balance ${_(n.balanceMicroUsd)}${W(n)}`);let i={...process.env,OPENCRATER_TOKEN:t,OPENCRATER_ON_GATEWAY:"1"},r=["-c",'model_provider="opencrater"',"-c",'model_providers.opencrater.name="OpenCrater"',"-c",`model_providers.opencrater.base_url="${o}"`,"-c",'model_providers.opencrater.wire_api="responses"',"-c",'model_providers.opencrater.env_key="OPENCRATER_TOKEN"'],a=[];for(let s=0;s<e.length;s++){let c=e[s],l=e[s+1];c==="-c"&&(l===void 0||!l.includes("="))?a.push("resume","--last"):a.push(c);}let f=child_process.spawn("codex",[...r,...a],{stdio:"inherit",env:i,shell:process.platform==="win32"});return await new Promise(s=>{f.on("exit",c=>s(c??0)),f.on("error",c=>{console.error(`Couldn't launch codex: ${c.message}`),console.error("Is Codex installed? npm i -g @openai/codex"),s(127);});})}function un(){let e=process.env.GROK_HOME;return e&&e.trim()!==""?e:u__namespace.join(U__namespace.homedir(),".grok")}function dn(e){let t=u__namespace.join(un(),"config.toml"),n="";try{n=m__namespace.readFileSync(t,"utf8");}catch{}if(/^\s*\[model\.opencrater\]/m.test(n))return;let o=n.length===0?"":n.endsWith(`
|
|
13
13
|
`)?`
|
|
14
14
|
`:`
|
|
15
15
|
|
|
@@ -18,7 +18,7 @@ model = "x-ai/grok-build-0.1"
|
|
|
18
18
|
base_url = "${e}"
|
|
19
19
|
name = "OpenCrater Compute"
|
|
20
20
|
env_key = "OPENCRATER_TOKEN"
|
|
21
|
-
`,m__namespace.mkdirSync(u__namespace.dirname(t),{recursive:true}),m__namespace.writeFileSync(t,n,"utf8");}async function
|
|
21
|
+
`,m__namespace.mkdirSync(u__namespace.dirname(t),{recursive:true}),m__namespace.writeFileSync(t,n,"utf8");}async function pn(e){let t=g().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await M(t,g().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${A().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Grok on OpenCrater compute \xB7 balance ${_(n.balanceMicroUsd)}${W(n)}`);try{D("grok_cli");}catch{}try{dn(o);}catch(s){return console.error(`Couldn't configure the Grok compute model: ${s.message}`),1}let i={...process.env,OPENCRATER_TOKEN:t,OPENCRATER_ON_GATEWAY:"1"};delete i.GROK_MODELS_BASE_URL,delete i.GROK_HOME;let a=e.some(s=>s==="-m"||s==="--model"||s.startsWith("--model="))?[]:["-m","opencrater"],f=child_process.spawn("grok",[...a,...e],{stdio:"inherit",env:i,shell:process.platform==="win32"});return await new Promise(s=>{f.on("exit",c=>s(c??0)),f.on("error",c=>{console.error(`Couldn't launch grok: ${c.message}`),console.error("Is Grok installed? npm i -g @xai-official/grok"),s(127);});})}function ke(e){let t=new Map,n=[];for(let o=0;o<e.length;o++){let i=e[o];if(i!==void 0)if(i.startsWith("--")){let r=i.indexOf("=");if(r!==-1)t.set(i.slice(2,r),i.slice(r+1));else {let a=e[o+1];a!==void 0&&!a.startsWith("--")?(t.set(i.slice(2),a),o++):t.set(i.slice(2),"true");}}else n.push(i);}return {flags:t,rest:n}}function we(e,t){let n=g();n.integrations.some(o=>o.key===e&&o.package===t)||x({integrations:[...n.integrations,{key:e,package:t}].slice(-32)});}function G(e,t){let n=t||"compute hooks";if(e.length===0){console.log(`No supported AI CLIs detected yet \u2014 OpenCrater will wire ${n} automatically the moment you install one (it re-checks on the next session).`);return}console.log(`OpenCrater wired ${n} into:`);for(let o of e)if(o.status==="error")console.log(` \u2717 ${o.host}: ${o.error}`);else {let i=o.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${o.host} (${o.events.join(", ")})${i}`);}}function mn(){return x({optOut:true}),console.log("OpenCrater Blips are now OFF for this machine."),console.log("Re-enable any time with: npx opencrater on"),0}function gn(e){let{flags:t}=ke(e),n=t.get("key"),o=t.get("package");return x({optOut:false}),n&&o?(we(n,o),G(I(n,o),o),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(z()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):g().devToken?(G(I()),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(z()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):(console.log("OpenCrater Blips are now ON for this machine."),console.log("Earn compute: run `opencrater login` (no package needed)."),console.log("Earn cash as a publisher: `opencrater on --key <key> --package <name>`.")),console.log("Opt out any time with: npx opencrater off"),0}function hn(){let e=g(),t=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${N}`),console.log(` state file: ${E()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${t}`),console.log(` pooled Blips: ${e.pool.length}`),console.log(` hosts found: ${Q().join(", ")||"(none)"}`),console.log(` integrations: ${e.integrations.map(o=>o.package).join(", ")||"(none)"}`);let n=Z();return console.log(` wired hooks: ${n.length}`),0}function yn(e){let{flags:t}=ke(e),n=t.get("key"),o=t.get("package");if(!n||!o)return console.error("Usage: opencrater hooks install --key <publisherKey> --package <name> [--host <host>]"),1;we(n,o);let i=t.get("host");if(i&&i!=="true"){if(!S.includes(i))return console.error(`Unknown host "${i}". Supported: ${S.join(", ")}`),1;let r=i;try{let a=D(r,n,o);G([{host:r,status:a,events:F(r)}],o);}catch(a){return console.error(`Could not wire ${r}: ${a.message}`),1}}else G(I(n,o),o);return console.log("Remove with: npx opencrater hooks uninstall"),0}function kn(){let e=de();return x({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function wn(){let e=Z();if(e.length===0)return console.log("No OpenCrater hooks installed."),0;for(let t of e)console.log(`${t.host} ${t.event}: ${t.command}`);return 0}function ge(){return console.log(`opencrater v${N} \u2014 OpenCrater Blips
|
|
22
22
|
|
|
23
23
|
Usage:
|
|
24
24
|
opencrater on [--key <ock_\u2026> --package <name>]
|
|
@@ -43,4 +43,4 @@ Usage:
|
|
|
43
43
|
opencrater hooks list List installed OpenCrater hooks
|
|
44
44
|
|
|
45
45
|
Hosts: ${S.join(", ")}
|
|
46
|
-
Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function
|
|
46
|
+
Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function bn(e){let[t,...n]=e;switch(t){case "off":return mn();case "on":return gn(n);case "login":return sn();case "balance":return an();case "logout":return cn();case "claude":case "code":return ln(n);case "codex":return fn(n);case "grok":return pn(n);case "status":return hn();case "hooks":{let[o,...i]=n;switch(o){case "install":return yn(i);case "uninstall":return kn();case "list":return wn();default:return console.error("Usage: opencrater hooks <install|uninstall|list>"),1}}case "version":case "--version":case "-v":return console.log(N),0;case void 0:case "help":case "--help":case "-h":return ge();default:return console.error(`Unknown command: ${t}`),ge(),1}}typeof K<"u"&&typeof module<"u"&&K.main===module&&Promise.resolve().then(()=>bn(process.argv.slice(2))).then(e=>{process.exitCode=e;}).catch(e=>{console.error(`opencrater: ${e.message}`),process.exitCode=1;});exports.runCli=bn;
|
package/dist/hook.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var child_process=require('child_process'),h=require('fs'),N=require('os'),y=require('path'),crypto=require('crypto');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var h__namespace=/*#__PURE__*/_interopNamespace(h);var N__namespace=/*#__PURE__*/_interopNamespace(N);var y__namespace=/*#__PURE__*/_interopNamespace(y);var M=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(o,e)=>(typeof require<"u"?require:o)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var
|
|
3
|
-
`);}catch{}}catch{}}function z(t){return typeof t=="number"&&Number.isFinite(t)}function bt(t){let o=B;if(typeof t!="object"||t===null)return {...o};let e=t;return {minIntervalSeconds:z(e.minIntervalSeconds)?e.minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:z(e.serveTimeoutMs)?e.serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:z(e.preloadPoolSize)?e.preloadPoolSize:o.preloadPoolSize,killSwitch:e.killSwitch===true,displayDurationSeconds:z(e.displayDurationSeconds)?e.displayDurationSeconds:o.displayDurationSeconds,minSdkVersion:typeof e.minSdkVersion=="string"?e.minSdkVersion:o.minSdkVersion}}async function _e(t,o,e,r,n){try{let c=await fetch(`${t}${o}`,{method:"POST",headers:{"content-type":"application/json",...n??{}},body:JSON.stringify(e),signal:AbortSignal.timeout(r)});return c.ok?await c.json():(x(`POST ${o} -> HTTP ${c.status}`),null)}catch(c){return x(`POST ${o} failed:`,c),null}}function Ie(t,o){let e=t.host??"generic";return {publisherKey:t.publisherKey,packageName:t.packageName,placement:t.placement,host:e,sdkVersion:A,installId:o.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:o.topics&&o.topics.length>0?o.topics:void 0,tags:o.tags&&o.tags.length>0?o.tags:void 0}}function Pe(t){if(typeof t!="object"||t===null)return null;let o=t;if(typeof o.fill!="boolean")return null;let e={fill:o.fill,fallback:o.fallback??null,config:bt(o.config),...Array.isArray(o.allowedPlacements)?{allowedPlacements:o.allowedPlacements.filter(r=>typeof r=="string")}:{}};return o.blip!==void 0&&o.blip!==null&&(e.blip=o.blip),typeof o.computeBalanceMicroUsd=="number"&&(e.computeBalanceMicroUsd=o.computeBalanceMicroUsd),typeof o.weeklyGrantMicroUsd=="number"&&(e.weeklyGrantMicroUsd=o.weeklyGrantMicroUsd),typeof o.pendingMicroUsd=="number"&&(e.pendingMicroUsd=o.pendingMicroUsd),e}async function Ne(t,o){let e=await _e(o.origin,"/v1/serve",Ie(t,o),o.timeoutMs);return Pe(e)}async function $e(t,o,e){let r={...Ie(o,e),publisherKey:o.publisherKey??"",packageName:o.packageName??""},n=await _e(e.origin,"/v1/dev/serve",r,e.timeoutMs,{authorization:`Bearer ${t}`});return Pe(n)}var wt=48,K=360*60*1e3;function Me(t){return crypto.createHash("sha256").update(t).digest("hex").slice(0,16)}function Le(t){let o=new Set,e=s=>{o.size<wt&&o.add(s);},r=[];try{r=h__namespace.readdirSync(t);}catch{return []}let n=s=>r.includes(s),c=s=>{try{return h__namespace.readFileSync(y__namespace.join(t,s),"utf8")}catch{return ""}},f=s=>{try{return JSON.parse(c(s))}catch{return null}},p=f("package.json")??{},u={...p.dependencies??{},...p.devDependencies??{},...p.peerDependencies??{}},a=s=>Object.prototype.hasOwnProperty.call(u,s),d=s=>Object.keys(u).some(i=>i===s||i.startsWith(s));n("package.json")&&(e("lang:javascript"),(a("typescript")||n("tsconfig.json"))&&e("lang:typescript")),(n("deno.json")||n("deno.jsonc"))&&e("lang:typescript"),(n("tsconfig.json")||n("tsconfig.base.json"))&&e("lang:typescript"),n("jsconfig.json")&&e("lang:javascript"),(n("bun.lockb")||n("bun.lock"))&&e("lang:javascript"),r.some(s=>s.endsWith(".ts")||s.endsWith(".tsx")||s.endsWith(".mts")||s.endsWith(".cts"))&&e("lang:typescript"),r.some(s=>s.endsWith(".js")||s.endsWith(".jsx")||s.endsWith(".mjs")||s.endsWith(".cjs"))&&e("lang:javascript"),(n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile"))&&e("lang:python"),(n("setup.cfg")||n("Pipfile.lock")||n("poetry.lock")||n("uv.lock")||n("environment.yml"))&&e("lang:python"),r.some(s=>s.endsWith(".py")||s.endsWith(".pyi")||s.endsWith(".ipynb"))&&e("lang:python"),(n("go.mod")||n("go.sum")||n("go.work"))&&e("lang:go"),r.some(s=>s.endsWith(".go"))&&e("lang:go"),(n("Cargo.toml")||n("Cargo.lock"))&&e("lang:rust"),r.some(s=>s.endsWith(".rs"))&&e("lang:rust"),(n("pom.xml")||n("build.gradle"))&&e("lang:java"),r.some(s=>s.endsWith(".java"))&&e("lang:java"),(n("build.gradle.kts")||n("settings.gradle.kts"))&&e("lang:kotlin"),r.some(s=>s.endsWith(".kt")||s.endsWith(".kts"))&&e("lang:kotlin"),(n("build.sbt")||n(".scalafmt.conf"))&&e("lang:scala"),r.some(s=>s.endsWith(".scala")||s.endsWith(".sc"))&&e("lang:scala"),r.some(s=>s.endsWith(".groovy")||s.endsWith(".gradle"))&&e("lang:groovy"),(n("deps.edn")||n("project.clj")||n("shadow-cljs.edn"))&&e("lang:clojure"),r.some(s=>s.endsWith(".clj")||s.endsWith(".cljs")||s.endsWith(".cljc"))&&e("lang:clojure"),r.some(s=>s.endsWith(".csproj")||s.endsWith(".sln"))&&e("lang:csharp"),r.some(s=>s.endsWith(".fsproj"))&&e("lang:fsharp"),r.some(s=>s.endsWith(".cs"))&&e("lang:csharp"),r.some(s=>s.endsWith(".fs")||s.endsWith(".fsx")||s.endsWith(".fsi"))&&e("lang:fsharp"),r.some(s=>s.endsWith(".cpp")||s.endsWith(".cc")||s.endsWith(".cxx")||s.endsWith(".hpp")||s.endsWith(".hxx"))&&e("lang:cpp"),r.some(s=>s.endsWith(".c"))&&e("lang:c"),(n("composer.json")||n("composer.lock"))&&e("lang:php"),r.some(s=>s.endsWith(".php"))&&e("lang:php"),(n("Gemfile")||n("Gemfile.lock")||n(".ruby-version")||r.some(s=>s.endsWith(".gemspec")))&&e("lang:ruby"),r.some(s=>s.endsWith(".rb")||s==="Rakefile")&&e("lang:ruby"),(n("Package.swift")||n("Podfile")||r.some(s=>s.endsWith(".xcodeproj")||s.endsWith(".xcworkspace")))&&e("lang:swift"),r.some(s=>s.endsWith(".swift"))&&e("lang:swift"),r.some(s=>s.endsWith(".m")||s.endsWith(".mm"))&&e("lang:objective-c"),(n("pubspec.yaml")||n("pubspec.yml")||n("pubspec.lock"))&&e("lang:dart"),r.some(s=>s.endsWith(".dart"))&&e("lang:dart"),(n("mix.exs")||n("mix.lock"))&&e("lang:elixir"),r.some(s=>s.endsWith(".ex")||s.endsWith(".exs"))&&e("lang:elixir"),(n("rebar.config")||n("rebar.lock"))&&e("lang:erlang"),r.some(s=>s.endsWith(".erl")||s.endsWith(".hrl"))&&e("lang:erlang"),(n("gleam.toml")||r.some(s=>s.endsWith(".gleam")))&&e("lang:gleam"),(n("stack.yaml")||n("cabal.project")||r.some(s=>s.endsWith(".cabal")||s.endsWith(".hs")))&&e("lang:haskell"),(n("dune-project")||n("dune")||r.some(s=>s.endsWith(".ml")||s.endsWith(".mli")))&&e("lang:ocaml"),(r.some(s=>s.endsWith(".rockspec")||s.endsWith(".lua"))||n(".luarc.json"))&&e("lang:lua"),(n("cpanfile")||n("Makefile.PL")||r.some(s=>s.endsWith(".pl")||s.endsWith(".pm")))&&e("lang:perl"),(n("DESCRIPTION")||n("renv.lock")||r.some(s=>s.endsWith(".Rproj")||s.endsWith(".Rmd")||s.endsWith(".R")))&&e("lang:r"),(n("Project.toml")||n("Manifest.toml")||r.some(s=>s.endsWith(".jl")))&&e("lang:julia"),(n("build.zig")||n("build.zig.zon")||r.some(s=>s.endsWith(".zig")))&&e("lang:zig"),r.some(s=>s.endsWith(".nimble")||s.endsWith(".nim"))&&e("lang:nim"),(n("shard.yml")||n("shard.lock")||r.some(s=>s.endsWith(".cr")))&&e("lang:crystal"),(n("v.mod")||r.some(s=>s.endsWith(".vsh")))&&e("lang:vlang"),r.some(s=>s.endsWith(".hx")||s.endsWith(".hxml"))&&e("lang:haxe"),(n("foundry.toml")||n("hardhat.config.js")||n("hardhat.config.ts")||r.some(s=>s.endsWith(".sol")))&&e("lang:solidity"),r.some(s=>s.endsWith(".f")||s.endsWith(".f90")||s.endsWith(".f95"))&&e("lang:fortran"),r.some(s=>s.endsWith(".cob")||s.endsWith(".cbl"))&&e("lang:cobol"),r.some(s=>s.endsWith(".asm"))&&e("lang:assembly"),r.some(s=>s.endsWith(".sh")||s.endsWith(".bash")||s.endsWith(".zsh"))&&e("lang:shell"),r.some(s=>s.endsWith(".ps1")||s.endsWith(".psm1"))&&e("lang:powershell"),r.some(s=>s.endsWith(".sql"))&&e("lang:sql"),r.some(s=>s.endsWith(".html")||s.endsWith(".htm"))&&e("lang:html"),r.some(s=>s.endsWith(".css"))&&e("lang:css"),r.some(s=>s.endsWith(".scss")||s.endsWith(".sass"))&&e("lang:scss"),r.some(s=>s.endsWith(".graphql")||s.endsWith(".gql"))&&e("lang:graphql"),r.some(s=>s.endsWith(".proto"))&&e("lang:protobuf");{if(a("react")&&e("fw:react"),a("next")&&e("fw:nextjs"),a("vue")&&e("fw:vue"),(a("nuxt")||a("nuxt3"))&&e("fw:nuxt"),a("@angular/core")&&e("fw:angular"),a("svelte")&&e("fw:svelte"),a("@sveltejs/kit")&&e("fw:sveltekit"),(a("@remix-run/react")||a("@remix-run/node"))&&e("fw:remix"),a("astro")&&e("fw:astro"),a("gatsby")&&e("fw:gatsby"),a("solid-js")&&e("fw:solid"),(a("@solidjs/start")||a("solid-start"))&&e("fw:solidstart"),(a("@builder.io/qwik")||a("@qwik.dev/core"))&&e("fw:qwik"),a("preact")&&e("fw:preact"),(a("lit")||a("lit-element"))&&e("fw:lit"),(a("ember-source")||a("ember-cli"))&&e("fw:ember"),a("htmx.org")&&e("fw:htmx"),a("vite")&&e("fw:vite"),a("webpack")&&e("fw:webpack"),a("express")&&e("fw:express"),a("fastify")&&e("fw:fastify"),a("@nestjs/core")&&e("fw:nestjs"),a("koa")&&e("fw:koa"),a("hono")&&e("fw:hono"),(a("@hapi/hapi")||a("hapi"))&&e("fw:hapi"),a("@adonisjs/core")&&e("fw:adonis"),(a("@trpc/server")||a("@trpc/client"))&&e("fw:trpc"),a("sails")&&e("fw:sails"),a("electron")&&e("fw:electron"),a("react-native")&&e("fw:react-native"),a("expo")&&e("fw:expo"),d("@ionic/")&&e("fw:ionic"),a("@capacitor/core")&&e("fw:capacitor"),n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile")){let i=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")).toLowerCase();i.includes("fastapi")&&e("fw:fastapi"),i.includes("django")&&e("fw:django"),i.includes("flask")&&e("fw:flask"),i.includes("litestar")&&e("fw:litestar"),i.includes("starlette")&&e("fw:starlette"),i.includes("tornado")&&e("fw:tornado"),i.includes("sanic")&&e("fw:sanic"),i.includes("aiohttp")&&e("fw:aiohttp"),i.includes("pyramid")&&e("fw:pyramid"),i.includes("fasthtml")&&e("fw:fasthtml"),(i.includes("torch")||i.includes("pytorch"))&&e("fw:pytorch"),i.includes("tensorflow")&&e("fw:tensorflow"),(i.includes("jax")||i.includes("jaxlib"))&&e("fw:jax"),i.includes("keras")&&e("fw:keras"),(i.includes("scikit-learn")||i.includes("sklearn"))&&e("fw:scikit-learn"),i.includes("transformers")&&e("fw:transformers"),i.includes("langchain")&&e("fw:langchain"),(i.includes("llama-index")||i.includes("llama_index")||i.includes("llamaindex"))&&e("fw:llamaindex"),i.includes("pandas")&&e("fw:pandas"),i.includes("numpy")&&e("fw:numpy"),i.includes("streamlit")&&e("fw:streamlit"),i.includes("gradio")&&e("fw:gradio"),i.includes("fastai")&&e("fw:fastai");}if(n("go.mod")){let i=c("go.mod").toLowerCase();i.includes("gin-gonic/gin")&&e("fw:gin"),i.includes("labstack/echo")&&e("fw:echo"),i.includes("gofiber/fiber")&&e("fw:fiber"),i.includes("go-chi/chi")&&e("fw:chi"),(i.includes("gorilla/mux")||i.includes("gorilla/websocket"))&&e("fw:gorilla"),(i.includes("beego/beego")||i.includes("astaxie/beego"))&&e("fw:beego"),i.includes("gobuffalo/buffalo")&&e("fw:buffalo");}if(n("Cargo.toml")){let i=c("Cargo.toml").toLowerCase();i.includes("actix-web")&&e("fw:actix"),i.includes("axum")&&e("fw:axum"),i.includes("rocket")&&e("fw:rocket"),i.includes("warp")&&e("fw:warp"),i.includes("tonic")&&e("fw:tonic"),i.includes("leptos")&&e("fw:leptos"),i.includes("yew")&&e("fw:yew"),i.includes("tauri")&&e("fw:tauri"),i.includes("dioxus")&&e("fw:dioxus"),i.includes("bevy")&&e("fw:bevy");}if(n("pom.xml")||n("build.gradle")||n("build.gradle.kts")){let i=(c("pom.xml")+c("build.gradle")+c("build.gradle.kts")).toLowerCase();(i.includes("spring-boot")||i.includes("springframework"))&&e("fw:spring"),i.includes("quarkus")&&e("fw:quarkus"),i.includes("micronaut")&&e("fw:micronaut"),(i.includes("io.ktor")||i.includes("ktor-"))&&e("fw:ktor"),(i.includes("vertx")||i.includes("vert.x"))&&e("fw:vertx"),(i.includes("com.android")||i.includes("androidx"))&&e("fw:android"),(i.includes("androidx.compose")||i.includes("jetpack"))&&e("fw:jetpack-compose"),(i.includes("kotlin-multiplatform")||i.includes('kotlin("multiplatform")'))&&e("fw:kotlin-multiplatform");}if(n("Gemfile")){let i=c("Gemfile").toLowerCase();i.includes("rails")&&e("fw:rails"),i.includes("sinatra")&&e("fw:sinatra"),i.includes("hanami")&&e("fw:hanami");}if(n("composer.json")){let i=c("composer.json").toLowerCase();(i.includes("laravel/framework")||i.includes("laravel/laravel"))&&e("fw:laravel"),i.includes("symfony/")&&e("fw:symfony"),i.includes("drupal/")&&e("fw:drupal"),i.includes("codeigniter")&&e("fw:codeigniter"),i.includes("slim/slim")&&e("fw:slim");}(n("wp-config.php")||n("wp-load.php")||n("wp-content"))&&e("fw:wordpress"),n("pubspec.yaml")&&c("pubspec.yaml").toLowerCase().includes("flutter")&&e("fw:flutter");{let i=r.filter(b=>b.endsWith(".csproj"));if(i.length>0){let b=i.map(g=>c(g)).join(`
|
|
4
|
-
`).toLowerCase();(b.includes("microsoft.net.sdk.web")||b.includes("microsoft.aspnetcore"))&&e("fw:aspnet"),b.includes("blazor")&&e("fw:blazor"),(b.includes("microsoft.net.sdk.maui")||b.includes("usemaui"))&&e("fw:maui");}}(n("ProjectSettings")||r.includes("Assembly-CSharp.csproj"))&&e("fw:unity"),n("project.godot")&&e("fw:godot");{let i=c("Package.swift").toLowerCase();i.includes("swiftui")&&e("fw:swiftui"),i.includes("uikit")&&e("fw:uikit");}let s=i=>r.some(b=>b===i||b.startsWith(i+"."));s("next.config")&&e("fw:nextjs"),s("nuxt.config")&&e("fw:nuxt"),s("astro.config")&&e("fw:astro"),s("svelte.config")&&e("fw:svelte"),s("remix.config")&&e("fw:remix"),s("gatsby-config")&&e("fw:gatsby"),s("vite.config")&&e("fw:vite"),s("vue.config")&&e("fw:vue"),s("qwik.config")&&e("fw:qwik"),n("angular.json")&&e("fw:angular"),s("capacitor.config")&&e("fw:capacitor"),s("ionic.config")&&e("fw:ionic"),n("app.json")&&c("app.json").toLowerCase().includes('"expo"')&&e("fw:expo");}{if((a("pg")||a("postgres")||a("pg-promise")||a("@vercel/postgres"))&&e("infra:postgres"),(a("mysql")||a("mysql2"))&&e("infra:mysql"),a("mariadb")&&e("infra:mariadb"),(a("redis")||a("ioredis"))&&e("infra:redis"),(a("mongodb")||a("mongoose"))&&e("infra:mongodb"),a("mongoose")&&e("infra:mongoose"),(a("better-sqlite3")||a("sqlite3")||a("sqlite"))&&e("infra:sqlite"),a("@libsql/client")&&e("infra:libsql"),a("cassandra-driver")&&e("infra:cassandra"),(a("@elastic/elasticsearch")||a("elasticsearch"))&&e("infra:elasticsearch"),a("@opensearch-project/opensearch")&&e("infra:opensearch"),(a("@clickhouse/client")||a("clickhouse"))&&e("infra:clickhouse"),(a("duckdb")||a("@duckdb/node-api"))&&e("infra:duckdb"),a("neo4j-driver")&&e("infra:neo4j"),a("@influxdata/influxdb-client")&&e("infra:influxdb"),a("snowflake-sdk")&&e("infra:snowflake"),a("@google-cloud/bigquery")&&e("infra:bigquery"),(a("firebase-admin")||a("@google-cloud/firestore"))&&e("infra:firestore"),(a("faunadb")||a("fauna"))&&e("infra:fauna"),(a("surrealdb")||a("surrealdb.js"))&&e("infra:surrealdb"),a("@qdrant/js-client-rest")&&e("infra:qdrant"),a("@pinecone-database/pinecone")&&e("infra:pinecone"),(a("weaviate-ts-client")||a("weaviate-client"))&&e("infra:weaviate"),a("chromadb")&&e("infra:chromadb"),a("@zilliz/milvus2-sdk-node")&&e("infra:milvus"),(a("@prisma/client")||a("prisma"))&&e("infra:prisma"),a("drizzle-orm")&&e("infra:drizzle"),a("typeorm")&&e("infra:typeorm"),(a("aws-sdk")||d("@aws-sdk/"))&&e("infra:aws"),(d("@google-cloud/")||a("googleapis"))&&e("infra:gcp"),d("@azure/")&&e("infra:azure"),(d("@cloudflare/")||a("wrangler"))&&e("infra:cloudflare"),(a("@vercel/node")||a("@vercel/kv")||a("@vercel/blob"))&&e("infra:vercel"),(a("firebase")||a("firebase-admin"))&&e("infra:firebase"),a("@supabase/supabase-js")&&e("infra:supabase"),a("@neondatabase/serverless")&&e("infra:neon"),a("@planetscale/database")&&e("infra:planetscale"),d("@upstash/")&&e("infra:upstash"),a("@tursodatabase/api")&&e("infra:turso"),a("modal")&&e("infra:modal"),a("replicate")&&e("infra:replicate"),(a("kafkajs")||a("node-rdkafka"))&&e("infra:kafka"),(a("amqplib")||a("rabbitmq-client"))&&e("infra:rabbitmq"),a("nats")&&e("infra:nats"),(d("@aws-sdk/client-sqs")||a("sqs-consumer"))&&e("infra:sqs"),a("@google-cloud/pubsub")&&e("infra:pubsub"),d("@temporalio/")&&e("infra:temporal"),(a("bullmq")||a("bull"))&&e("infra:bullmq"),d("@sentry/")&&e("infra:sentry"),(d("@datadog/")||a("dd-trace"))&&e("infra:datadog"),d("@opentelemetry/")&&e("infra:opentelemetry"),a("newrelic")&&e("infra:newrelic"),(a("posthog-node")||a("posthog-js"))&&e("infra:posthog"),d("@honeycombio/")&&e("infra:honeycomb"),a("prom-client")&&e("infra:prometheus"),(a("stripe")||a("@stripe/stripe-js"))&&e("infra:stripe"),d("@paddle/")&&e("infra:paddle"),d("@clerk/")&&e("infra:clerk"),(a("auth0")||d("@auth0/"))&&e("infra:auth0"),(a("next-auth")||d("@auth/"))&&e("infra:nextauth"),a("twilio")&&e("infra:twilio"),a("@sendgrid/mail")&&e("infra:sendgrid"),a("resend")&&e("infra:resend"),a("postmark")&&e("infra:postmark"),d("@pulumi/")&&e("infra:pulumi"),n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile")){let i=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")).toLowerCase();(i.includes("psycopg")||i.includes("asyncpg"))&&e("infra:postgres"),(i.includes("pymysql")||i.includes("aiomysql")||i.includes("mysqlclient"))&&e("infra:mysql"),(i.includes("redis")||i.includes("aioredis"))&&e("infra:redis"),(i.includes("pymongo")||i.includes("motor")||i.includes("mongoengine"))&&e("infra:mongodb"),i.includes("elasticsearch")&&e("infra:elasticsearch"),i.includes("clickhouse")&&e("infra:clickhouse"),i.includes("duckdb")&&e("infra:duckdb"),i.includes("neo4j")&&e("infra:neo4j"),i.includes("snowflake")&&e("infra:snowflake"),i.includes("qdrant-client")&&e("infra:qdrant"),i.includes("pinecone")&&e("infra:pinecone"),i.includes("chromadb")&&e("infra:chromadb"),i.includes("pymilvus")&&e("infra:milvus"),i.includes("sqlalchemy")&&e("infra:sqlalchemy"),(i.includes("boto3")||i.includes("botocore"))&&e("infra:aws"),i.includes("google-cloud")&&e("infra:gcp"),i.includes("azure-")&&e("infra:azure"),i.includes("supabase")&&e("infra:supabase"),(i.includes("confluent-kafka")||i.includes("aiokafka")||i.includes("kafka-python"))&&e("infra:kafka"),(i.includes("pika")||i.includes("aio-pika"))&&e("infra:rabbitmq"),i.includes("temporalio")&&e("infra:temporal"),i.includes("sentry-sdk")&&e("infra:sentry"),(i.includes("ddtrace")||i.includes("datadog"))&&e("infra:datadog"),i.includes("opentelemetry")&&e("infra:opentelemetry"),i.includes("stripe")&&e("infra:stripe"),i.includes("twilio")&&e("infra:twilio"),i.includes("pulumi")&&e("infra:pulumi"),i.includes("ansible")&&e("infra:ansible");}if(n("go.mod")){let i=c("go.mod").toLowerCase();(i.includes("lib/pq")||i.includes("jackc/pgx"))&&e("infra:postgres"),i.includes("go-sql-driver/mysql")&&e("infra:mysql"),(i.includes("go-redis")||i.includes("redis/go-redis"))&&e("infra:redis"),i.includes("go.mongodb.org/mongo-driver")&&e("infra:mongodb"),i.includes("aws/aws-sdk-go")&&e("infra:aws"),i.includes("cloud.google.com/go")&&e("infra:gcp"),(i.includes("segmentio/kafka-go")||i.includes("sarama"))&&e("infra:kafka"),i.includes("getsentry/sentry-go")&&e("infra:sentry"),i.includes("go.opentelemetry.io")&&e("infra:opentelemetry"),i.includes("stripe/stripe-go")&&e("infra:stripe"),i.includes("hashicorp/terraform")&&e("infra:terraform"),i.includes("k8s.io/client-go")&&e("infra:kubernetes");}(n("Dockerfile")||n("docker-compose.yml")||n("docker-compose.yaml")||n("compose.yaml")||n("compose.yml")||n(".dockerignore"))&&e("infra:docker"),(n("Containerfile")||n("podman-compose.yml"))&&e("infra:podman"),r.some(i=>i.endsWith(".tf")||i===".terraform.lock.hcl")&&e("infra:terraform"),(n("Pulumi.yaml")||n("Pulumi.yml"))&&e("infra:pulumi"),(n("ansible.cfg")||n("playbook.yml")||n("playbook.yaml"))&&e("infra:ansible"),(n("kustomization.yaml")||n("kustomization.yml")||n("k8s")||n("kubernetes")||n("skaffold.yaml"))&&e("infra:kubernetes"),(n("Chart.yaml")||n("helmfile.yaml"))&&(e("infra:helm"),e("infra:kubernetes")),r.some(i=>i.endsWith(".nomad")||i.endsWith(".nomad.hcl"))&&e("infra:nomad"),(n("vercel.json")||n(".vercel"))&&e("infra:vercel"),(n("netlify.toml")||n(".netlify"))&&e("infra:netlify"),n("fly.toml")&&e("infra:fly"),(n("railway.json")||n("railway.toml"))&&e("infra:railway"),n("render.yaml")&&e("infra:render"),n("Procfile")&&e("infra:heroku"),(n("wrangler.toml")||n("wrangler.jsonc")||n("wrangler.json"))&&e("infra:cloudflare"),n("supabase")&&e("infra:supabase"),(n("firebase.json")||n(".firebaserc"))&&e("infra:firebase"),(n("serverless.yml")||n("serverless.yaml")||n("template.yaml")||n("samconfig.toml"))&&e("infra:aws"),(n("prisma")||n("schema.prisma"))&&e("infra:prisma"),(n("drizzle.config.ts")||n("drizzle.config.js"))&&e("infra:drizzle");let s=false;try{s=n(".github")&&h__namespace.existsSync(y__namespace.join(t,".github","workflows"));}catch{s=false;}s&&e("infra:github-actions"),(n(".gitlab-ci.yml")||n(".gitlab-ci.yaml"))&&e("infra:gitlab-ci"),n(".circleci")&&e("infra:circleci"),n("Jenkinsfile")&&e("infra:jenkins");{let i=(c("Dockerfile")+c("docker-compose.yml")+c("docker-compose.yaml")+c("compose.yaml")+c("compose.yml")).toLowerCase();i&&((i.includes("postgres")||i.includes("pgvector"))&&e("infra:postgres"),i.includes("timescale")&&e("infra:timescaledb"),i.includes("mysql")&&e("infra:mysql"),i.includes("mariadb")&&e("infra:mariadb"),i.includes("redis")&&e("infra:redis"),i.includes("mongo")&&e("infra:mongodb"),i.includes("cassandra")&&e("infra:cassandra"),i.includes("cockroach")&&e("infra:cockroachdb"),i.includes("clickhouse")&&e("infra:clickhouse"),i.includes("elasticsearch")&&e("infra:elasticsearch"),i.includes("neo4j")&&e("infra:neo4j"),i.includes("qdrant")&&e("infra:qdrant"),i.includes("rabbitmq")&&e("infra:rabbitmq"),(i.includes("kafka")||i.includes("redpanda"))&&e("infra:kafka"),i.includes("nats")&&e("infra:nats"),i.includes("grafana")&&e("infra:grafana"),(i.includes("prometheus")||i.includes("prom/"))&&e("infra:prometheus"));}}{let i=(...w)=>w.some(a),b=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")+c("environment.yml")).toLowerCase(),g=c("go.mod").toLowerCase(),m=c("Cargo.toml").toLowerCase(),l=w=>b.includes(w),I=w=>r.some(fe=>fe.toLowerCase().endsWith(w)),k=(...w)=>w.some(fe=>n(fe)),j=()=>Array.from(o).some(w=>w.startsWith("type:")),le=()=>Array.from(o).some(w=>w.startsWith("fw:"));(a("@modelcontextprotocol/sdk")||l("modelcontextprotocol")||l("fastmcp")||g.includes("modelcontextprotocol")||k("mcp.json",".mcp.json"))&&e("type:mcp-server"),(i("langgraph","@langchain/langgraph","crewai","autogen","@mastra/core","@openai/agents","@langchain/core")||l("langgraph")||l("crewai")||l("autogen")||l("pyautogen")||l("smolagents")||l("haystack"))&&e("type:agent-framework"),(i("ai","openai","@anthropic-ai/sdk","@google/generative-ai","@ai-sdk/openai","@ai-sdk/anthropic","langchain","@huggingface/inference","cohere-ai","ollama","groq-sdk","@mistralai/mistralai")||l("openai")||l("anthropic")||l("langchain")||l("litellm")||l("google-generativeai")||l("cohere")||l("ollama"))&&e("type:ai-app"),(I(".sol")||k("hardhat.config.js","hardhat.config.ts","foundry.toml","truffle-config.js","Anchor.toml","Move.toml")||i("hardhat","ethers","web3","@solana/web3.js","wagmi","viem","@openzeppelin/contracts"))&&e("type:smart-contract"),(k("project.godot","ProjectSettings")||I(".unity")||I(".uproject")||i("phaser","kaplay","kaboom","excalibur","playcanvas")||m.includes("bevy")||m.includes("macroquad")||m.includes("ggez")||l("pygame")||l("arcade"))&&e("type:game");{let w=f("manifest.json");(w&&Object.prototype.hasOwnProperty.call(w,"manifest_version")||i("webextension-polyfill","@types/chrome","wxt","plasmo"))&&e("type:browser-extension");}(i("react-native","expo","nativescript")||n("pubspec.yaml")||I(".xcodeproj")||k("AndroidManifest.xml"))&&e("type:mobile-app"),(i("electron","@tauri-apps/api","@tauri-apps/cli","nw")||k("tauri.conf.json","src-tauri")||m.includes("tauri")||m.includes("egui")||l("pyqt5")||l("pyqt6")||l("pyside6")||l("kivy"))&&e("type:desktop-app"),(i("discord.js","telegraf","node-telegram-bot-api","@slack/bolt","probot","grammy")||l("discord.py")||l("python-telegram-bot")||l("slack-bolt")||l("slack_bolt")||l("aiogram")||l("pyrogram"))&&e("type:bot"),(k("dbt_project.yml","dagster.yaml")||i("@dagster-io/dagster","apache-airflow")||l("airflow")||l("dagster")||l("prefect")||l("dbt-core")||l("luigi")||l("kedro")||l("pyspark")||l("apache-beam"))&&e("type:data-pipeline"),(l("torch")||l("tensorflow")||l("keras")||l("jax")||l("scikit-learn")||l("sklearn")||l("xgboost")||l("lightgbm")||l("pytorch-lightning")||l("diffusers")||l("mlflow"))&&e("type:ml-model"),(I(".ipynb")||l("jupyter")||l("jupyterlab")||l("marimo")||n("notebooks"))&&e("type:notebook"),(k("mkdocs.yml","mkdocs.yaml","mint.json","docusaurus.config.js","docusaurus.config.ts","book.toml")||i("@docusaurus/core","vitepress","vuepress","nextra","@astrojs/starlight")||l("mkdocs")||l("sphinx"))&&e("type:documentation"),(k("hugo.toml","_config.yml",".eleventy.js","eleventy.config.js","astro.config.mjs","astro.config.ts","astro.config.js")||i("astro","gatsby","@11ty/eleventy","hexo","gridsome")||l("pelican"))&&e("type:static-site"),i("@medusajs/medusa","@saleor/sdk","@shopify/hydrogen","vendure","@vendure/core","snipcart","use-shopping-cart","swell-js")&&e("type:ecommerce"),(p.bin||i("commander","yargs","oclif","@oclif/core","cac","meow","inquirer","@clack/prompts","ink")||l("click")||l("typer")||l("docopt")||g.includes("spf13/cobra")||g.includes("urfave/cli")||m.includes("clap")||m.includes("structopt"))&&e("type:cli"),(k("pnpm-workspace.yaml","turbo.json","nx.json","lerna.json","rush.json")||Array.isArray(p.workspaces)||m.includes("[workspace]")||n("go.work"))&&e("type:monorepo");let T=i("next","react","vue","@angular/core","svelte","@sveltejs/kit","solid-js","nuxt","remix","@remix-run/react","preact","qwik"),R=i("express","fastify","@nestjs/core","koa","hapi","@hapi/hapi","hono")||l("fastapi")||l("django")||l("flask")||l("starlette")||l("sanic")||g.includes("gin-gonic/gin")||g.includes("labstack/echo")||g.includes("gofiber/fiber")||m.includes("axum")||m.includes("actix-web")||(c("pom.xml")+c("build.gradle")).toLowerCase().includes("spring-boot"),je=Array.from(o).some(w=>["infra:postgres","infra:mysql","infra:mongodb","infra:supabase","infra:neon"].includes(w)),Re=i("next-auth","@clerk/nextjs","@auth0/auth0-react","passport","lucia","@workos-inc/node")||l("django-allauth")||l("flask-login"),Ee=i("stripe","@stripe/stripe-js","@paddle/paddle-js","@lemonsqueezy/lemonsqueezy.js")||l("stripe");(!T&&!R&&(p.main||p.exports||p.module||p.types||p.publishConfig)||n("Cargo.toml")&&!m.includes("[[bin]]")&&m.includes("[lib]")||k("LICENSE","LICENSE.md","LICENSE.txt")&&!T&&!R&&!j())&&!j()&&e("type:library"),T?(je&&(Re||Ee)&&e("type:saas"),e("type:web-app")):R&&(je&&(Re||Ee)&&e("type:saas"),e("type:api-service")),j()||(le()?e("type:web-app"):k("Dockerfile","docker-compose.yml","compose.yaml")||r.some(w=>w.endsWith(".tf"))||k("Chart.yaml","kustomization.yaml","wrangler.toml","serverless.yml",".github")||i("@pulumi/pulumi","aws-cdk-lib","cdktf")?e("type:devops-tool"):n("package.json")&&(p.main||p.exports)&&e("type:library"));}return Array.from(o)}function De(t){let o={sponsorLabel:t.sponsorLabel,title:t.creative.title,body:t.creative.body,url:t.clickUrl};return t.creative.cta!==void 0&&(o.cta=t.creative.cta),o}function We(t){return {sponsorLabel:"",title:t.title,body:t.body,url:t.url}}function Y(t){let o=De(t),e=t.creative;switch(e.format){case "image":case "gif":return {...o,body:e.textFallback??o.body};case "video":return {...o,body:e.textFallback??o.body,cta:o.cta??"\u25B6 Watch"};case "audio":return {...o,body:e.textFallback??o.body,cta:o.cta??"\u{1F50A} Listen"};default:return o}}function U(t=process.env){return y__namespace.join(N__namespace.homedir(),".config","opencrater")}function X(t=process.env){return y__namespace.join(U(t),"state.json")}function V(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function E(t){return typeof t=="number"&&Number.isFinite(t)}var Be=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function Ue(t){for(let o=0;;o++)try{return {text:h__namespace.readFileSync(t,"utf8")}}catch(e){let r=e.code??"";if(!(r==="ENOENT"||Be.has(r)))return {locked:true};if(o>=4)return r==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(o+1));}catch{}}}function vt(t){if(typeof t!="object"||t===null)return null;let o=t;return !E(o.minIntervalSeconds)||!E(o.serveTimeoutMs)||!E(o.preloadPoolSize)||typeof o.killSwitch!="boolean"?null:{minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:o.preloadPoolSize,killSwitch:o.killSwitch,displayDurationSeconds:E(o.displayDurationSeconds)?o.displayDurationSeconds:25,minSdkVersion:typeof o.minSdkVersion=="string"?o.minSdkVersion:""}}function xt(t){if(!Array.isArray(t))return [];let o=[];for(let e of t){if(typeof e!="object"||e===null)continue;let r=e,n=r.blip;if(!E(r.renderBy)||typeof n!="object"||n===null||typeof n.impressionId!="string"||typeof n.clickUrl!="string"||typeof n.sponsorLabel!="string"||typeof n.creative!="object"||n.creative===null)continue;let c=n.creative;typeof c.title!="string"||typeof c.body!="string"||o.push({blip:{impressionId:n.impressionId,...typeof n.campaignId=="string"?{campaignId:n.campaignId}:{},clickUrl:n.clickUrl,sponsorLabel:n.sponsorLabel,creative:{format:"text",title:c.title,body:c.body,...typeof c.cta=="string"?{cta:c.cta}:{}}},renderBy:r.renderBy});}return o}function Ct(t){if(typeof t!="object"||t===null||Array.isArray(t))return {};let o={};for(let[e,r]of Object.entries(t)){if(!Array.isArray(r))continue;let n=r.filter(c=>typeof c=="string"&&c.length<=64);o[e]=n.slice(0,64);}return o}function Tt(t){if(!Array.isArray(t))return [];let o=[];for(let e of t){if(typeof e!="object"||e===null)continue;let r=e;if(!(typeof r.topic!="string"||!E(r.at))&&(o.push({topic:r.topic.slice(0,32),at:r.at}),o.length>=24))break}return o}function jt(t){if(!Array.isArray(t))return [];let o=[],e=new Set;for(let r of t){if(typeof r!="object"||r===null)continue;let n=r;if(typeof n.key!="string"||typeof n.package!="string"||n.key===""||n.package==="")continue;let c=`${n.package}\0${n.key}`;if(!e.has(c)&&(e.add(c),o.push({key:n.key,package:n.package}),o.length>=32))break}return o}function Rt(t){if(typeof t!="object"||t===null)return null;let o=t,e={};if(typeof o.savedEnv=="object"&&o.savedEnv!==null)for(let[r,n]of Object.entries(o.savedEnv))(typeof n=="string"||n===null)&&(e[r]=n);return {active:o.active===true,savedEnv:e}}function Et(t){if(typeof t!="object"||t===null)return null;let o=t,e=r=>E(r)&&r>=0?r:0;return {turns:e(o.turns),lastLimitAt:e(o.lastLimitAt),lastDepletedAt:e(o.lastDepletedAt),lastBackupAt:e(o.lastBackupAt)}}function Ot(t){let o=t.attrTagsAt,e=t.attrTagsCwd;return !E(o)||Date.now()-o>K||typeof e!="string"||e.length===0||e.length>64?{}:{attrTags:Array.isArray(t.attrTags)?t.attrTags.filter(n=>typeof n=="string"&&n.length<=40).slice(0,48):[],attrTagsCwd:e,attrTagsAt:o}}function At(t){let o=V();if(typeof t!="object"||t===null)return o;let e=t;return {installId:typeof e.installId=="string"&&e.installId.length>0?e.installId:o.installId,lastShownAt:E(e.lastShownAt)&&e.lastShownAt>=0?e.lastShownAt:0,optOut:e.optOut===true,disclosureShown:e.disclosureShown===true,cachedConfig:vt(e.cachedConfig),allowedPlacements:Ct(e.allowedPlacements),sessionTopics:Tt(e.sessionTopics),integrations:jt(e.integrations),devToken:typeof e.devToken=="string"?e.devToken:null,computeRouting:Rt(e.computeRouting),computeCards:Et(e.computeCards),configFetchedAt:E(e.configFetchedAt)&&e.configFetchedAt>=0?e.configFetchedAt:0,pool:xt(e.pool),...Ot(e)}}function de(t=process.env){let o=X(t),e=Ue(o);if(e.text!==void 0)try{return At(JSON.parse(e.text))}catch{let r=V();try{C(r,t);}catch{}return r}if(e.missing){let r=V();try{C(r,t);}catch{}return r}return V()}function C(t,o=process.env,e={}){let r=X(o),n=y__namespace.dirname(r);h__namespace.mkdirSync(n,{recursive:true});let c=Ue(r),f=null;if(c.text!==void 0)try{f=JSON.parse(c.text);}catch{f=null;}if(f)typeof f.lastShownAt=="number"&&f.lastShownAt>t.lastShownAt&&(t={...t,lastShownAt:f.lastShownAt}),!e.allowClearToken&&typeof f.devToken=="string"&&t.devToken==null&&(t={...t,devToken:f.devToken}),typeof f.installId=="string"&&f.installId.length>0&&f.installId!==t.installId&&(t={...t,installId:f.installId});else if(!e.allowClearToken&&t.devToken==null&&c.text===void 0&&!c.missing)return;let p=y__namespace.join(n,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);h__namespace.writeFileSync(p,JSON.stringify(t,null,2)+`
|
|
5
|
-
`,"utf8");for(let u=0;;u++)try{h__namespace.renameSync(p,r);return}catch(a){let d=a.code??"";if(u>=4||!
|
|
6
|
-
`,"utf8"),h__namespace.renameSync(r,t);}function
|
|
2
|
+
'use strict';var child_process=require('child_process'),h=require('fs'),N=require('os'),y=require('path'),crypto=require('crypto');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var h__namespace=/*#__PURE__*/_interopNamespace(h);var N__namespace=/*#__PURE__*/_interopNamespace(N);var y__namespace=/*#__PURE__*/_interopNamespace(y);var M=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(o,e)=>(typeof require<"u"?require:o)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""},_e={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],antigravity:["Stop"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]},Ie={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],antigravity:["PreToolUse","PostToolUse","PreInvocation","PostInvocation","Stop"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var A="1.4.1";var yt="https://api.opencrater.to";function J(t,o=process.env){let e=o.OPENCRATER_API_ORIGIN;return ((e&&e.trim()!==""?e:yt)).replace(/\/+$/,"")}function x(...t){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...t);try{let o=M("os"),e=M("fs"),r=M("path");e.appendFileSync(r.join(o.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${t.map(n=>String(n)).join(" ")}
|
|
3
|
+
`);}catch{}}catch{}}function z(t){return typeof t=="number"&&Number.isFinite(t)}function bt(t){let o=H;if(typeof t!="object"||t===null)return {...o};let e=t;return {minIntervalSeconds:z(e.minIntervalSeconds)?e.minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:z(e.serveTimeoutMs)?e.serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:z(e.preloadPoolSize)?e.preloadPoolSize:o.preloadPoolSize,killSwitch:e.killSwitch===true,displayDurationSeconds:z(e.displayDurationSeconds)?e.displayDurationSeconds:o.displayDurationSeconds,minSdkVersion:typeof e.minSdkVersion=="string"?e.minSdkVersion:o.minSdkVersion}}async function Pe(t,o,e,r,n){try{let c=await fetch(`${t}${o}`,{method:"POST",headers:{"content-type":"application/json",...n??{}},body:JSON.stringify(e),signal:AbortSignal.timeout(r)});return c.ok?await c.json():(x(`POST ${o} -> HTTP ${c.status}`),null)}catch(c){return x(`POST ${o} failed:`,c),null}}function Ne(t,o){let e=t.host??"generic";return {publisherKey:t.publisherKey,packageName:t.packageName,placement:t.placement,host:e,sdkVersion:A,installId:o.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:o.topics&&o.topics.length>0?o.topics:void 0,tags:o.tags&&o.tags.length>0?o.tags:void 0}}function $e(t){if(typeof t!="object"||t===null)return null;let o=t;if(typeof o.fill!="boolean")return null;let e={fill:o.fill,fallback:o.fallback??null,config:bt(o.config),...Array.isArray(o.allowedPlacements)?{allowedPlacements:o.allowedPlacements.filter(r=>typeof r=="string")}:{}};return o.blip!==void 0&&o.blip!==null&&(e.blip=o.blip),typeof o.computeBalanceMicroUsd=="number"&&(e.computeBalanceMicroUsd=o.computeBalanceMicroUsd),typeof o.weeklyGrantMicroUsd=="number"&&(e.weeklyGrantMicroUsd=o.weeklyGrantMicroUsd),typeof o.pendingMicroUsd=="number"&&(e.pendingMicroUsd=o.pendingMicroUsd),e}async function Me(t,o){let e=await Pe(o.origin,"/v1/serve",Ne(t,o),o.timeoutMs);return $e(e)}async function Le(t,o,e){let r={...Ne(o,e),publisherKey:o.publisherKey??"",packageName:o.packageName??""},n=await Pe(e.origin,"/v1/dev/serve",r,e.timeoutMs,{authorization:`Bearer ${t}`});return $e(n)}var wt=48,K=360*60*1e3;function De(t){return crypto.createHash("sha256").update(t).digest("hex").slice(0,16)}function We(t){let o=new Set,e=s=>{o.size<wt&&o.add(s);},r=[];try{r=h__namespace.readdirSync(t);}catch{return []}let n=s=>r.includes(s),c=s=>{try{return h__namespace.readFileSync(y__namespace.join(t,s),"utf8")}catch{return ""}},f=s=>{try{return JSON.parse(c(s))}catch{return null}},p=f("package.json")??{},u={...p.dependencies??{},...p.devDependencies??{},...p.peerDependencies??{}},a=s=>Object.prototype.hasOwnProperty.call(u,s),d=s=>Object.keys(u).some(i=>i===s||i.startsWith(s));n("package.json")&&(e("lang:javascript"),(a("typescript")||n("tsconfig.json"))&&e("lang:typescript")),(n("deno.json")||n("deno.jsonc"))&&e("lang:typescript"),(n("tsconfig.json")||n("tsconfig.base.json"))&&e("lang:typescript"),n("jsconfig.json")&&e("lang:javascript"),(n("bun.lockb")||n("bun.lock"))&&e("lang:javascript"),r.some(s=>s.endsWith(".ts")||s.endsWith(".tsx")||s.endsWith(".mts")||s.endsWith(".cts"))&&e("lang:typescript"),r.some(s=>s.endsWith(".js")||s.endsWith(".jsx")||s.endsWith(".mjs")||s.endsWith(".cjs"))&&e("lang:javascript"),(n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile"))&&e("lang:python"),(n("setup.cfg")||n("Pipfile.lock")||n("poetry.lock")||n("uv.lock")||n("environment.yml"))&&e("lang:python"),r.some(s=>s.endsWith(".py")||s.endsWith(".pyi")||s.endsWith(".ipynb"))&&e("lang:python"),(n("go.mod")||n("go.sum")||n("go.work"))&&e("lang:go"),r.some(s=>s.endsWith(".go"))&&e("lang:go"),(n("Cargo.toml")||n("Cargo.lock"))&&e("lang:rust"),r.some(s=>s.endsWith(".rs"))&&e("lang:rust"),(n("pom.xml")||n("build.gradle"))&&e("lang:java"),r.some(s=>s.endsWith(".java"))&&e("lang:java"),(n("build.gradle.kts")||n("settings.gradle.kts"))&&e("lang:kotlin"),r.some(s=>s.endsWith(".kt")||s.endsWith(".kts"))&&e("lang:kotlin"),(n("build.sbt")||n(".scalafmt.conf"))&&e("lang:scala"),r.some(s=>s.endsWith(".scala")||s.endsWith(".sc"))&&e("lang:scala"),r.some(s=>s.endsWith(".groovy")||s.endsWith(".gradle"))&&e("lang:groovy"),(n("deps.edn")||n("project.clj")||n("shadow-cljs.edn"))&&e("lang:clojure"),r.some(s=>s.endsWith(".clj")||s.endsWith(".cljs")||s.endsWith(".cljc"))&&e("lang:clojure"),r.some(s=>s.endsWith(".csproj")||s.endsWith(".sln"))&&e("lang:csharp"),r.some(s=>s.endsWith(".fsproj"))&&e("lang:fsharp"),r.some(s=>s.endsWith(".cs"))&&e("lang:csharp"),r.some(s=>s.endsWith(".fs")||s.endsWith(".fsx")||s.endsWith(".fsi"))&&e("lang:fsharp"),r.some(s=>s.endsWith(".cpp")||s.endsWith(".cc")||s.endsWith(".cxx")||s.endsWith(".hpp")||s.endsWith(".hxx"))&&e("lang:cpp"),r.some(s=>s.endsWith(".c"))&&e("lang:c"),(n("composer.json")||n("composer.lock"))&&e("lang:php"),r.some(s=>s.endsWith(".php"))&&e("lang:php"),(n("Gemfile")||n("Gemfile.lock")||n(".ruby-version")||r.some(s=>s.endsWith(".gemspec")))&&e("lang:ruby"),r.some(s=>s.endsWith(".rb")||s==="Rakefile")&&e("lang:ruby"),(n("Package.swift")||n("Podfile")||r.some(s=>s.endsWith(".xcodeproj")||s.endsWith(".xcworkspace")))&&e("lang:swift"),r.some(s=>s.endsWith(".swift"))&&e("lang:swift"),r.some(s=>s.endsWith(".m")||s.endsWith(".mm"))&&e("lang:objective-c"),(n("pubspec.yaml")||n("pubspec.yml")||n("pubspec.lock"))&&e("lang:dart"),r.some(s=>s.endsWith(".dart"))&&e("lang:dart"),(n("mix.exs")||n("mix.lock"))&&e("lang:elixir"),r.some(s=>s.endsWith(".ex")||s.endsWith(".exs"))&&e("lang:elixir"),(n("rebar.config")||n("rebar.lock"))&&e("lang:erlang"),r.some(s=>s.endsWith(".erl")||s.endsWith(".hrl"))&&e("lang:erlang"),(n("gleam.toml")||r.some(s=>s.endsWith(".gleam")))&&e("lang:gleam"),(n("stack.yaml")||n("cabal.project")||r.some(s=>s.endsWith(".cabal")||s.endsWith(".hs")))&&e("lang:haskell"),(n("dune-project")||n("dune")||r.some(s=>s.endsWith(".ml")||s.endsWith(".mli")))&&e("lang:ocaml"),(r.some(s=>s.endsWith(".rockspec")||s.endsWith(".lua"))||n(".luarc.json"))&&e("lang:lua"),(n("cpanfile")||n("Makefile.PL")||r.some(s=>s.endsWith(".pl")||s.endsWith(".pm")))&&e("lang:perl"),(n("DESCRIPTION")||n("renv.lock")||r.some(s=>s.endsWith(".Rproj")||s.endsWith(".Rmd")||s.endsWith(".R")))&&e("lang:r"),(n("Project.toml")||n("Manifest.toml")||r.some(s=>s.endsWith(".jl")))&&e("lang:julia"),(n("build.zig")||n("build.zig.zon")||r.some(s=>s.endsWith(".zig")))&&e("lang:zig"),r.some(s=>s.endsWith(".nimble")||s.endsWith(".nim"))&&e("lang:nim"),(n("shard.yml")||n("shard.lock")||r.some(s=>s.endsWith(".cr")))&&e("lang:crystal"),(n("v.mod")||r.some(s=>s.endsWith(".vsh")))&&e("lang:vlang"),r.some(s=>s.endsWith(".hx")||s.endsWith(".hxml"))&&e("lang:haxe"),(n("foundry.toml")||n("hardhat.config.js")||n("hardhat.config.ts")||r.some(s=>s.endsWith(".sol")))&&e("lang:solidity"),r.some(s=>s.endsWith(".f")||s.endsWith(".f90")||s.endsWith(".f95"))&&e("lang:fortran"),r.some(s=>s.endsWith(".cob")||s.endsWith(".cbl"))&&e("lang:cobol"),r.some(s=>s.endsWith(".asm"))&&e("lang:assembly"),r.some(s=>s.endsWith(".sh")||s.endsWith(".bash")||s.endsWith(".zsh"))&&e("lang:shell"),r.some(s=>s.endsWith(".ps1")||s.endsWith(".psm1"))&&e("lang:powershell"),r.some(s=>s.endsWith(".sql"))&&e("lang:sql"),r.some(s=>s.endsWith(".html")||s.endsWith(".htm"))&&e("lang:html"),r.some(s=>s.endsWith(".css"))&&e("lang:css"),r.some(s=>s.endsWith(".scss")||s.endsWith(".sass"))&&e("lang:scss"),r.some(s=>s.endsWith(".graphql")||s.endsWith(".gql"))&&e("lang:graphql"),r.some(s=>s.endsWith(".proto"))&&e("lang:protobuf");{if(a("react")&&e("fw:react"),a("next")&&e("fw:nextjs"),a("vue")&&e("fw:vue"),(a("nuxt")||a("nuxt3"))&&e("fw:nuxt"),a("@angular/core")&&e("fw:angular"),a("svelte")&&e("fw:svelte"),a("@sveltejs/kit")&&e("fw:sveltekit"),(a("@remix-run/react")||a("@remix-run/node"))&&e("fw:remix"),a("astro")&&e("fw:astro"),a("gatsby")&&e("fw:gatsby"),a("solid-js")&&e("fw:solid"),(a("@solidjs/start")||a("solid-start"))&&e("fw:solidstart"),(a("@builder.io/qwik")||a("@qwik.dev/core"))&&e("fw:qwik"),a("preact")&&e("fw:preact"),(a("lit")||a("lit-element"))&&e("fw:lit"),(a("ember-source")||a("ember-cli"))&&e("fw:ember"),a("htmx.org")&&e("fw:htmx"),a("vite")&&e("fw:vite"),a("webpack")&&e("fw:webpack"),a("express")&&e("fw:express"),a("fastify")&&e("fw:fastify"),a("@nestjs/core")&&e("fw:nestjs"),a("koa")&&e("fw:koa"),a("hono")&&e("fw:hono"),(a("@hapi/hapi")||a("hapi"))&&e("fw:hapi"),a("@adonisjs/core")&&e("fw:adonis"),(a("@trpc/server")||a("@trpc/client"))&&e("fw:trpc"),a("sails")&&e("fw:sails"),a("electron")&&e("fw:electron"),a("react-native")&&e("fw:react-native"),a("expo")&&e("fw:expo"),d("@ionic/")&&e("fw:ionic"),a("@capacitor/core")&&e("fw:capacitor"),n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile")){let i=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")).toLowerCase();i.includes("fastapi")&&e("fw:fastapi"),i.includes("django")&&e("fw:django"),i.includes("flask")&&e("fw:flask"),i.includes("litestar")&&e("fw:litestar"),i.includes("starlette")&&e("fw:starlette"),i.includes("tornado")&&e("fw:tornado"),i.includes("sanic")&&e("fw:sanic"),i.includes("aiohttp")&&e("fw:aiohttp"),i.includes("pyramid")&&e("fw:pyramid"),i.includes("fasthtml")&&e("fw:fasthtml"),(i.includes("torch")||i.includes("pytorch"))&&e("fw:pytorch"),i.includes("tensorflow")&&e("fw:tensorflow"),(i.includes("jax")||i.includes("jaxlib"))&&e("fw:jax"),i.includes("keras")&&e("fw:keras"),(i.includes("scikit-learn")||i.includes("sklearn"))&&e("fw:scikit-learn"),i.includes("transformers")&&e("fw:transformers"),i.includes("langchain")&&e("fw:langchain"),(i.includes("llama-index")||i.includes("llama_index")||i.includes("llamaindex"))&&e("fw:llamaindex"),i.includes("pandas")&&e("fw:pandas"),i.includes("numpy")&&e("fw:numpy"),i.includes("streamlit")&&e("fw:streamlit"),i.includes("gradio")&&e("fw:gradio"),i.includes("fastai")&&e("fw:fastai");}if(n("go.mod")){let i=c("go.mod").toLowerCase();i.includes("gin-gonic/gin")&&e("fw:gin"),i.includes("labstack/echo")&&e("fw:echo"),i.includes("gofiber/fiber")&&e("fw:fiber"),i.includes("go-chi/chi")&&e("fw:chi"),(i.includes("gorilla/mux")||i.includes("gorilla/websocket"))&&e("fw:gorilla"),(i.includes("beego/beego")||i.includes("astaxie/beego"))&&e("fw:beego"),i.includes("gobuffalo/buffalo")&&e("fw:buffalo");}if(n("Cargo.toml")){let i=c("Cargo.toml").toLowerCase();i.includes("actix-web")&&e("fw:actix"),i.includes("axum")&&e("fw:axum"),i.includes("rocket")&&e("fw:rocket"),i.includes("warp")&&e("fw:warp"),i.includes("tonic")&&e("fw:tonic"),i.includes("leptos")&&e("fw:leptos"),i.includes("yew")&&e("fw:yew"),i.includes("tauri")&&e("fw:tauri"),i.includes("dioxus")&&e("fw:dioxus"),i.includes("bevy")&&e("fw:bevy");}if(n("pom.xml")||n("build.gradle")||n("build.gradle.kts")){let i=(c("pom.xml")+c("build.gradle")+c("build.gradle.kts")).toLowerCase();(i.includes("spring-boot")||i.includes("springframework"))&&e("fw:spring"),i.includes("quarkus")&&e("fw:quarkus"),i.includes("micronaut")&&e("fw:micronaut"),(i.includes("io.ktor")||i.includes("ktor-"))&&e("fw:ktor"),(i.includes("vertx")||i.includes("vert.x"))&&e("fw:vertx"),(i.includes("com.android")||i.includes("androidx"))&&e("fw:android"),(i.includes("androidx.compose")||i.includes("jetpack"))&&e("fw:jetpack-compose"),(i.includes("kotlin-multiplatform")||i.includes('kotlin("multiplatform")'))&&e("fw:kotlin-multiplatform");}if(n("Gemfile")){let i=c("Gemfile").toLowerCase();i.includes("rails")&&e("fw:rails"),i.includes("sinatra")&&e("fw:sinatra"),i.includes("hanami")&&e("fw:hanami");}if(n("composer.json")){let i=c("composer.json").toLowerCase();(i.includes("laravel/framework")||i.includes("laravel/laravel"))&&e("fw:laravel"),i.includes("symfony/")&&e("fw:symfony"),i.includes("drupal/")&&e("fw:drupal"),i.includes("codeigniter")&&e("fw:codeigniter"),i.includes("slim/slim")&&e("fw:slim");}(n("wp-config.php")||n("wp-load.php")||n("wp-content"))&&e("fw:wordpress"),n("pubspec.yaml")&&c("pubspec.yaml").toLowerCase().includes("flutter")&&e("fw:flutter");{let i=r.filter(b=>b.endsWith(".csproj"));if(i.length>0){let b=i.map(g=>c(g)).join(`
|
|
4
|
+
`).toLowerCase();(b.includes("microsoft.net.sdk.web")||b.includes("microsoft.aspnetcore"))&&e("fw:aspnet"),b.includes("blazor")&&e("fw:blazor"),(b.includes("microsoft.net.sdk.maui")||b.includes("usemaui"))&&e("fw:maui");}}(n("ProjectSettings")||r.includes("Assembly-CSharp.csproj"))&&e("fw:unity"),n("project.godot")&&e("fw:godot");{let i=c("Package.swift").toLowerCase();i.includes("swiftui")&&e("fw:swiftui"),i.includes("uikit")&&e("fw:uikit");}let s=i=>r.some(b=>b===i||b.startsWith(i+"."));s("next.config")&&e("fw:nextjs"),s("nuxt.config")&&e("fw:nuxt"),s("astro.config")&&e("fw:astro"),s("svelte.config")&&e("fw:svelte"),s("remix.config")&&e("fw:remix"),s("gatsby-config")&&e("fw:gatsby"),s("vite.config")&&e("fw:vite"),s("vue.config")&&e("fw:vue"),s("qwik.config")&&e("fw:qwik"),n("angular.json")&&e("fw:angular"),s("capacitor.config")&&e("fw:capacitor"),s("ionic.config")&&e("fw:ionic"),n("app.json")&&c("app.json").toLowerCase().includes('"expo"')&&e("fw:expo");}{if((a("pg")||a("postgres")||a("pg-promise")||a("@vercel/postgres"))&&e("infra:postgres"),(a("mysql")||a("mysql2"))&&e("infra:mysql"),a("mariadb")&&e("infra:mariadb"),(a("redis")||a("ioredis"))&&e("infra:redis"),(a("mongodb")||a("mongoose"))&&e("infra:mongodb"),a("mongoose")&&e("infra:mongoose"),(a("better-sqlite3")||a("sqlite3")||a("sqlite"))&&e("infra:sqlite"),a("@libsql/client")&&e("infra:libsql"),a("cassandra-driver")&&e("infra:cassandra"),(a("@elastic/elasticsearch")||a("elasticsearch"))&&e("infra:elasticsearch"),a("@opensearch-project/opensearch")&&e("infra:opensearch"),(a("@clickhouse/client")||a("clickhouse"))&&e("infra:clickhouse"),(a("duckdb")||a("@duckdb/node-api"))&&e("infra:duckdb"),a("neo4j-driver")&&e("infra:neo4j"),a("@influxdata/influxdb-client")&&e("infra:influxdb"),a("snowflake-sdk")&&e("infra:snowflake"),a("@google-cloud/bigquery")&&e("infra:bigquery"),(a("firebase-admin")||a("@google-cloud/firestore"))&&e("infra:firestore"),(a("faunadb")||a("fauna"))&&e("infra:fauna"),(a("surrealdb")||a("surrealdb.js"))&&e("infra:surrealdb"),a("@qdrant/js-client-rest")&&e("infra:qdrant"),a("@pinecone-database/pinecone")&&e("infra:pinecone"),(a("weaviate-ts-client")||a("weaviate-client"))&&e("infra:weaviate"),a("chromadb")&&e("infra:chromadb"),a("@zilliz/milvus2-sdk-node")&&e("infra:milvus"),(a("@prisma/client")||a("prisma"))&&e("infra:prisma"),a("drizzle-orm")&&e("infra:drizzle"),a("typeorm")&&e("infra:typeorm"),(a("aws-sdk")||d("@aws-sdk/"))&&e("infra:aws"),(d("@google-cloud/")||a("googleapis"))&&e("infra:gcp"),d("@azure/")&&e("infra:azure"),(d("@cloudflare/")||a("wrangler"))&&e("infra:cloudflare"),(a("@vercel/node")||a("@vercel/kv")||a("@vercel/blob"))&&e("infra:vercel"),(a("firebase")||a("firebase-admin"))&&e("infra:firebase"),a("@supabase/supabase-js")&&e("infra:supabase"),a("@neondatabase/serverless")&&e("infra:neon"),a("@planetscale/database")&&e("infra:planetscale"),d("@upstash/")&&e("infra:upstash"),a("@tursodatabase/api")&&e("infra:turso"),a("modal")&&e("infra:modal"),a("replicate")&&e("infra:replicate"),(a("kafkajs")||a("node-rdkafka"))&&e("infra:kafka"),(a("amqplib")||a("rabbitmq-client"))&&e("infra:rabbitmq"),a("nats")&&e("infra:nats"),(d("@aws-sdk/client-sqs")||a("sqs-consumer"))&&e("infra:sqs"),a("@google-cloud/pubsub")&&e("infra:pubsub"),d("@temporalio/")&&e("infra:temporal"),(a("bullmq")||a("bull"))&&e("infra:bullmq"),d("@sentry/")&&e("infra:sentry"),(d("@datadog/")||a("dd-trace"))&&e("infra:datadog"),d("@opentelemetry/")&&e("infra:opentelemetry"),a("newrelic")&&e("infra:newrelic"),(a("posthog-node")||a("posthog-js"))&&e("infra:posthog"),d("@honeycombio/")&&e("infra:honeycomb"),a("prom-client")&&e("infra:prometheus"),(a("stripe")||a("@stripe/stripe-js"))&&e("infra:stripe"),d("@paddle/")&&e("infra:paddle"),d("@clerk/")&&e("infra:clerk"),(a("auth0")||d("@auth0/"))&&e("infra:auth0"),(a("next-auth")||d("@auth/"))&&e("infra:nextauth"),a("twilio")&&e("infra:twilio"),a("@sendgrid/mail")&&e("infra:sendgrid"),a("resend")&&e("infra:resend"),a("postmark")&&e("infra:postmark"),d("@pulumi/")&&e("infra:pulumi"),n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile")){let i=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")).toLowerCase();(i.includes("psycopg")||i.includes("asyncpg"))&&e("infra:postgres"),(i.includes("pymysql")||i.includes("aiomysql")||i.includes("mysqlclient"))&&e("infra:mysql"),(i.includes("redis")||i.includes("aioredis"))&&e("infra:redis"),(i.includes("pymongo")||i.includes("motor")||i.includes("mongoengine"))&&e("infra:mongodb"),i.includes("elasticsearch")&&e("infra:elasticsearch"),i.includes("clickhouse")&&e("infra:clickhouse"),i.includes("duckdb")&&e("infra:duckdb"),i.includes("neo4j")&&e("infra:neo4j"),i.includes("snowflake")&&e("infra:snowflake"),i.includes("qdrant-client")&&e("infra:qdrant"),i.includes("pinecone")&&e("infra:pinecone"),i.includes("chromadb")&&e("infra:chromadb"),i.includes("pymilvus")&&e("infra:milvus"),i.includes("sqlalchemy")&&e("infra:sqlalchemy"),(i.includes("boto3")||i.includes("botocore"))&&e("infra:aws"),i.includes("google-cloud")&&e("infra:gcp"),i.includes("azure-")&&e("infra:azure"),i.includes("supabase")&&e("infra:supabase"),(i.includes("confluent-kafka")||i.includes("aiokafka")||i.includes("kafka-python"))&&e("infra:kafka"),(i.includes("pika")||i.includes("aio-pika"))&&e("infra:rabbitmq"),i.includes("temporalio")&&e("infra:temporal"),i.includes("sentry-sdk")&&e("infra:sentry"),(i.includes("ddtrace")||i.includes("datadog"))&&e("infra:datadog"),i.includes("opentelemetry")&&e("infra:opentelemetry"),i.includes("stripe")&&e("infra:stripe"),i.includes("twilio")&&e("infra:twilio"),i.includes("pulumi")&&e("infra:pulumi"),i.includes("ansible")&&e("infra:ansible");}if(n("go.mod")){let i=c("go.mod").toLowerCase();(i.includes("lib/pq")||i.includes("jackc/pgx"))&&e("infra:postgres"),i.includes("go-sql-driver/mysql")&&e("infra:mysql"),(i.includes("go-redis")||i.includes("redis/go-redis"))&&e("infra:redis"),i.includes("go.mongodb.org/mongo-driver")&&e("infra:mongodb"),i.includes("aws/aws-sdk-go")&&e("infra:aws"),i.includes("cloud.google.com/go")&&e("infra:gcp"),(i.includes("segmentio/kafka-go")||i.includes("sarama"))&&e("infra:kafka"),i.includes("getsentry/sentry-go")&&e("infra:sentry"),i.includes("go.opentelemetry.io")&&e("infra:opentelemetry"),i.includes("stripe/stripe-go")&&e("infra:stripe"),i.includes("hashicorp/terraform")&&e("infra:terraform"),i.includes("k8s.io/client-go")&&e("infra:kubernetes");}(n("Dockerfile")||n("docker-compose.yml")||n("docker-compose.yaml")||n("compose.yaml")||n("compose.yml")||n(".dockerignore"))&&e("infra:docker"),(n("Containerfile")||n("podman-compose.yml"))&&e("infra:podman"),r.some(i=>i.endsWith(".tf")||i===".terraform.lock.hcl")&&e("infra:terraform"),(n("Pulumi.yaml")||n("Pulumi.yml"))&&e("infra:pulumi"),(n("ansible.cfg")||n("playbook.yml")||n("playbook.yaml"))&&e("infra:ansible"),(n("kustomization.yaml")||n("kustomization.yml")||n("k8s")||n("kubernetes")||n("skaffold.yaml"))&&e("infra:kubernetes"),(n("Chart.yaml")||n("helmfile.yaml"))&&(e("infra:helm"),e("infra:kubernetes")),r.some(i=>i.endsWith(".nomad")||i.endsWith(".nomad.hcl"))&&e("infra:nomad"),(n("vercel.json")||n(".vercel"))&&e("infra:vercel"),(n("netlify.toml")||n(".netlify"))&&e("infra:netlify"),n("fly.toml")&&e("infra:fly"),(n("railway.json")||n("railway.toml"))&&e("infra:railway"),n("render.yaml")&&e("infra:render"),n("Procfile")&&e("infra:heroku"),(n("wrangler.toml")||n("wrangler.jsonc")||n("wrangler.json"))&&e("infra:cloudflare"),n("supabase")&&e("infra:supabase"),(n("firebase.json")||n(".firebaserc"))&&e("infra:firebase"),(n("serverless.yml")||n("serverless.yaml")||n("template.yaml")||n("samconfig.toml"))&&e("infra:aws"),(n("prisma")||n("schema.prisma"))&&e("infra:prisma"),(n("drizzle.config.ts")||n("drizzle.config.js"))&&e("infra:drizzle");let s=false;try{s=n(".github")&&h__namespace.existsSync(y__namespace.join(t,".github","workflows"));}catch{s=false;}s&&e("infra:github-actions"),(n(".gitlab-ci.yml")||n(".gitlab-ci.yaml"))&&e("infra:gitlab-ci"),n(".circleci")&&e("infra:circleci"),n("Jenkinsfile")&&e("infra:jenkins");{let i=(c("Dockerfile")+c("docker-compose.yml")+c("docker-compose.yaml")+c("compose.yaml")+c("compose.yml")).toLowerCase();i&&((i.includes("postgres")||i.includes("pgvector"))&&e("infra:postgres"),i.includes("timescale")&&e("infra:timescaledb"),i.includes("mysql")&&e("infra:mysql"),i.includes("mariadb")&&e("infra:mariadb"),i.includes("redis")&&e("infra:redis"),i.includes("mongo")&&e("infra:mongodb"),i.includes("cassandra")&&e("infra:cassandra"),i.includes("cockroach")&&e("infra:cockroachdb"),i.includes("clickhouse")&&e("infra:clickhouse"),i.includes("elasticsearch")&&e("infra:elasticsearch"),i.includes("neo4j")&&e("infra:neo4j"),i.includes("qdrant")&&e("infra:qdrant"),i.includes("rabbitmq")&&e("infra:rabbitmq"),(i.includes("kafka")||i.includes("redpanda"))&&e("infra:kafka"),i.includes("nats")&&e("infra:nats"),i.includes("grafana")&&e("infra:grafana"),(i.includes("prometheus")||i.includes("prom/"))&&e("infra:prometheus"));}}{let i=(...w)=>w.some(a),b=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")+c("environment.yml")).toLowerCase(),g=c("go.mod").toLowerCase(),m=c("Cargo.toml").toLowerCase(),l=w=>b.includes(w),I=w=>r.some(de=>de.toLowerCase().endsWith(w)),k=(...w)=>w.some(de=>n(de)),j=()=>Array.from(o).some(w=>w.startsWith("type:")),ue=()=>Array.from(o).some(w=>w.startsWith("fw:"));(a("@modelcontextprotocol/sdk")||l("modelcontextprotocol")||l("fastmcp")||g.includes("modelcontextprotocol")||k("mcp.json",".mcp.json"))&&e("type:mcp-server"),(i("langgraph","@langchain/langgraph","crewai","autogen","@mastra/core","@openai/agents","@langchain/core")||l("langgraph")||l("crewai")||l("autogen")||l("pyautogen")||l("smolagents")||l("haystack"))&&e("type:agent-framework"),(i("ai","openai","@anthropic-ai/sdk","@google/generative-ai","@ai-sdk/openai","@ai-sdk/anthropic","langchain","@huggingface/inference","cohere-ai","ollama","groq-sdk","@mistralai/mistralai")||l("openai")||l("anthropic")||l("langchain")||l("litellm")||l("google-generativeai")||l("cohere")||l("ollama"))&&e("type:ai-app"),(I(".sol")||k("hardhat.config.js","hardhat.config.ts","foundry.toml","truffle-config.js","Anchor.toml","Move.toml")||i("hardhat","ethers","web3","@solana/web3.js","wagmi","viem","@openzeppelin/contracts"))&&e("type:smart-contract"),(k("project.godot","ProjectSettings")||I(".unity")||I(".uproject")||i("phaser","kaplay","kaboom","excalibur","playcanvas")||m.includes("bevy")||m.includes("macroquad")||m.includes("ggez")||l("pygame")||l("arcade"))&&e("type:game");{let w=f("manifest.json");(w&&Object.prototype.hasOwnProperty.call(w,"manifest_version")||i("webextension-polyfill","@types/chrome","wxt","plasmo"))&&e("type:browser-extension");}(i("react-native","expo","nativescript")||n("pubspec.yaml")||I(".xcodeproj")||k("AndroidManifest.xml"))&&e("type:mobile-app"),(i("electron","@tauri-apps/api","@tauri-apps/cli","nw")||k("tauri.conf.json","src-tauri")||m.includes("tauri")||m.includes("egui")||l("pyqt5")||l("pyqt6")||l("pyside6")||l("kivy"))&&e("type:desktop-app"),(i("discord.js","telegraf","node-telegram-bot-api","@slack/bolt","probot","grammy")||l("discord.py")||l("python-telegram-bot")||l("slack-bolt")||l("slack_bolt")||l("aiogram")||l("pyrogram"))&&e("type:bot"),(k("dbt_project.yml","dagster.yaml")||i("@dagster-io/dagster","apache-airflow")||l("airflow")||l("dagster")||l("prefect")||l("dbt-core")||l("luigi")||l("kedro")||l("pyspark")||l("apache-beam"))&&e("type:data-pipeline"),(l("torch")||l("tensorflow")||l("keras")||l("jax")||l("scikit-learn")||l("sklearn")||l("xgboost")||l("lightgbm")||l("pytorch-lightning")||l("diffusers")||l("mlflow"))&&e("type:ml-model"),(I(".ipynb")||l("jupyter")||l("jupyterlab")||l("marimo")||n("notebooks"))&&e("type:notebook"),(k("mkdocs.yml","mkdocs.yaml","mint.json","docusaurus.config.js","docusaurus.config.ts","book.toml")||i("@docusaurus/core","vitepress","vuepress","nextra","@astrojs/starlight")||l("mkdocs")||l("sphinx"))&&e("type:documentation"),(k("hugo.toml","_config.yml",".eleventy.js","eleventy.config.js","astro.config.mjs","astro.config.ts","astro.config.js")||i("astro","gatsby","@11ty/eleventy","hexo","gridsome")||l("pelican"))&&e("type:static-site"),i("@medusajs/medusa","@saleor/sdk","@shopify/hydrogen","vendure","@vendure/core","snipcart","use-shopping-cart","swell-js")&&e("type:ecommerce"),(p.bin||i("commander","yargs","oclif","@oclif/core","cac","meow","inquirer","@clack/prompts","ink")||l("click")||l("typer")||l("docopt")||g.includes("spf13/cobra")||g.includes("urfave/cli")||m.includes("clap")||m.includes("structopt"))&&e("type:cli"),(k("pnpm-workspace.yaml","turbo.json","nx.json","lerna.json","rush.json")||Array.isArray(p.workspaces)||m.includes("[workspace]")||n("go.work"))&&e("type:monorepo");let T=i("next","react","vue","@angular/core","svelte","@sveltejs/kit","solid-js","nuxt","remix","@remix-run/react","preact","qwik"),R=i("express","fastify","@nestjs/core","koa","hapi","@hapi/hapi","hono")||l("fastapi")||l("django")||l("flask")||l("starlette")||l("sanic")||g.includes("gin-gonic/gin")||g.includes("labstack/echo")||g.includes("gofiber/fiber")||m.includes("axum")||m.includes("actix-web")||(c("pom.xml")+c("build.gradle")).toLowerCase().includes("spring-boot"),Ee=Array.from(o).some(w=>["infra:postgres","infra:mysql","infra:mongodb","infra:supabase","infra:neon"].includes(w)),Oe=i("next-auth","@clerk/nextjs","@auth0/auth0-react","passport","lucia","@workos-inc/node")||l("django-allauth")||l("flask-login"),Ae=i("stripe","@stripe/stripe-js","@paddle/paddle-js","@lemonsqueezy/lemonsqueezy.js")||l("stripe");(!T&&!R&&(p.main||p.exports||p.module||p.types||p.publishConfig)||n("Cargo.toml")&&!m.includes("[[bin]]")&&m.includes("[lib]")||k("LICENSE","LICENSE.md","LICENSE.txt")&&!T&&!R&&!j())&&!j()&&e("type:library"),T?(Ee&&(Oe||Ae)&&e("type:saas"),e("type:web-app")):R&&(Ee&&(Oe||Ae)&&e("type:saas"),e("type:api-service")),j()||(ue()?e("type:web-app"):k("Dockerfile","docker-compose.yml","compose.yaml")||r.some(w=>w.endsWith(".tf"))||k("Chart.yaml","kustomization.yaml","wrangler.toml","serverless.yml",".github")||i("@pulumi/pulumi","aws-cdk-lib","cdktf")?e("type:devops-tool"):n("package.json")&&(p.main||p.exports)&&e("type:library"));}return Array.from(o)}function He(t){let o={sponsorLabel:t.sponsorLabel,title:t.creative.title,body:t.creative.body,url:t.clickUrl};return t.creative.cta!==void 0&&(o.cta=t.creative.cta),o}function Be(t){return {sponsorLabel:"",title:t.title,body:t.body,url:t.url}}function Y(t){let o=He(t),e=t.creative;switch(e.format){case "image":case "gif":return {...o,body:e.textFallback??o.body};case "video":return {...o,body:e.textFallback??o.body,cta:o.cta??"\u25B6 Watch"};case "audio":return {...o,body:e.textFallback??o.body,cta:o.cta??"\u{1F50A} Listen"};default:return o}}function B(t=process.env){return y__namespace.join(N__namespace.homedir(),".config","opencrater")}function X(t=process.env){return y__namespace.join(B(t),"state.json")}function V(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function E(t){return typeof t=="number"&&Number.isFinite(t)}var Fe=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function qe(t){for(let o=0;;o++)try{return {text:h__namespace.readFileSync(t,"utf8")}}catch(e){let r=e.code??"";if(!(r==="ENOENT"||Fe.has(r)))return {locked:true};if(o>=4)return r==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(o+1));}catch{}}}function vt(t){if(typeof t!="object"||t===null)return null;let o=t;return !E(o.minIntervalSeconds)||!E(o.serveTimeoutMs)||!E(o.preloadPoolSize)||typeof o.killSwitch!="boolean"?null:{minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:o.preloadPoolSize,killSwitch:o.killSwitch,displayDurationSeconds:E(o.displayDurationSeconds)?o.displayDurationSeconds:25,minSdkVersion:typeof o.minSdkVersion=="string"?o.minSdkVersion:""}}function xt(t){if(!Array.isArray(t))return [];let o=[];for(let e of t){if(typeof e!="object"||e===null)continue;let r=e,n=r.blip;if(!E(r.renderBy)||typeof n!="object"||n===null||typeof n.impressionId!="string"||typeof n.clickUrl!="string"||typeof n.sponsorLabel!="string"||typeof n.creative!="object"||n.creative===null)continue;let c=n.creative;typeof c.title!="string"||typeof c.body!="string"||o.push({blip:{impressionId:n.impressionId,...typeof n.campaignId=="string"?{campaignId:n.campaignId}:{},clickUrl:n.clickUrl,sponsorLabel:n.sponsorLabel,creative:{format:"text",title:c.title,body:c.body,...typeof c.cta=="string"?{cta:c.cta}:{}}},renderBy:r.renderBy});}return o}function Ct(t){if(typeof t!="object"||t===null||Array.isArray(t))return {};let o={};for(let[e,r]of Object.entries(t)){if(!Array.isArray(r))continue;let n=r.filter(c=>typeof c=="string"&&c.length<=64);o[e]=n.slice(0,64);}return o}function Tt(t){if(!Array.isArray(t))return [];let o=[];for(let e of t){if(typeof e!="object"||e===null)continue;let r=e;if(!(typeof r.topic!="string"||!E(r.at))&&(o.push({topic:r.topic.slice(0,32),at:r.at}),o.length>=24))break}return o}function jt(t){if(!Array.isArray(t))return [];let o=[],e=new Set;for(let r of t){if(typeof r!="object"||r===null)continue;let n=r;if(typeof n.key!="string"||typeof n.package!="string"||n.key===""||n.package==="")continue;let c=`${n.package}\0${n.key}`;if(!e.has(c)&&(e.add(c),o.push({key:n.key,package:n.package}),o.length>=32))break}return o}function Rt(t){if(typeof t!="object"||t===null)return null;let o=t,e={};if(typeof o.savedEnv=="object"&&o.savedEnv!==null)for(let[r,n]of Object.entries(o.savedEnv))(typeof n=="string"||n===null)&&(e[r]=n);return {active:o.active===true,savedEnv:e}}function Et(t){if(typeof t!="object"||t===null)return null;let o=t,e=r=>E(r)&&r>=0?r:0;return {turns:e(o.turns),lastLimitAt:e(o.lastLimitAt),lastDepletedAt:e(o.lastDepletedAt),lastBackupAt:e(o.lastBackupAt)}}function Ot(t){let o=t.attrTagsAt,e=t.attrTagsCwd;return !E(o)||Date.now()-o>K||typeof e!="string"||e.length===0||e.length>64?{}:{attrTags:Array.isArray(t.attrTags)?t.attrTags.filter(n=>typeof n=="string"&&n.length<=40).slice(0,48):[],attrTagsCwd:e,attrTagsAt:o}}function At(t){let o=V();if(typeof t!="object"||t===null)return o;let e=t;return {installId:typeof e.installId=="string"&&e.installId.length>0?e.installId:o.installId,lastShownAt:E(e.lastShownAt)&&e.lastShownAt>=0?e.lastShownAt:0,optOut:e.optOut===true,disclosureShown:e.disclosureShown===true,cachedConfig:vt(e.cachedConfig),allowedPlacements:Ct(e.allowedPlacements),sessionTopics:Tt(e.sessionTopics),integrations:jt(e.integrations),devToken:typeof e.devToken=="string"?e.devToken:null,computeRouting:Rt(e.computeRouting),computeCards:Et(e.computeCards),configFetchedAt:E(e.configFetchedAt)&&e.configFetchedAt>=0?e.configFetchedAt:0,pool:xt(e.pool),...Ot(e)}}function me(t=process.env){let o=X(t),e=qe(o);if(e.text!==void 0)try{return At(JSON.parse(e.text))}catch{let r=V();try{C(r,t);}catch{}return r}if(e.missing){let r=V();try{C(r,t);}catch{}return r}return V()}function C(t,o=process.env,e={}){let r=X(o),n=y__namespace.dirname(r);h__namespace.mkdirSync(n,{recursive:true});let c=qe(r),f=null;if(c.text!==void 0)try{f=JSON.parse(c.text);}catch{f=null;}if(f)typeof f.lastShownAt=="number"&&f.lastShownAt>t.lastShownAt&&(t={...t,lastShownAt:f.lastShownAt}),!e.allowClearToken&&typeof f.devToken=="string"&&t.devToken==null&&(t={...t,devToken:f.devToken}),typeof f.installId=="string"&&f.installId.length>0&&f.installId!==t.installId&&(t={...t,installId:f.installId});else if(!e.allowClearToken&&t.devToken==null&&c.text===void 0&&!c.missing)return;let p=y__namespace.join(n,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);h__namespace.writeFileSync(p,JSON.stringify(t,null,2)+`
|
|
5
|
+
`,"utf8");for(let u=0;;u++)try{h__namespace.renameSync(p,r);return}catch(a){let d=a.code??"";if(u>=4||!Fe.has(d)){try{h__namespace.rmSync(p,{force:!0});}catch{}if(u>=4)return;throw a}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(u+1));}catch{}}}var _t=300*1e3;function It(){return y__namespace.join(B(),"blocked-ads.json")}function ge(){return y__namespace.join(B(),"recent-renders.json")}function Pt(){return y__namespace.join(B(),"reported-ads.json")}function Ge(t,o){let e={};for(let[r,n]of Object.entries(t))typeof n=="number"&&Number.isFinite(n)&&n>o&&(e[r]=n);return e}function Nt(t){try{let o=JSON.parse(h__namespace.readFileSync(It(),"utf8"));return Ge(o&&typeof o=="object"?o:{},t)}catch{return {}}}function $t(){try{let t=JSON.parse(h__namespace.readFileSync(Pt(),"utf8"));return t&&typeof t=="object"?t:{}}catch{return {}}}function Mt(t){return t?$t()[t]!==void 0:false}function Z(t,o=Date.now()){return t?Nt(o)[t]!==void 0||Mt(t):false}function ze(t){try{let o=JSON.parse(h__namespace.readFileSync(ge(),"utf8"));return Ge(o&&typeof o=="object"?o:{},t)}catch{return {}}}function Q(t,o=Date.now()){if(t)try{let e=ze(o);e[t]=o+_t,h__namespace.mkdirSync(y__namespace.dirname(ge()),{recursive:!0}),h__namespace.writeFileSync(ge(),JSON.stringify(e));}catch{}}function ee(t,o=Date.now()){return t?ze(o)[t]!==void 0:false}function Lt(t,o){return t.filter(e=>e.renderBy>o)}function he(t,o){let e=Lt(t.pool,o),r=e.shift();return {blip:r?r.blip:null,pool:e}}var Dt=["claude_code","codex","antigravity","copilot_cli","grok_cli"];function be(t){return t.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(t)}function Wt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ht(t,o){return be(t)&&new RegExp(`--package ['"]?${Wt(o)}['"]?`).test(t)}function ke(t,o){return o?Ht(t,o):be(t)&&!/--package\b/.test(t)}function te(t){return /^[A-Za-z0-9@_./:-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var ne='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',Je="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function U(t,o,e,r){let n=`--placement ${o}`;return e&&(n+=` --key ${te(e)}`),r&&(n+=` --package ${te(r)}`),n+=` --host ${t}`,`{ if [ -f ${ne} ]; then node ${ne} ${n}; else npx -y -p opencrater opencrater-hook ${n}; fi; } 2>/dev/null || true`}function Bt(t,o,e){if(process.platform!=="win32")return U("grok_cli",t,o,e);let r=`--placement ${t}`;o&&(r+=` --key ${o}`),e&&(r+=` --package ${e}`),r+=" --host grok_cli";let n=`${N__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${n}") { node "${n}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Ut(t,o,e){let r=`--placement ${t}`;return o&&(r+=` --key ${te(o)}`),e&&(r+=` --package ${te(e)}`),r+=" --host antigravity",`{ if [ -f ${ne} ]; then node ${ne} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } >/dev/null 2>&1; echo '{}'`}function Ye(t,o,e,r){let n=`--placement ${o}`;return e&&(n+=` --key '${e}'`),r&&(n+=` --package '${r}'`),n+=` --host ${t}`,`try { if (Test-Path "${Je}") { node "${Je}" ${n} } else { npx -y -p opencrater opencrater-hook ${n} } } catch {}`}function Ft(t,o,e){if(process.platform!=="win32")return U("claude_code",t,o,e);let r=`--placement ${t}`;return o&&(r+=` --key ${o}`),e&&(r+=` --package ${e}`),r+=" --host claude_code",`node "${`${N__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${r}; exit 0`}function ye(t,o,e,r){if(t==="grok_cli")return {type:"command",command:Bt(o,e,r),timeout:15};let c={type:"command",command:t==="claude_code"?Ft(o,e,r):U(t,o,e,r)};return t==="codex"&&(c.commandWindows=Ye(t,o,e,r)),c}function re(t,o){let e=N__namespace.homedir();switch(t){case "claude_code":{let r=o.CLAUDE_CONFIG_DIR;return r&&r.trim()!==""?r:y__namespace.join(e,".claude")}case "codex":{let r=o.CODEX_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".codex")}case "antigravity":return y__namespace.join(e,".gemini");case "copilot_cli":{let r=o.COPILOT_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".copilot")}case "grok_cli":{let r=o.GROK_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".grok")}default:return y__namespace.join(e,".opencrater-unknown")}}function F(t,o=process.env){let e=re(t,o);switch(t){case "claude_code":return y__namespace.join(e,"settings.json");case "codex":return y__namespace.join(e,"hooks.json");case "antigravity":return y__namespace.join(e,"config","hooks.json");case "copilot_cli":return y__namespace.join(e,"hooks","hooks.json");case "grok_cli":return y__namespace.join(e,"hooks","opencrater.json");default:return y__namespace.join(e,"hooks.json")}}var qt={claude_code:["claude"],codex:["codex"],antigravity:["agy"],copilot_cli:["copilot"],grok_cli:["grok"]};function Gt(t,o){if(t.length===0)return false;let e=(o.PATH??o.Path??"").split(y__namespace.delimiter).filter(Boolean),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let n of e)for(let c of t)for(let f of r)try{if(h__namespace.existsSync(y__namespace.join(n,c+f)))return !0}catch{}return false}function zt(t,o=process.env){try{if(h__namespace.existsSync(re(t,o)))return !0}catch{}return Gt(qt[t]??[],o)}function we(t=process.env){return Dt.filter(o=>zt(o,t))}function ie(t){let o;try{o=h__namespace.readFileSync(t,"utf8");}catch{return {}}let e=JSON.parse(o);if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t} is not a JSON object`);return e}function se(t,o){let e=y__namespace.dirname(t);h__namespace.mkdirSync(e,{recursive:true});let r=y__namespace.join(e,`.${y__namespace.basename(t)}.${process.pid}.tmp`);h__namespace.writeFileSync(r,JSON.stringify(o,null,2)+`
|
|
6
|
+
`,"utf8"),h__namespace.renameSync(r,t);}function Jt(t,o){return Array.isArray(t.hooks)&&t.hooks.some(e=>typeof e.command=="string"&&ke(e.command,o))}function Kt(t,o,e,r){let n=F(t),c=ie(n),f=c.hooks&&typeof c.hooks=="object"?c.hooks:{};if(r.every(u=>{let a=ye(t,u,o,e);return (Array.isArray(f[u])?f[u]:[]).some(d=>Array.isArray(d.hooks)&&d.hooks.some(s=>s.command===a.command&&s.commandWindows===a.commandWindows))}))return "nochange";for(let u of r){let d=(Array.isArray(f[u])?f[u]:[]).filter(i=>!Jt(i,e)),s=t==="grok_cli"?{hooks:[ye(t,u,o,e)]}:{matcher:"",hooks:[ye(t,u,o,e)]};d.push(s),f[u]=d;}return c.hooks=f,se(n,c),"wrote"}var Yt=15;function Vt(t){return t?`opencrater-${t}`:"opencrater-compute"}function Xt(t,o){if(!t||typeof t!="object")return false;for(let e of Object.values(t))for(let r of Array.isArray(e)?e:[])if(Array.isArray(r.hooks)&&r.hooks.some(n=>typeof n.command=="string"&&ke(n.command,o)))return true;return false}function Zt(t){try{let o=y__namespace.join(re("antigravity",t),"settings.json"),e;try{e=ie(o);}catch{return}let r=!1,n=e.hooks;if(n&&typeof n=="object"&&!Array.isArray(n)){let c=n;for(let f of Object.keys(c)){let p=Array.isArray(c[f])?c[f]:[],u=p.filter(a=>!(Array.isArray(a.hooks)&&a.hooks.some(d=>typeof d.command=="string"&&be(d.command))));u.length!==p.length&&(r=!0,u.length>0?c[f]=u:delete c[f]);}Object.keys(c).length===0&&(delete e.hooks,r=!0);}e["json-hooks-enabled"]===!0&&(delete e["json-hooks-enabled"],r=!0),r&&se(o,e);}catch{}}function Qt(t,o,e){let r=F("antigravity"),n=ie(r),c=Vt(o),f={};for(let a of e)f[a]=[{hooks:[{type:"command",command:Ut(a,t,o),timeout:Yt}]}];let p=JSON.stringify(f),u=false;JSON.stringify(n[c]??null)!==p&&(n[c]=f,u=true);for(let a of Object.keys(n))a!==c&&Xt(n[a],o)&&(delete n[a],u=true);return Zt(process.env),u?(se(r,n),"wrote"):"nochange"}var Ke=12;function en(t,o){return [t.bash,t.powershell,t.command].some(e=>typeof e=="string"&&ke(e,o))}function tn(t,o,e,r){let n=F(t),c=ie(n);typeof c.version!="number"&&(c.version=1);let f=c.hooks&&typeof c.hooks=="object"?c.hooks:{};if(r.every(u=>{let a=U(t,u,o,e);return (Array.isArray(f[u])?f[u]:[]).some(d=>d.bash===a&&d.timeoutSec===Ke)}))return "nochange";for(let u of r){let d=(Array.isArray(f[u])?f[u]:[]).filter(s=>!en(s,e));d.push({type:"command",bash:U(t,u,o,e),powershell:Ye(t,u,o,e),timeoutSec:Ke}),f[u]=d;}return c.hooks=f,se(n,c),"wrote"}function Ve(t){return [...Ie[t]]}function nn(t){let o=t;for(let e of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${e}\\]`,"m").test(o))continue;let r=o.length===0?"":o.endsWith(`
|
|
7
7
|
`)?`
|
|
8
8
|
`:`
|
|
9
9
|
|
|
10
10
|
`;o+=`${r}[compat.${e}]
|
|
11
11
|
hooks = false
|
|
12
|
-
`;}return o}function nn(t){try{let o=y__namespace.join(ne("grok_cli",t),"config.toml"),e="";try{e=h__namespace.readFileSync(o,"utf8");}catch{}let r=tn(e);if(r===e)return;h__namespace.mkdirSync(y__namespace.dirname(o),{recursive:!0}),h__namespace.writeFileSync(o,r,"utf8");}catch{}}function on(t,o,e){let r=Ve(t);return r.length===0?"nochange":(t==="grok_cli"&&nn(process.env),t==="copilot_cli"?en(t,o,e,r):t==="antigravity"?Zt(o,e,r):Jt(t,o,e,r))}function ke(t,o,e=process.env){return be(e).map(r=>{try{let n=on(r,t,o);return {host:r,status:n,events:Ve(r)}}catch(n){return {host:r,status:"error",events:[],error:n.message}}})}function sn(){return y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime")}function an(t){return ["install","--prefix",t,"opencrater@latest","--silent","--no-audit","--no-fund"]}function we(t=sn()){child_process.spawn("npm",an(t),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var et={atLimit:false,resetAt:null};function tt(t,o=N__namespace.homedir()){try{if(t==="claude_code")return cn(o);if(t==="codex")return ln(o)}catch{}return et}function cn(t){let o=h__namespace.readFileSync(y__namespace.join(t,".claude.json"),"utf8"),e=JSON.parse(o),r=e.hasAvailableSubscription===false||e.cachedExtraUsageDisabledReason==="out_of_credits",n=null,p=e.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof p=="string"){let u=Date.parse(p);Number.isFinite(u)&&(n=u);}return {atLimit:r,resetAt:n}}function ln(t){return h__namespace.accessSync(y__namespace.join(t,".codex","auth.json")),et}function nt(t,o){return t==="copilot_cli"?o==="agentStop":o==="Stop"}var ot=36e5,fn=30*6e4,un=30*6e4,dn=4*ot,pn=3,ie="https://opencrater.to/dashboard";function q(t){return `${Math.round(t/1e3).toLocaleString()} tokens`}function mn(t){let o=t/1e3;return o>0&&o<10?`${(Math.round(o*10)/10).toFixed(1)} tokens`:`${Math.round(o).toLocaleString()} tokens`}function gn(t){switch(t){case "claude_code":return {name:"Claude Code",launch:"opencrater claude",resume:"opencrater claude -c"};case "codex":return {name:"Codex",launch:"opencrater codex",resume:"opencrater codex -c"};case "grok_cli":return {name:"Grok",launch:"opencrater grok",resume:"opencrater grok -c"};default:return null}}var se="opencrater claude";function hn(t,o){if(!t||t<=o)return "";let e=t-o,r=e>=864e5?`${Math.floor(e/864e5)}d`:`${Math.max(1,Math.floor(e/ot))}h`,n=new Date(t).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${n}).`}function rt(t){let{balanceMicroUsd:o,pendingMicroUsd:e,onGateway:r,turnEnd:n,hostName:c,host:f,cc:p,now:u}=t;if(o===null)return null;let a=gn(c),d=e&&e>0?` (+${mn(e)} pending)`:"";return o<=0?u-(p.lastDepletedAt??0)<un?null:{kind:"depleted",card:{sponsorLabel:"OpenCrater",title:"Compute used up",body:`Keep coding in any CLI to earn more compute, then switch back to ${a?.name??"your plan"}.`+hn(f.resetAt,u),url:ie,cta:"Earn more"}}:r?!n||(p.turns??0)%pn!==0?null:{kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:`${q(o)} compute available${d}.`,url:ie,cta:"Wallet"}}:f.atLimit?u-(p.lastLimitAt??0)<fn?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:a?`${q(o)} of OpenCrater compute is ready. Continue this ${a.name} session now: ${a.resume}`:`${q(o)} of OpenCrater compute is ready. Run your coding agent on it: ${se}`,url:ie,cta:a?a.resume:se}}:u-(p.lastBackupAt??0)>=dn?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:a?`${q(o)} of OpenCrater compute waiting${d}. When you hit your limit: ${a.resume}`:`${q(o)} of OpenCrater compute waiting${d}. Spend it any time: ${se}`,url:ie,cta:a?a.resume:se}}:null}var wn=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function ve(t){return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"}function Sn(t){return ve(t.OPENCRATER_DISABLE)||ve(t.TSN_DISABLE)}function vn(t){return wn.some(o=>ve(t[o]))}function ce(t){return t?{...B,...t}:B}function ut(t,o={}){if(Sn(t.env))return "env_disabled";if(t.state.optOut)return "opt_out";let e=ce(t.state.cachedConfig);if(e.killSwitch)return "kill_switch";if(vn(t.env))return "ci";if(!o.skipTTY&&false);if(!o.skipFrequency){let r=e.minIntervalSeconds*1e3;if(t.state.lastShownAt>0&&t.now-t.state.lastShownAt<r)return "frequency"}return null}var xn=new Set(["the","and","for","but","not","you","all","any","can","this","that","with","have","will","your","from","they","what","when","where","how","why","make","fix","add","update","remove","create","delete","change","error","errors","bug","bugs","file","files","code","test","tests","run","running","build","please","help","want","need","should","would","could","into","about","then","here","there","now","new","use","using","used","work","working","works","check","show","see","look","get","set","let","lets","dont","cant","issue"]);function Cn(t){if(t.includes("/")||t.includes("\\")||t.includes("@")||t.includes("://"))return true;let o=t.toLowerCase();return !!(/^(sk|pk|rk|ock|ghp|gho|ghs|xox|akia|eyj|npm|glpat)[-_]/.test(o)||t.length>=16&&/^[0-9a-f]+$/i.test(t)||t.length>=20&&/^[A-Za-z0-9+/=_-]+$/.test(t)&&/[A-Z]/.test(t)&&/[0-9]/.test(t))}function Tn(t,o=12){let e=[];for(let r of t.slice(0,2e3).split(/\s+/))if(!(!r||Cn(r)))for(let n of r.split(/[^A-Za-z0-9+#.]+|(?<=[a-z0-9])(?=[A-Z])/)){let c=n.replace(/^[.]+|[.]+$/g,"").toLowerCase();if(!(c.length<3||c.length>24)&&!(/^\d+$/.test(c)||xn.has(c))&&!e.includes(c)&&(e.push(c),e.length>=o))return e}return e}function xe(t){let o=[];typeof t.prompt=="string"&&o.push(t.prompt);let e=t.cwd;if(typeof e=="string"&&e.length>0){let r=e.replace(/[\\/]+$/,""),n=r.split(/[\\/]/).pop()??"",c=(process.env.HOME??process.env.USERPROFILE??"").replace(/[\\/]+$/,""),f=process.env.USER??process.env.USERNAME??"";r!==c&&n!==f&&n.length>0&&o.push(n.replace(/[-_]/g," "));}return Tn(o.join(" "))}function Ce(t,o,e){let r=new Map;for(let{topic:n,at:c}of t)e-c<216e5&&r.set(n,c);for(let n of o)r.set(n,e);return [...r.entries()].map(([n,c])=>({topic:n,at:c})).sort((n,c)=>c.at-n.at).slice(0,24)}function dt(t,o){return t.filter(({at:e})=>o-e<216e5).sort((e,r)=>r.at-e.at).slice(0,12).map(({topic:e})=>e)}var En=false,On=process.platform==="win32"?8e3:3200,An=150,_n=2800,Te="claude_code";function In(t){let o={host:"claude_code"};for(let e=0;e<t.length;e++){let r=t[e],n=t[e+1];switch(r){case "--placement":n!==void 0&&(o.placement=n,e++);break;case "--key":n!==void 0&&(o.key=n,e++);break;case "--package":n!==void 0&&(o.package=n,e++);break;case "--host":(n==="claude_code"||n==="codex"||n==="openclaw"||n==="antigravity"||n==="copilot_cli"||n==="grok_cli"||n==="generic")&&(o.host=n,e++);break;}}return o}function Pn(t){return new Promise(o=>{if(process.stdin.isTTY){o("");return}let e="",r=false,n=()=>{r||(r=true,o(e));},c=setTimeout(n,t);c.unref?.(),process.stdin.setEncoding("utf8"),process.stdin.on("data",f=>{e+=f;}),process.stdin.on("end",()=>{clearTimeout(c),n();}),process.stdin.on("error",()=>{clearTimeout(c),n();});})}var Nn="\\\\.\\CONOUT$";function $n(t){return !t||t==="?"||t==="??"||t==="-"?null:t.startsWith("/")?t:`/dev/${t}`}function Mn(t){let o=t.match(/^\s*(\d+)\s+(\S+)/);return o?{ppid:Number(o[1]),tty:o[2]}:null}function Ln(t){if(!Number.isInteger(t)||t<=0)return null;let o=t>>8&4095,e=t&255|t>>12&1048320;return o>=136&&o<=143?`/dev/pts/${(o-136)*256+e}`:o===4?e<64?`/dev/tty${e}`:`/dev/ttyS${e-64}`:null}function Dn(t){let o=t.lastIndexOf(")");if(o<0)return null;let e=t.slice(o+1).trim().split(/\s+/),r=Number(e[1]),n=Number(e[4]);return !Number.isInteger(r)||!Number.isInteger(n)?null:{ppid:r,ttyNr:n}}function Wn(t){try{let o=Dn(h__namespace.readFileSync(`/proc/${t}/stat`,"utf8"));if(o)return {ppid:o.ppid,ttyPath:Ln(o.ttyNr)}}catch{}try{let o=child_process.spawnSync("ps",["-o","ppid=,tty=","-p",String(t)],{encoding:"utf8",timeout:1500}).stdout?.trim();if(!o)return null;let e=Mn(o);return e?{ppid:e.ppid,ttyPath:$n(e.tty)}:null}catch{return null}}function Hn(){if(process.platform==="win32")return {path:Nn,ownerPid:null};let t=process.pid;for(let o=0;o<12&&t>1;o++){let e=Wn(t);if(!e)return null;if(e.ttyPath)return {path:e.ttyPath,ownerPid:t};t=e.ppid;}return null}function Bn(t){return t==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function G(t,o,e,r,n,c){try{let f=y__namespace.join(__dirname,"paint.js"),p,u;if(c&&r){let g=J();c.kind==="dev"?(p=`${g}/v1/dev/impression`,u=c.token):p=`${g}/v1/events/impression`;}let a=ce(o.cachedConfig),d=Math.min(Math.max(a.displayDurationSeconds??25,3),120),s={...t,format:e?.format,mediaUrl:e?.mediaUrl,mediaPixelUrl:e?.mediaPixelUrl,audioUrl:e?.audioUrl,impressionId:r,campaignId:n,apiOrigin:J(),reportImpressionUrl:p,reportImpressionAuth:u,durationMs:d*1e3,disclosure:!o.disclosureShown,host:Te},i={...process.env,OPENCRATER_PAINT:JSON.stringify(s)};if(!i.OPENCRATER_TTY){let g=Hn();g&&(i.OPENCRATER_TTY=g.path,g.ownerPid!==null&&(i.OPENCRATER_HOST_PID=String(g.ownerPid)));}let b=child_process.spawn(process.execPath,[f],{...Bn(process.platform),env:i});process.platform==="win32"?await new Promise(g=>{let m=!1,l=()=>{m||(m=!0,g());};b.on("exit",l),b.on("error",l),setTimeout(l,7500);}):b.unref();}catch{}return {...o,lastShownAt:Date.now(),disclosureShown:true}}function pt(t){if(process.platform!=="win32")return false;try{let o=y__namespace.join(N__namespace.homedir(),".config","opencrater","painter.lock"),e=JSON.parse(h__namespace.readFileSync(o,"utf8"));if(typeof e.startedAt!="number"||Date.now()-e.startedAt>t+1500)return !1;if(typeof e.pid=="number")try{process.kill(e.pid,0);}catch(r){if(r.code==="ESRCH")return !1}return !0}catch{return false}}var Un=8e3;function mt(){let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","render.lock");try{let o=h__namespace.statSync(t);if(Date.now()-o.mtimeMs<Un)return !1;h__namespace.unlinkSync(t);}catch{}try{return h__namespace.mkdirSync(y__namespace.join(N__namespace.homedir(),".config","opencrater"),{recursive:!0}),h__namespace.writeFileSync(t,String(process.pid),{flag:"wx"}),!0}catch{return false}}function Fn(t,o,e,r){if(!o)return true;let n=t.allowedPlacements[`${o}:${e}`];return n?n.includes(r):o==="opencrater"?Oe[e].includes(r):true}var qn=1440*60*1e3;function Gn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime"),o=y__namespace.join(t,"node_modules","opencrater","dist","hook.js"),e=y__namespace.join(t,".last-update");if(h__namespace.existsSync(o)){try{if(Date.now()-h__namespace.statSync(e).mtimeMs<qn)return}catch{}try{h__namespace.writeFileSync(e,String(Date.now()));}catch{return}}else {let r=y__namespace.join(t,".installing");try{h__namespace.mkdirSync(t,{recursive:!0});let n=h__namespace.statSync(r);if(Date.now()-n.mtimeMs<600*1e3)return}catch{}h__namespace.writeFileSync(r,String(Date.now()));}we(t);}catch{}}function gt(t,o){if(!o)return false;let e=f=>f.split(/[-+]/)[0].split(".").map(p=>parseInt(p,10)||0),r=e(t),n=e(o),c=Math.max(r.length,n.length);for(let f=0;f<c;f++){let p=r[f]??0,u=n[f]??0;if(p!==u)return p<u}return false}function ht(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime"),o=y__namespace.join(t,".last-update"),e=y__namespace.join(t,".force-update");try{if(Date.now()-h__namespace.statSync(e).mtimeMs<600*1e3)return}catch{}h__namespace.mkdirSync(t,{recursive:!0}),h__namespace.writeFileSync(e,String(Date.now()));try{h__namespace.rmSync(o,{force:!0});}catch{}we(t);}catch{}}function zn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater");h__namespace.mkdirSync(t,{recursive:!0}),h__namespace.writeFileSync(y__namespace.join(t,"activity.signal"),String(Date.now()));}catch{}}var Jn=1440*60*1e3;function Kn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater"),o=y__namespace.join(t,".last-host-check"),e=y__namespace.join(t,".known-hosts"),r=y__namespace.join(t,".wired-version"),n=be().sort(),c=[];try{let d=JSON.parse(h__namespace.readFileSync(e,"utf8"));Array.isArray(d)&&(c=d.filter(s=>typeof s=="string"));}catch{}let f=n.some(d=>!c.includes(d)),p="";try{p=h__namespace.readFileSync(r,"utf8").trim();}catch{}if(!f&&!(p!==A))try{if(Date.now()-h__namespace.statSync(o).mtimeMs<Jn)return}catch{}h__namespace.mkdirSync(t,{recursive:!0});try{h__namespace.writeFileSync(o,String(Date.now()));}catch{return}let a=de();try{h__namespace.writeFileSync(e,JSON.stringify(n)),h__namespace.writeFileSync(r,A);}catch{}if(a.optOut)return;if(a.devToken)try{ke();}catch{}for(let d of a.integrations)try{ke(d.key,d.package);}catch{}}catch{}}async function Yn(){let t=In(process.argv.slice(2));if(Te=t.host,process.env.GROK_HOOK_EVENT&&Te!=="grok_cli")return;zn(),Gn(),Kn();let o=await Pn(An),e={};if(o)try{e=JSON.parse(o);let m=e.hook_event_name;!t.placement&&typeof m=="string"&&(t.placement=m);}catch{}let r=t.placement??"SessionStart",n=de();x(`state=${X()} devToken=${n.devToken?"present":"MISSING"}`,`host=${t.host} placement=${r}`);let c=ut({env:process.env,state:n,now:Date.now()},{skipTTY:true});if(c!==null){if(c==="frequency"){let m=xe(e);m.length>0&&C({...n,sessionTopics:Ce(n.sessionTopics,m,Date.now())});}x("hook suppressed:",c);return}if(n={...n,sessionTopics:Ce(n.sessionTopics,xe(e),Date.now())},!Fn(n,t.package,t.host,r)){C(n),x("hook gated: placement",r,"not selected for",t.package);return}let f=ce(n.cachedConfig),p=J(),u=typeof e?.cwd=="string"&&e.cwd||process.cwd(),a=Me(u),d=n.attrTags??[];if(n.attrTagsCwd!==a||!n.attrTagsAt||Date.now()-n.attrTagsAt>K){try{d=Le(u);}catch{d=[];}n={...n,attrTags:d,attrTagsCwd:a,attrTagsAt:Date.now()};}let s={origin:p,timeoutMs:Math.min(f.serveTimeoutMs,_n),installId:n.installId,topics:dt(n.sessionTopics,Date.now()),tags:d};if(n.devToken){let m=await $e(n.devToken,{publisherKey:t.key??"",packageName:t.package??"",placement:r,host:t.host},s);if(m){if(n={...n,cachedConfig:m.config,configFetchedAt:Date.now()},gt(A,m.config.minSdkVersion)&&ht(),En);let l=t.host??"claude_code",I=nt(l,r),k=n.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};I&&(k.turns+=1);let j=rt({balanceMicroUsd:typeof m.computeBalanceMicroUsd=="number"?m.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof m.weeklyGrantMicroUsd=="number"?m.weeklyGrantMicroUsd:null,pendingMicroUsd:typeof m.pendingMicroUsd=="number"?m.pendingMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway")||process.env.OPENCRATER_ON_GATEWAY==="1",turnEnd:I,hostName:l,host:tt(l),cc:k,now:Date.now()}),le=(m.config.displayDurationSeconds??25)*1e3,T=m.fill&&m.blip&&!Z(m.blip.campaignId)&&!ee(m.blip.campaignId)?m.blip:null;if((j||T)&&!pt(le)&&mt())if(j){let R=Date.now();j.kind==="limit"?k.lastLimitAt=R:j.kind==="depleted"?k.lastDepletedAt=R:j.kind==="backup"&&(k.lastBackupAt=R),n=await G({...j.card,label:"OpenCrater"},n);}else T&&(Q(T.campaignId),n=await G(Y(T),n,T.creative,T.impressionId,T.campaignId,n.devToken?{kind:"dev",token:n.devToken}:void 0));n={...n,computeCards:k};}C(n);return}let{blip:i,pool:b}=me(n,Date.now());for(;i&&(Z(i.campaignId)||ee(i.campaignId));)x("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:i,pool:b}=me({pool:b},Date.now());if((i||t.key)&&pt((f.displayDurationSeconds??25)*1e3)){C(n),x("hook: a card is already on screen \u2014 not rendering another");return}if((i||t.key)&&!mt()){C(n),x("hook: render slot already claimed by a concurrent fire");return}if(i){Q(i.campaignId),n=await G(Y(i),{...n,pool:b},i.creative,i.impressionId,i.campaignId,{kind:"publisher"}),C(n);return}if(b.length!==n.pool.length&&(n={...n,pool:b}),!t.key||!t.package){C(n),x("hook: pool empty and no --key/--package; nothing to render");return}let g=await Ne({publisherKey:t.key,packageName:t.package,placement:r,host:t.host},s);if(!g){C(n);return}if(n={...n,cachedConfig:g.config,configFetchedAt:Date.now()},gt(A,g.config.minSdkVersion)&&(x(`SDK ${A} below floor ${g.config.minSdkVersion} \u2014 forcing runtime update`),ht()),t.package&&g.allowedPlacements&&(n={...n,allowedPlacements:{...n.allowedPlacements,[`${t.package}:${t.host}`]:g.allowedPlacements}}),g.fill&&g.blip){if(Z(g.blip.campaignId)||ee(g.blip.campaignId)){x("hook: served blip suppressed \u2014 campaign inside a local cooldown"),C(n);return}Q(g.blip.campaignId),n=await G(Y(g.blip),n,g.blip.creative,g.blip.impressionId,g.blip.campaignId,{kind:"publisher"}),C(n);return}g.fallback&&(n=await G(We(g.fallback),n)),C(n);}if(typeof M<"u"&&typeof module<"u"&&M.main===module){let t=setTimeout(()=>process.exit(0),On);Yn().catch(o=>x(`opencrater-hook v${A} error:`,o)).finally(()=>{clearTimeout(t),process.exit(0);});}
|
|
13
|
-
exports.decodeTtyNr=
|
|
12
|
+
`;}return o}function on(t){try{let o=y__namespace.join(re("grok_cli",t),"config.toml"),e="";try{e=h__namespace.readFileSync(o,"utf8");}catch{}let r=nn(e);if(r===e)return;h__namespace.mkdirSync(y__namespace.dirname(o),{recursive:!0}),h__namespace.writeFileSync(o,r,"utf8");}catch{}}function rn(t,o,e){let r=Ve(t);return r.length===0?"nochange":(t==="grok_cli"&&on(process.env),t==="copilot_cli"?tn(t,o,e,r):t==="antigravity"?Qt(o,e,r):Kt(t,o,e,r))}function Se(t,o,e=process.env){return we(e).map(r=>{try{let n=rn(r,t,o);return {host:r,status:n,events:Ve(r)}}catch(n){return {host:r,status:"error",events:[],error:n.message}}})}function an(){return y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime")}function cn(t){return ["install","--prefix",t,"opencrater@latest","--silent","--no-audit","--no-fund"]}function ve(t=an()){child_process.spawn("npm",cn(t),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var et={atLimit:false,resetAt:null};function tt(t,o=N__namespace.homedir()){try{if(t==="claude_code")return ln(o);if(t==="codex")return fn(o)}catch{}return et}function ln(t){let o=h__namespace.readFileSync(y__namespace.join(t,".claude.json"),"utf8"),e=JSON.parse(o),r=e.hasAvailableSubscription===false||e.cachedExtraUsageDisabledReason==="out_of_credits",n=null,p=e.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof p=="string"){let u=Date.parse(p);Number.isFinite(u)&&(n=u);}return {atLimit:r,resetAt:n}}function fn(t){return h__namespace.accessSync(y__namespace.join(t,".codex","auth.json")),et}function nt(t,o){return t==="copilot_cli"?o==="agentStop":o==="Stop"}var ot=36e5,un=30*6e4,dn=30*6e4,pn=4*ot,mn=3,ae="https://opencrater.to/dashboard";function q(t){return `${Math.round(t/1e3).toLocaleString()} tokens`}function gn(t){let o=t/1e3;return o>0&&o<10?`${(Math.round(o*10)/10).toFixed(1)} tokens`:`${Math.round(o).toLocaleString()} tokens`}function hn(t){switch(t){case "claude_code":return {name:"Claude Code",launch:"opencrater claude",resume:"opencrater claude -c"};case "codex":return {name:"Codex",launch:"opencrater codex",resume:"opencrater codex -c"};case "grok_cli":return {name:"Grok",launch:"opencrater grok",resume:"opencrater grok -c"};default:return null}}var ce="opencrater claude";function yn(t,o){if(!t||t<=o)return "";let e=t-o,r=e>=864e5?`${Math.floor(e/864e5)}d`:`${Math.max(1,Math.floor(e/ot))}h`,n=new Date(t).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${n}).`}function rt(t){let{balanceMicroUsd:o,pendingMicroUsd:e,onGateway:r,turnEnd:n,hostName:c,host:f,cc:p,now:u}=t;if(o===null)return null;let a=hn(c),d=e&&e>0?` (+${gn(e)} pending)`:"";return o<=0?u-(p.lastDepletedAt??0)<dn?null:{kind:"depleted",card:{sponsorLabel:"OpenCrater",title:"Compute used up",body:`Keep coding in any CLI to earn more compute, then switch back to ${a?.name??"your plan"}.`+yn(f.resetAt,u),url:ae,cta:"Earn more"}}:r?!n||(p.turns??0)%mn!==0?null:{kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:`${q(o)} compute available${d}.`,url:ae,cta:"Wallet"}}:f.atLimit?u-(p.lastLimitAt??0)<un?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:a?`${q(o)} of OpenCrater compute is ready. Continue this ${a.name} session now: ${a.resume}`:`${q(o)} of OpenCrater compute is ready. Run your coding agent on it: ${ce}`,url:ae,cta:a?a.resume:ce}}:u-(p.lastBackupAt??0)>=pn?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:a?`${q(o)} of OpenCrater compute waiting${d}. When you hit your limit: ${a.resume}`:`${q(o)} of OpenCrater compute waiting${d}. Spend it any time: ${ce}`,url:ae,cta:a?a.resume:ce}}:null}var Sn=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Ce(t){return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"}function vn(t){return Ce(t.OPENCRATER_DISABLE)||Ce(t.TSN_DISABLE)}function xn(t){return Sn.some(o=>Ce(t[o]))}function fe(t){return t?{...H,...t}:H}function ut(t,o={}){if(vn(t.env))return "env_disabled";if(t.state.optOut)return "opt_out";let e=fe(t.state.cachedConfig);if(e.killSwitch)return "kill_switch";if(xn(t.env))return "ci";if(!o.skipTTY&&false);if(!o.skipFrequency){let r=e.minIntervalSeconds*1e3;if(t.state.lastShownAt>0&&t.now-t.state.lastShownAt<r)return "frequency"}return null}var Cn=new Set(["the","and","for","but","not","you","all","any","can","this","that","with","have","will","your","from","they","what","when","where","how","why","make","fix","add","update","remove","create","delete","change","error","errors","bug","bugs","file","files","code","test","tests","run","running","build","please","help","want","need","should","would","could","into","about","then","here","there","now","new","use","using","used","work","working","works","check","show","see","look","get","set","let","lets","dont","cant","issue"]);function Tn(t){if(t.includes("/")||t.includes("\\")||t.includes("@")||t.includes("://"))return true;let o=t.toLowerCase();return !!(/^(sk|pk|rk|ock|ghp|gho|ghs|xox|akia|eyj|npm|glpat)[-_]/.test(o)||t.length>=16&&/^[0-9a-f]+$/i.test(t)||t.length>=20&&/^[A-Za-z0-9+/=_-]+$/.test(t)&&/[A-Z]/.test(t)&&/[0-9]/.test(t))}function jn(t,o=12){let e=[];for(let r of t.slice(0,2e3).split(/\s+/))if(!(!r||Tn(r)))for(let n of r.split(/[^A-Za-z0-9+#.]+|(?<=[a-z0-9])(?=[A-Z])/)){let c=n.replace(/^[.]+|[.]+$/g,"").toLowerCase();if(!(c.length<3||c.length>24)&&!(/^\d+$/.test(c)||Cn.has(c))&&!e.includes(c)&&(e.push(c),e.length>=o))return e}return e}function Te(t){let o=[];typeof t.prompt=="string"&&o.push(t.prompt);let e=t.cwd;if(typeof e=="string"&&e.length>0){let r=e.replace(/[\\/]+$/,""),n=r.split(/[\\/]/).pop()??"",c=(process.env.HOME??process.env.USERPROFILE??"").replace(/[\\/]+$/,""),f=process.env.USER??process.env.USERNAME??"";r!==c&&n!==f&&n.length>0&&o.push(n.replace(/[-_]/g," "));}return jn(o.join(" "))}function je(t,o,e){let r=new Map;for(let{topic:n,at:c}of t)e-c<216e5&&r.set(n,c);for(let n of o)r.set(n,e);return [...r.entries()].map(([n,c])=>({topic:n,at:c})).sort((n,c)=>c.at-n.at).slice(0,24)}function dt(t,o){return t.filter(({at:e})=>o-e<216e5).sort((e,r)=>r.at-e.at).slice(0,12).map(({topic:e})=>e)}var On=false,An=process.platform==="win32"?8e3:3200,_n=150,In=2800,Re="claude_code";function Pn(t){let o={host:"claude_code"};for(let e=0;e<t.length;e++){let r=t[e],n=t[e+1];switch(r){case "--placement":n!==void 0&&(o.placement=n,e++);break;case "--key":n!==void 0&&(o.key=n,e++);break;case "--package":n!==void 0&&(o.package=n,e++);break;case "--host":(n==="claude_code"||n==="codex"||n==="openclaw"||n==="antigravity"||n==="copilot_cli"||n==="grok_cli"||n==="generic")&&(o.host=n,e++);break;}}return o}function Nn(t){return new Promise(o=>{if(process.stdin.isTTY){o("");return}let e="",r=false,n=()=>{r||(r=true,o(e));},c=setTimeout(n,t);c.unref?.(),process.stdin.setEncoding("utf8"),process.stdin.on("data",f=>{e+=f;}),process.stdin.on("end",()=>{clearTimeout(c),n();}),process.stdin.on("error",()=>{clearTimeout(c),n();});})}var $n="\\\\.\\CONOUT$";function Mn(t){return !t||t==="?"||t==="??"||t==="-"?null:t.startsWith("/")?t:`/dev/${t}`}function Ln(t){let o=t.match(/^\s*(\d+)\s+(\S+)/);return o?{ppid:Number(o[1]),tty:o[2]}:null}function Dn(t){if(!Number.isInteger(t)||t<=0)return null;let o=t>>8&4095,e=t&255|t>>12&1048320;return o>=136&&o<=143?`/dev/pts/${(o-136)*256+e}`:o===4?e<64?`/dev/tty${e}`:`/dev/ttyS${e-64}`:null}function Wn(t){let o=t.lastIndexOf(")");if(o<0)return null;let e=t.slice(o+1).trim().split(/\s+/),r=Number(e[1]),n=Number(e[4]);return !Number.isInteger(r)||!Number.isInteger(n)?null:{ppid:r,ttyNr:n}}function Hn(t){try{let o=Wn(h__namespace.readFileSync(`/proc/${t}/stat`,"utf8"));if(o)return {ppid:o.ppid,ttyPath:Dn(o.ttyNr)}}catch{}try{let o=child_process.spawnSync("ps",["-o","ppid=,tty=","-p",String(t)],{encoding:"utf8",timeout:1500}).stdout?.trim();if(!o)return null;let e=Ln(o);return e?{ppid:e.ppid,ttyPath:Mn(e.tty)}:null}catch{return null}}function Bn(){if(process.platform==="win32")return {path:$n,ownerPid:null};let t=process.pid;for(let o=0;o<12&&t>1;o++){let e=Hn(t);if(!e)return null;if(e.ttyPath)return {path:e.ttyPath,ownerPid:t};t=e.ppid;}return null}function Un(t){return t==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function G(t,o,e,r,n,c){try{let f=y__namespace.join(__dirname,"paint.js"),p,u;if(c&&r){let g=J();c.kind==="dev"?(p=`${g}/v1/dev/impression`,u=c.token):p=`${g}/v1/events/impression`;}let a=fe(o.cachedConfig),d=Math.min(Math.max(a.displayDurationSeconds??25,3),120),s={...t,format:e?.format,mediaUrl:e?.mediaUrl,mediaPixelUrl:e?.mediaPixelUrl,audioUrl:e?.audioUrl,impressionId:r,campaignId:n,apiOrigin:J(),reportImpressionUrl:p,reportImpressionAuth:u,durationMs:d*1e3,disclosure:!o.disclosureShown,host:Re},i={...process.env,OPENCRATER_PAINT:JSON.stringify(s)};if(!i.OPENCRATER_TTY){let g=Bn();g&&(i.OPENCRATER_TTY=g.path,g.ownerPid!==null&&(i.OPENCRATER_HOST_PID=String(g.ownerPid)));}let b=child_process.spawn(process.execPath,[f],{...Un(process.platform),env:i});process.platform==="win32"?await new Promise(g=>{let m=!1,l=()=>{m||(m=!0,g());};b.on("exit",l),b.on("error",l),setTimeout(l,7500);}):b.unref();}catch{}return {...o,lastShownAt:Date.now(),disclosureShown:true}}function pt(t){if(process.platform!=="win32")return false;try{let o=y__namespace.join(N__namespace.homedir(),".config","opencrater","painter.lock"),e=JSON.parse(h__namespace.readFileSync(o,"utf8"));if(typeof e.startedAt!="number"||Date.now()-e.startedAt>t+1500)return !1;if(typeof e.pid=="number")try{process.kill(e.pid,0);}catch(r){if(r.code==="ESRCH")return !1}return !0}catch{return false}}var Fn=8e3;function mt(){let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","render.lock");try{let o=h__namespace.statSync(t);if(Date.now()-o.mtimeMs<Fn)return !1;h__namespace.unlinkSync(t);}catch{}try{return h__namespace.mkdirSync(y__namespace.join(N__namespace.homedir(),".config","opencrater"),{recursive:!0}),h__namespace.writeFileSync(t,String(process.pid),{flag:"wx"}),!0}catch{return false}}function qn(t,o,e,r){if(!o)return true;let n=t.allowedPlacements[`${o}:${e}`];return n?n.includes(r):o==="opencrater"?_e[e].includes(r):true}var Gn=1440*60*1e3;function zn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime"),o=y__namespace.join(t,"node_modules","opencrater","dist","hook.js"),e=y__namespace.join(t,".last-update");if(h__namespace.existsSync(o)){try{if(Date.now()-h__namespace.statSync(e).mtimeMs<Gn)return}catch{}try{h__namespace.writeFileSync(e,String(Date.now()));}catch{return}}else {let r=y__namespace.join(t,".installing");try{h__namespace.mkdirSync(t,{recursive:!0});let n=h__namespace.statSync(r);if(Date.now()-n.mtimeMs<600*1e3)return}catch{}h__namespace.writeFileSync(r,String(Date.now()));}ve(t);}catch{}}function gt(t,o){if(!o)return false;let e=f=>f.split(/[-+]/)[0].split(".").map(p=>parseInt(p,10)||0),r=e(t),n=e(o),c=Math.max(r.length,n.length);for(let f=0;f<c;f++){let p=r[f]??0,u=n[f]??0;if(p!==u)return p<u}return false}function ht(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime"),o=y__namespace.join(t,".last-update"),e=y__namespace.join(t,".force-update");try{if(Date.now()-h__namespace.statSync(e).mtimeMs<600*1e3)return}catch{}h__namespace.mkdirSync(t,{recursive:!0}),h__namespace.writeFileSync(e,String(Date.now()));try{h__namespace.rmSync(o,{force:!0});}catch{}ve(t);}catch{}}function Jn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater");h__namespace.mkdirSync(t,{recursive:!0}),h__namespace.writeFileSync(y__namespace.join(t,"activity.signal"),String(Date.now()));}catch{}}var Kn=1440*60*1e3;function Yn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater"),o=y__namespace.join(t,".last-host-check"),e=y__namespace.join(t,".known-hosts"),r=y__namespace.join(t,".wired-version"),n=we().sort(),c=[];try{let d=JSON.parse(h__namespace.readFileSync(e,"utf8"));Array.isArray(d)&&(c=d.filter(s=>typeof s=="string"));}catch{}let f=n.some(d=>!c.includes(d)),p="";try{p=h__namespace.readFileSync(r,"utf8").trim();}catch{}if(!f&&!(p!==A))try{if(Date.now()-h__namespace.statSync(o).mtimeMs<Kn)return}catch{}h__namespace.mkdirSync(t,{recursive:!0});try{h__namespace.writeFileSync(o,String(Date.now()));}catch{return}let a=me();try{h__namespace.writeFileSync(e,JSON.stringify(n)),h__namespace.writeFileSync(r,A);}catch{}if(a.optOut)return;if(a.devToken)try{Se();}catch{}for(let d of a.integrations)try{Se(d.key,d.package);}catch{}}catch{}}async function Vn(){let t=Pn(process.argv.slice(2));if(Re=t.host,process.env.GROK_HOOK_EVENT&&Re!=="grok_cli")return;Jn(),zn(),Yn();let o=await Nn(_n),e={};if(o)try{e=JSON.parse(o);let m=e.hook_event_name;!t.placement&&typeof m=="string"&&(t.placement=m);}catch{}let r=t.placement??"SessionStart",n=me();x(`state=${X()} devToken=${n.devToken?"present":"MISSING"}`,`host=${t.host} placement=${r}`);let c=ut({env:process.env,state:n,now:Date.now()},{skipTTY:true});if(c!==null){if(c==="frequency"){let m=Te(e);m.length>0&&C({...n,sessionTopics:je(n.sessionTopics,m,Date.now())});}x("hook suppressed:",c);return}if(n={...n,sessionTopics:je(n.sessionTopics,Te(e),Date.now())},!qn(n,t.package,t.host,r)){C(n),x("hook gated: placement",r,"not selected for",t.package);return}let f=fe(n.cachedConfig),p=J(),u=typeof e?.cwd=="string"&&e.cwd||process.cwd(),a=De(u),d=n.attrTags??[];if(n.attrTagsCwd!==a||!n.attrTagsAt||Date.now()-n.attrTagsAt>K){try{d=We(u);}catch{d=[];}n={...n,attrTags:d,attrTagsCwd:a,attrTagsAt:Date.now()};}let s={origin:p,timeoutMs:Math.min(f.serveTimeoutMs,In),installId:n.installId,topics:dt(n.sessionTopics,Date.now()),tags:d};if(n.devToken){let m=await Le(n.devToken,{publisherKey:t.key??"",packageName:t.package??"",placement:r,host:t.host},s);if(m){if(n={...n,cachedConfig:m.config,configFetchedAt:Date.now()},gt(A,m.config.minSdkVersion)&&ht(),On);let l=t.host??"claude_code",I=nt(l,r),k=n.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};I&&(k.turns+=1);let j=rt({balanceMicroUsd:typeof m.computeBalanceMicroUsd=="number"?m.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof m.weeklyGrantMicroUsd=="number"?m.weeklyGrantMicroUsd:null,pendingMicroUsd:typeof m.pendingMicroUsd=="number"?m.pendingMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway")||process.env.OPENCRATER_ON_GATEWAY==="1",turnEnd:I,hostName:l,host:tt(l),cc:k,now:Date.now()}),ue=(m.config.displayDurationSeconds??25)*1e3,T=m.fill&&m.blip&&!Z(m.blip.campaignId)&&!ee(m.blip.campaignId)?m.blip:null;if((j||T)&&!pt(ue)&&mt())if(j){let R=Date.now();j.kind==="limit"?k.lastLimitAt=R:j.kind==="depleted"?k.lastDepletedAt=R:j.kind==="backup"&&(k.lastBackupAt=R),n=await G({...j.card,label:"OpenCrater"},n);}else T&&(Q(T.campaignId),n=await G(Y(T),n,T.creative,T.impressionId,T.campaignId,n.devToken?{kind:"dev",token:n.devToken}:void 0));n={...n,computeCards:k};}C(n);return}let{blip:i,pool:b}=he(n,Date.now());for(;i&&(Z(i.campaignId)||ee(i.campaignId));)x("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:i,pool:b}=he({pool:b},Date.now());if((i||t.key)&&pt((f.displayDurationSeconds??25)*1e3)){C(n),x("hook: a card is already on screen \u2014 not rendering another");return}if((i||t.key)&&!mt()){C(n),x("hook: render slot already claimed by a concurrent fire");return}if(i){Q(i.campaignId),n=await G(Y(i),{...n,pool:b},i.creative,i.impressionId,i.campaignId,{kind:"publisher"}),C(n);return}if(b.length!==n.pool.length&&(n={...n,pool:b}),!t.key||!t.package){C(n),x("hook: pool empty and no --key/--package; nothing to render");return}let g=await Me({publisherKey:t.key,packageName:t.package,placement:r,host:t.host},s);if(!g){C(n);return}if(n={...n,cachedConfig:g.config,configFetchedAt:Date.now()},gt(A,g.config.minSdkVersion)&&(x(`SDK ${A} below floor ${g.config.minSdkVersion} \u2014 forcing runtime update`),ht()),t.package&&g.allowedPlacements&&(n={...n,allowedPlacements:{...n.allowedPlacements,[`${t.package}:${t.host}`]:g.allowedPlacements}}),g.fill&&g.blip){if(Z(g.blip.campaignId)||ee(g.blip.campaignId)){x("hook: served blip suppressed \u2014 campaign inside a local cooldown"),C(n);return}Q(g.blip.campaignId),n=await G(Y(g.blip),n,g.blip.creative,g.blip.impressionId,g.blip.campaignId,{kind:"publisher"}),C(n);return}g.fallback&&(n=await G(Be(g.fallback),n)),C(n);}if(typeof M<"u"&&typeof module<"u"&&M.main===module){let t=setTimeout(()=>process.exit(0),An);Vn().catch(o=>x(`opencrater-hook v${A} error:`,o)).finally(()=>{clearTimeout(t),process.exit(0);});}
|
|
13
|
+
exports.decodeTtyNr=Dn;exports.painterSpawnOptions=Un;exports.parseArgs=Pn;exports.parseProcStat=Wn;exports.parsePsLine=Ln;exports.resolveTtyPath=Bn;exports.ttyNameToDevPath=Mn;
|
package/dist/index.d.mts
CHANGED
|
@@ -232,7 +232,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
|
|
|
232
232
|
|
|
233
233
|
/** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
|
|
234
234
|
* AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
|
|
235
|
-
declare const SDK_VERSION = "1.4.
|
|
235
|
+
declare const SDK_VERSION = "1.4.1";
|
|
236
236
|
|
|
237
237
|
/** Public API. Every method is fail-silent: it never throws. */
|
|
238
238
|
declare const sponsor: {
|
package/dist/index.d.ts
CHANGED
|
@@ -232,7 +232,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
|
|
|
232
232
|
|
|
233
233
|
/** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
|
|
234
234
|
* AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
|
|
235
|
-
declare const SDK_VERSION = "1.4.
|
|
235
|
+
declare const SDK_VERSION = "1.4.1";
|
|
236
236
|
|
|
237
237
|
/** Public API. Every method is fail-silent: it never throws. */
|
|
238
238
|
declare const sponsor: {
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
'use strict';var crypto=require('crypto'),m=require('fs'),ie=require('os'),S=require('path');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var m__namespace=/*#__PURE__*/_interopNamespace(m);var ie__namespace=/*#__PURE__*/_interopNamespace(ie);var S__namespace=/*#__PURE__*/_interopNamespace(S);var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var le=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var N="1.4.
|
|
1
|
+
'use strict';var crypto=require('crypto'),m=require('fs'),ie=require('os'),S=require('path');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var m__namespace=/*#__PURE__*/_interopNamespace(m);var ie__namespace=/*#__PURE__*/_interopNamespace(ie);var S__namespace=/*#__PURE__*/_interopNamespace(S);var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var le=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var N="1.4.1";var ce="https://api.opencrater.to";function K(e,n=process.env){let t=n.OPENCRATER_API_ORIGIN;return (e??(t&&t.trim()!==""?t:ce)).replace(/\/+$/,"")}function c(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let n=q("os"),t=q("fs"),o=q("path");t.appendFileSync(o.join(n.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(i=>String(i)).join(" ")}
|
|
2
2
|
`);}catch{}}catch{}}function R(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let n=w;if(typeof e!="object"||e===null)return {...n};let t=e;return {minIntervalSeconds:R(t.minIntervalSeconds)?t.minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:R(t.serveTimeoutMs)?t.serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:R(t.preloadPoolSize)?t.preloadPoolSize:n.preloadPoolSize,killSwitch:t.killSwitch===true,displayDurationSeconds:R(t.displayDurationSeconds)?t.displayDurationSeconds:n.displayDurationSeconds,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:n.minSdkVersion}}async function D(e,n,t,o,i){try{let r=await fetch(`${e}${n}`,{method:"POST",headers:{"content-type":"application/json",...i??{}},body:JSON.stringify(t),signal:AbortSignal.timeout(o)});return r.ok?await r.json():(c(`POST ${n} -> HTTP ${r.status}`),null)}catch(r){return c(`POST ${n} failed:`,r),null}}function J(e,n){let t=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:t,sdkVersion:N,installId:n.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:n.topics&&n.topics.length>0?n.topics:void 0,tags:n.tags&&n.tags.length>0?n.tags:void 0}}function fe(e){if(typeof e!="object"||e===null)return null;let n=e;if(typeof n.fill!="boolean")return null;let t={fill:n.fill,fallback:n.fallback??null,config:V(n.config),...Array.isArray(n.allowedPlacements)?{allowedPlacements:n.allowedPlacements.filter(o=>typeof o=="string")}:{}};return n.blip!==void 0&&n.blip!==null&&(t.blip=n.blip),typeof n.computeBalanceMicroUsd=="number"&&(t.computeBalanceMicroUsd=n.computeBalanceMicroUsd),typeof n.weeklyGrantMicroUsd=="number"&&(t.weeklyGrantMicroUsd=n.weeklyGrantMicroUsd),typeof n.pendingMicroUsd=="number"&&(t.pendingMicroUsd=n.pendingMicroUsd),t}async function F(e,n){let t=await D(n.origin,"/v1/serve",J(e,n),n.timeoutMs);return fe(t)}async function X(e,n,t){let o=await D(t.origin,"/v1/serve/batch",{...J(e,t),count:n},t.timeoutMs);if(typeof o!="object"||o===null)return null;let i=o;return Array.isArray(i.blips)?{blips:i.blips,fallback:i.fallback??null,config:V(i.config),...Array.isArray(i.allowedPlacements)?{allowedPlacements:i.allowedPlacements.filter(r=>typeof r=="string")}:{}}:null}function $(e,n){return D(n.origin,"/v1/events/impression",{impressionId:e},n.timeoutMs).then(()=>{}).catch(()=>{})}var ue=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},de=60,pe=24,me="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function ge(e){return e.replace(ue,"").length}function y(e,n){return n<=0?"":e.length<=n?e:n===1?"\u2026":e.slice(0,n-1).trimEnd()+"\u2026"}function he(e,n,t){let o=e.split(/\s+/).filter(l=>l.length>0),i=[],r="";for(let l of o){let u=r===""?l:`${r} ${l}`;if(u.length<=n)r=u;else if(r!==""&&i.push(r),r=l.length>n?y(l,n):l,i.length>=t)break}r!==""&&i.length<t&&i.push(r),i.length>t&&(i.length=t);let s=i.join(" "),a=i.length-1,f=i[a];return f!==void 0&&s.length<o.join(" ").length&&(i[a]=y(`${f}\u2026`,n)),i}function I(e=process.env,n=!!process.stdout.isTTY){if(!n)return false;if(e.FORCE_HYPERLINK!==void 0&&e.FORCE_HYPERLINK!=="0")return true;let t=e.TERM_PROGRAM??"";return !!(["iTerm.app","WezTerm","ghostty","Hyper","vscode","Tabby"].includes(t)||e.KITTY_WINDOW_ID||e.WT_SESSION||Number(e.VTE_VERSION??"0")>=5e3)}function P(e=process.env,n=!!process.stdout.isTTY){return !(e.NO_COLOR!==void 0&&e.NO_COLOR!==""||!n||(e.TERM??"")==="dumb")}function ye(e,n){return `\x1B]8;;${e}\x07${n}\x1B]8;;\x07`}function E(e){let n={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(n.cta=e.creative.cta),n}function Z(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function h(e,n={}){let t=n.width??process.stdout.columns??80,i=Math.max(pe,Math.min(t,de))-4,r=n.color??P(),s=n.hyperlinks??I(),a=(g,M)=>r?`${M}${g}${k.reset}`:g,f=e.label?y(e.label,i):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,i):"Sponsored Blips",l=[];l.push(a(f,k.dim)),e.title!==e.sponsorLabel&&l.push(a(y(e.title,i),k.bold));for(let g of he(e.body,i,2))l.push(g);let u="\u2192 ";if(s){let g=y(e.cta??e.url,i-u.length);l.push(u+a(ye(e.url,g),k.dim));}else e.cta&&l.push(y(e.cta,i)),l.push(u+a(y(e.url,i-u.length),k.dim));let T=`\u256D${"\u2500".repeat(i+2)}\u256E`,j=`\u2570${"\u2500".repeat(i+2)}\u256F`,L=l.map(g=>{let M=" ".repeat(Math.max(0,i-ge(g)));return `\u2502 ${g}${M} \u2502`}),b=[];return n.disclosure&&b.push(a(me,k.dim)),b.push(T,...L,j),b.join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`}function Q(e){return e!==void 0&&e!==""}function
|
|
4
|
+
`}function Q(e){return e!==void 0&&e!==""}function U(e=process.env,n=!!process.stdout.isTTY){if(!n)return "none";let t=e.TERM??"";if(Q(e.TMUX)||t.startsWith("tmux")||t.startsWith("screen"))return "none";let o=e.TERM_PROGRAM??"";return o==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||o==="WezTerm"?"iterm2":t==="xterm-kitty"||Q(e.KITTY_WINDOW_ID)?"kitty":"none"}var v="\x1B",be="\x07",we=2e3,ke=2*1024*1024,Se=new Set(["image/png","image/jpeg","image/gif","image/webp"]),O=4096;async function ve(e,n=fetch,t={}){let o=t.timeoutMs??we,i=t.maxBytes??ke;try{let r=await n(e,{signal:AbortSignal.timeout(o)});if(!r.ok)return c(`media: HTTP ${r.status} for ${e}`),null;let s=(r.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!Se.has(s))return c(`media: disallowed content-type "${s}" for ${e}`),null;let a=Number(r.headers.get("content-length")??"0");if(Number.isFinite(a)&&a>i)return c(`media: content-length ${a} exceeds ${i} for ${e}`),null;let f=r.body;if(f&&typeof f.getReader=="function"){let u=f.getReader(),T=[],j=0;for(;;){let{done:L,value:b}=await u.read();if(L)break;if(b!==void 0){if(j+=b.byteLength,j>i)return await u.cancel().catch(()=>{}),c(`media: stream exceeded ${i} bytes for ${e}`),null;T.push(b);}}return Buffer.concat(T)}let l=Buffer.from(await r.arrayBuffer());return l.byteLength>i?(c(`media: body ${l.byteLength} bytes exceeds ${i} for ${e}`),null):l}catch(r){return c(`media: fetch failed for ${e}:`,r),null}}function xe(e){let n=e.toString("base64");return `${v}]1337;File=inline=1;size=${e.byteLength};width=auto:${n}${be}`}function Ce(e){let n=e.toString("base64");if(n.length<=O)return `${v}_Gf=100,a=T;${n}${v}\\`;let t=[];for(let o=0;o<n.length;o+=O){let i=n.slice(o,o+O),s=`m=${o+O>=n.length?0:1}`,a=o===0?`f=100,a=T,${s}`:s;t.push(`${v}_G${a};${i}${v}\\`);}return t.join("")}function A(e){let n=E(e),t=e.creative;switch(t.format){case "image":case "gif":return {...n,body:t.textFallback??n.body};case "video":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u25B6 Watch"};case "audio":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u{1F50A} Listen"};default:return n}}async function z(e,n={}){try{let t=e.creative;if(t.format!=="image"&&t.format!=="gif")return h(A(e),n);let o=n.protocol??U();if(o==="none"||t.mediaUrl===void 0||t.mediaUrl==="")return h(A(e),n);let i={};n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs),n.maxBytes!==void 0&&(i.maxBytes=n.maxBytes);let r=await ve(t.mediaUrl,n.fetchImpl??fetch,i);return r===null||r.byteLength===0?h(A(e),n):(o==="kitty"?Ce(r):xe(r))+`
|
|
5
5
|
`+h(E(e),n)}catch(t){return c("media: render failed, falling back to text:",t),h(E(e),n)}}function Te(e,n){return e.filter(t=>t.renderBy>n)}function ee(e,n,t=18e5){return e.filter(o=>o&&typeof o.impressionId=="string"&&typeof o.clickUrl=="string"&&o.creative&&typeof o.creative.title=="string").map(o=>({blip:o,renderBy:n+t}))}function ne(e,n){let t=Te(e.pool,n),o=t.shift();return {blip:o?o.blip:null,pool:t}}var te=360*60*1e3;function Ie(e=process.env){return S__namespace.join(ie__namespace.homedir(),".config","opencrater")}function oe(e=process.env){return S__namespace.join(Ie(e),"state.json")}function W(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function d(e){return typeof e=="number"&&Number.isFinite(e)}var re=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function se(e){for(let n=0;;n++)try{return {text:m__namespace.readFileSync(e,"utf8")}}catch(t){let o=t.code??"";if(!(o==="ENOENT"||re.has(o)))return {locked:true};if(n>=4)return o==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(n+1));}catch{}}}function Pe(e){if(typeof e!="object"||e===null)return null;let n=e;return !d(n.minIntervalSeconds)||!d(n.serveTimeoutMs)||!d(n.preloadPoolSize)||typeof n.killSwitch!="boolean"?null:{minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:n.preloadPoolSize,killSwitch:n.killSwitch,displayDurationSeconds:d(n.displayDurationSeconds)?n.displayDurationSeconds:25,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:""}}function Ee(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t,i=o.blip;if(!d(o.renderBy)||typeof i!="object"||i===null||typeof i.impressionId!="string"||typeof i.clickUrl!="string"||typeof i.sponsorLabel!="string"||typeof i.creative!="object"||i.creative===null)continue;let r=i.creative;typeof r.title!="string"||typeof r.body!="string"||n.push({blip:{impressionId:i.impressionId,...typeof i.campaignId=="string"?{campaignId:i.campaignId}:{},clickUrl:i.clickUrl,sponsorLabel:i.sponsorLabel,creative:{format:"text",title:r.title,body:r.body,...typeof r.cta=="string"?{cta:r.cta}:{}}},renderBy:o.renderBy});}return n}function Oe(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let n={};for(let[t,o]of Object.entries(e)){if(!Array.isArray(o))continue;let i=o.filter(r=>typeof r=="string"&&r.length<=64);n[t]=i.slice(0,64);}return n}function Ae(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t;if(!(typeof o.topic!="string"||!d(o.at))&&(n.push({topic:o.topic.slice(0,32),at:o.at}),n.length>=24))break}return n}function We(e){if(!Array.isArray(e))return [];let n=[],t=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let i=o;if(typeof i.key!="string"||typeof i.package!="string"||i.key===""||i.package==="")continue;let r=`${i.package}\0${i.key}`;if(!t.has(r)&&(t.add(r),n.push({key:i.key,package:i.package}),n.length>=32))break}return n}function Be(e){if(typeof e!="object"||e===null)return null;let n=e,t={};if(typeof n.savedEnv=="object"&&n.savedEnv!==null)for(let[o,i]of Object.entries(n.savedEnv))(typeof i=="string"||i===null)&&(t[o]=i);return {active:n.active===true,savedEnv:t}}function _e(e){if(typeof e!="object"||e===null)return null;let n=e,t=o=>d(o)&&o>=0?o:0;return {turns:t(n.turns),lastLimitAt:t(n.lastLimitAt),lastDepletedAt:t(n.lastDepletedAt),lastBackupAt:t(n.lastBackupAt)}}function Le(e){let n=e.attrTagsAt,t=e.attrTagsCwd;return !d(n)||Date.now()-n>te||typeof t!="string"||t.length===0||t.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(i=>typeof i=="string"&&i.length<=40).slice(0,48):[],attrTagsCwd:t,attrTagsAt:n}}function Me(e){let n=W();if(typeof e!="object"||e===null)return n;let t=e;return {installId:typeof t.installId=="string"&&t.installId.length>0?t.installId:n.installId,lastShownAt:d(t.lastShownAt)&&t.lastShownAt>=0?t.lastShownAt:0,optOut:t.optOut===true,disclosureShown:t.disclosureShown===true,cachedConfig:Pe(t.cachedConfig),allowedPlacements:Oe(t.allowedPlacements),sessionTopics:Ae(t.sessionTopics),integrations:We(t.integrations),devToken:typeof t.devToken=="string"?t.devToken:null,computeRouting:Be(t.computeRouting),computeCards:_e(t.computeCards),configFetchedAt:d(t.configFetchedAt)&&t.configFetchedAt>=0?t.configFetchedAt:0,pool:Ee(t.pool),...Le(t)}}function x(e=process.env){let n=oe(e),t=se(n);if(t.text!==void 0)try{return Me(JSON.parse(t.text))}catch{let o=W();try{p(o,e);}catch{}return o}if(t.missing){let o=W();try{p(o,e);}catch{}return o}return W()}function p(e,n=process.env,t={}){let o=oe(n),i=S__namespace.dirname(o);m__namespace.mkdirSync(i,{recursive:true});let r=se(o),s=null;if(r.text!==void 0)try{s=JSON.parse(r.text);}catch{s=null;}if(s)typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt}),!t.allowClearToken&&typeof s.devToken=="string"&&e.devToken==null&&(e={...e,devToken:s.devToken}),typeof s.installId=="string"&&s.installId.length>0&&s.installId!==e.installId&&(e={...e,installId:s.installId});else if(!t.allowClearToken&&e.devToken==null&&r.text===void 0&&!r.missing)return;let a=S__namespace.join(i,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);m__namespace.writeFileSync(a,JSON.stringify(e,null,2)+`
|
|
6
|
-
`,"utf8");for(let f=0;;f++)try{m__namespace.renameSync(a,o);return}catch(l){let u=l.code??"";if(f>=4||!re.has(u)){try{m__namespace.rmSync(a,{force:!0});}catch{}if(f>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(f+1));}catch{}}}var qe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Y(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return Y(e.OPENCRATER_DISABLE)||Y(e.TSN_DISABLE)}function De(e){return qe.some(n=>Y(e[n]))}function H(e){return e?{...w,...e}:w}function C(e,n={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let t=H(e.state.cachedConfig);if(t.killSwitch)return "kill_switch";if(De(e.env))return "ci";if(!n.skipTTY&&!e.isTTY)return "not_tty";if(!n.skipFrequency){let o=t.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<o)return "frequency"}return null}async function B(e){try{return await e()}catch(n){return c("suppressed error:",n),null}}function _(e,n){let t=H(n.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:t.serveTimeoutMs,installId:n.installId,config:t}}function Fe(e,n){let t=!n.disclosureShown,o=h(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:t});return process.stdout.write(o),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function ae(e,n){let t=await
|
|
6
|
+
`,"utf8");for(let f=0;;f++)try{m__namespace.renameSync(a,o);return}catch(l){let u=l.code??"";if(f>=4||!re.has(u)){try{m__namespace.rmSync(a,{force:!0});}catch{}if(f>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(f+1));}catch{}}}var qe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Y(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return Y(e.OPENCRATER_DISABLE)||Y(e.TSN_DISABLE)}function De(e){return qe.some(n=>Y(e[n]))}function H(e){return e?{...w,...e}:w}function C(e,n={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let t=H(e.state.cachedConfig);if(t.killSwitch)return "kill_switch";if(De(e.env))return "ci";if(!n.skipTTY&&!e.isTTY)return "not_tty";if(!n.skipFrequency){let o=t.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<o)return "frequency"}return null}async function B(e){try{return await e()}catch(n){return c("suppressed error:",n),null}}function _(e,n){let t=H(n.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:t.serveTimeoutMs,installId:n.installId,config:t}}function Fe(e,n){let t=!n.disclosureShown,o=h(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:t});return process.stdout.write(o),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function ae(e,n){let t=await z(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:!n.disclosureShown});return process.stdout.write(t),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function $e(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipFrequency:true});if(t!==null)return c("fetch suppressed:",t),null;let o=_(e,n),i=await F(e,o);return i?(p({...n,cachedConfig:i.config,configFetchedAt:Date.now()}),i.fill&&i.blip?i.blip:null):null}async function Ue(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()});if(t!==null)return c("suppressed:",t),false;let o=_(e,n),i=await F(e,o);return i?(n={...n,cachedConfig:i.config,configFetchedAt:Date.now()},i.fill&&i.blip?(n=await ae(i.blip,n),p(n),$(i.blip.impressionId,o),true):i.fallback?(n=Fe(Z(i.fallback),n),p(n),true):(p(n),false)):false}async function ze(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipTTY:true,skipFrequency:true});if(t!==null)return c("preload suppressed:",t),0;let o=_(e,n),i=Math.max(1,o.config.preloadPoolSize),r=await X(e,i,o);if(!r)return 0;let s=Date.now(),a=ee(r.blips,s);return p({...n,pool:a,cachedConfig:r.config,configFetchedAt:s}),a.length}async function Ge(e){let n=x(),t=Date.now(),o=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:t});if(o!==null)return c("renderFromPool suppressed:",o),false;let{blip:i,pool:r}=ne(n,t);if(!i)return p({...n,pool:r}),false;let s=await ae(i,{...n,pool:r});p(s);let a=_(e,n);return $(i.impressionId,a),true}var kn={show(e){return B(()=>Ue(e)).then(n=>n??false)},fetch(e){return B(()=>$e(e))},preload(e){return B(()=>ze(e)).then(n=>n??0)},renderFromPool(e){return B(()=>Ge(e)).then(n=>n??false)}};exports.DEFAULT_CONFIG=w;exports.HOOK_CATALOG=le;exports.SDK_VERSION=N;exports.detectImageProtocol=U;exports.renderBlip=z;exports.renderCard=h;exports.sponsor=kn;exports.textCardForBlip=A;
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {randomUUID}from'crypto';import*as m from'fs';import*as ie from'os';import*as S from'path';var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var le=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var N="1.4.
|
|
1
|
+
import {randomUUID}from'crypto';import*as m from'fs';import*as ie from'os';import*as S from'path';var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var le=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var N="1.4.1";var ce="https://api.opencrater.to";function K(e,n=process.env){let t=n.OPENCRATER_API_ORIGIN;return (e??(t&&t.trim()!==""?t:ce)).replace(/\/+$/,"")}function c(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let n=q("os"),t=q("fs"),o=q("path");t.appendFileSync(o.join(n.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(i=>String(i)).join(" ")}
|
|
2
2
|
`);}catch{}}catch{}}function R(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let n=w;if(typeof e!="object"||e===null)return {...n};let t=e;return {minIntervalSeconds:R(t.minIntervalSeconds)?t.minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:R(t.serveTimeoutMs)?t.serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:R(t.preloadPoolSize)?t.preloadPoolSize:n.preloadPoolSize,killSwitch:t.killSwitch===true,displayDurationSeconds:R(t.displayDurationSeconds)?t.displayDurationSeconds:n.displayDurationSeconds,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:n.minSdkVersion}}async function D(e,n,t,o,i){try{let r=await fetch(`${e}${n}`,{method:"POST",headers:{"content-type":"application/json",...i??{}},body:JSON.stringify(t),signal:AbortSignal.timeout(o)});return r.ok?await r.json():(c(`POST ${n} -> HTTP ${r.status}`),null)}catch(r){return c(`POST ${n} failed:`,r),null}}function J(e,n){let t=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:t,sdkVersion:N,installId:n.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:n.topics&&n.topics.length>0?n.topics:void 0,tags:n.tags&&n.tags.length>0?n.tags:void 0}}function fe(e){if(typeof e!="object"||e===null)return null;let n=e;if(typeof n.fill!="boolean")return null;let t={fill:n.fill,fallback:n.fallback??null,config:V(n.config),...Array.isArray(n.allowedPlacements)?{allowedPlacements:n.allowedPlacements.filter(o=>typeof o=="string")}:{}};return n.blip!==void 0&&n.blip!==null&&(t.blip=n.blip),typeof n.computeBalanceMicroUsd=="number"&&(t.computeBalanceMicroUsd=n.computeBalanceMicroUsd),typeof n.weeklyGrantMicroUsd=="number"&&(t.weeklyGrantMicroUsd=n.weeklyGrantMicroUsd),typeof n.pendingMicroUsd=="number"&&(t.pendingMicroUsd=n.pendingMicroUsd),t}async function F(e,n){let t=await D(n.origin,"/v1/serve",J(e,n),n.timeoutMs);return fe(t)}async function X(e,n,t){let o=await D(t.origin,"/v1/serve/batch",{...J(e,t),count:n},t.timeoutMs);if(typeof o!="object"||o===null)return null;let i=o;return Array.isArray(i.blips)?{blips:i.blips,fallback:i.fallback??null,config:V(i.config),...Array.isArray(i.allowedPlacements)?{allowedPlacements:i.allowedPlacements.filter(r=>typeof r=="string")}:{}}:null}function $(e,n){return D(n.origin,"/v1/events/impression",{impressionId:e},n.timeoutMs).then(()=>{}).catch(()=>{})}var ue=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},de=60,pe=24,me="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function ge(e){return e.replace(ue,"").length}function y(e,n){return n<=0?"":e.length<=n?e:n===1?"\u2026":e.slice(0,n-1).trimEnd()+"\u2026"}function he(e,n,t){let o=e.split(/\s+/).filter(l=>l.length>0),i=[],r="";for(let l of o){let u=r===""?l:`${r} ${l}`;if(u.length<=n)r=u;else if(r!==""&&i.push(r),r=l.length>n?y(l,n):l,i.length>=t)break}r!==""&&i.length<t&&i.push(r),i.length>t&&(i.length=t);let s=i.join(" "),a=i.length-1,f=i[a];return f!==void 0&&s.length<o.join(" ").length&&(i[a]=y(`${f}\u2026`,n)),i}function I(e=process.env,n=!!process.stdout.isTTY){if(!n)return false;if(e.FORCE_HYPERLINK!==void 0&&e.FORCE_HYPERLINK!=="0")return true;let t=e.TERM_PROGRAM??"";return !!(["iTerm.app","WezTerm","ghostty","Hyper","vscode","Tabby"].includes(t)||e.KITTY_WINDOW_ID||e.WT_SESSION||Number(e.VTE_VERSION??"0")>=5e3)}function P(e=process.env,n=!!process.stdout.isTTY){return !(e.NO_COLOR!==void 0&&e.NO_COLOR!==""||!n||(e.TERM??"")==="dumb")}function ye(e,n){return `\x1B]8;;${e}\x07${n}\x1B]8;;\x07`}function E(e){let n={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(n.cta=e.creative.cta),n}function Z(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function h(e,n={}){let t=n.width??process.stdout.columns??80,i=Math.max(pe,Math.min(t,de))-4,r=n.color??P(),s=n.hyperlinks??I(),a=(g,M)=>r?`${M}${g}${k.reset}`:g,f=e.label?y(e.label,i):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,i):"Sponsored Blips",l=[];l.push(a(f,k.dim)),e.title!==e.sponsorLabel&&l.push(a(y(e.title,i),k.bold));for(let g of he(e.body,i,2))l.push(g);let u="\u2192 ";if(s){let g=y(e.cta??e.url,i-u.length);l.push(u+a(ye(e.url,g),k.dim));}else e.cta&&l.push(y(e.cta,i)),l.push(u+a(y(e.url,i-u.length),k.dim));let T=`\u256D${"\u2500".repeat(i+2)}\u256E`,j=`\u2570${"\u2500".repeat(i+2)}\u256F`,L=l.map(g=>{let M=" ".repeat(Math.max(0,i-ge(g)));return `\u2502 ${g}${M} \u2502`}),b=[];return n.disclosure&&b.push(a(me,k.dim)),b.push(T,...L,j),b.join(`
|
|
3
3
|
`)+`
|
|
4
|
-
`}function Q(e){return e!==void 0&&e!==""}function
|
|
4
|
+
`}function Q(e){return e!==void 0&&e!==""}function U(e=process.env,n=!!process.stdout.isTTY){if(!n)return "none";let t=e.TERM??"";if(Q(e.TMUX)||t.startsWith("tmux")||t.startsWith("screen"))return "none";let o=e.TERM_PROGRAM??"";return o==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||o==="WezTerm"?"iterm2":t==="xterm-kitty"||Q(e.KITTY_WINDOW_ID)?"kitty":"none"}var v="\x1B",be="\x07",we=2e3,ke=2*1024*1024,Se=new Set(["image/png","image/jpeg","image/gif","image/webp"]),O=4096;async function ve(e,n=fetch,t={}){let o=t.timeoutMs??we,i=t.maxBytes??ke;try{let r=await n(e,{signal:AbortSignal.timeout(o)});if(!r.ok)return c(`media: HTTP ${r.status} for ${e}`),null;let s=(r.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!Se.has(s))return c(`media: disallowed content-type "${s}" for ${e}`),null;let a=Number(r.headers.get("content-length")??"0");if(Number.isFinite(a)&&a>i)return c(`media: content-length ${a} exceeds ${i} for ${e}`),null;let f=r.body;if(f&&typeof f.getReader=="function"){let u=f.getReader(),T=[],j=0;for(;;){let{done:L,value:b}=await u.read();if(L)break;if(b!==void 0){if(j+=b.byteLength,j>i)return await u.cancel().catch(()=>{}),c(`media: stream exceeded ${i} bytes for ${e}`),null;T.push(b);}}return Buffer.concat(T)}let l=Buffer.from(await r.arrayBuffer());return l.byteLength>i?(c(`media: body ${l.byteLength} bytes exceeds ${i} for ${e}`),null):l}catch(r){return c(`media: fetch failed for ${e}:`,r),null}}function xe(e){let n=e.toString("base64");return `${v}]1337;File=inline=1;size=${e.byteLength};width=auto:${n}${be}`}function Ce(e){let n=e.toString("base64");if(n.length<=O)return `${v}_Gf=100,a=T;${n}${v}\\`;let t=[];for(let o=0;o<n.length;o+=O){let i=n.slice(o,o+O),s=`m=${o+O>=n.length?0:1}`,a=o===0?`f=100,a=T,${s}`:s;t.push(`${v}_G${a};${i}${v}\\`);}return t.join("")}function A(e){let n=E(e),t=e.creative;switch(t.format){case "image":case "gif":return {...n,body:t.textFallback??n.body};case "video":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u25B6 Watch"};case "audio":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u{1F50A} Listen"};default:return n}}async function z(e,n={}){try{let t=e.creative;if(t.format!=="image"&&t.format!=="gif")return h(A(e),n);let o=n.protocol??U();if(o==="none"||t.mediaUrl===void 0||t.mediaUrl==="")return h(A(e),n);let i={};n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs),n.maxBytes!==void 0&&(i.maxBytes=n.maxBytes);let r=await ve(t.mediaUrl,n.fetchImpl??fetch,i);return r===null||r.byteLength===0?h(A(e),n):(o==="kitty"?Ce(r):xe(r))+`
|
|
5
5
|
`+h(E(e),n)}catch(t){return c("media: render failed, falling back to text:",t),h(E(e),n)}}function Te(e,n){return e.filter(t=>t.renderBy>n)}function ee(e,n,t=18e5){return e.filter(o=>o&&typeof o.impressionId=="string"&&typeof o.clickUrl=="string"&&o.creative&&typeof o.creative.title=="string").map(o=>({blip:o,renderBy:n+t}))}function ne(e,n){let t=Te(e.pool,n),o=t.shift();return {blip:o?o.blip:null,pool:t}}var te=360*60*1e3;function Ie(e=process.env){return S.join(ie.homedir(),".config","opencrater")}function oe(e=process.env){return S.join(Ie(e),"state.json")}function W(){return {installId:randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function d(e){return typeof e=="number"&&Number.isFinite(e)}var re=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function se(e){for(let n=0;;n++)try{return {text:m.readFileSync(e,"utf8")}}catch(t){let o=t.code??"";if(!(o==="ENOENT"||re.has(o)))return {locked:true};if(n>=4)return o==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(n+1));}catch{}}}function Pe(e){if(typeof e!="object"||e===null)return null;let n=e;return !d(n.minIntervalSeconds)||!d(n.serveTimeoutMs)||!d(n.preloadPoolSize)||typeof n.killSwitch!="boolean"?null:{minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:n.preloadPoolSize,killSwitch:n.killSwitch,displayDurationSeconds:d(n.displayDurationSeconds)?n.displayDurationSeconds:25,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:""}}function Ee(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t,i=o.blip;if(!d(o.renderBy)||typeof i!="object"||i===null||typeof i.impressionId!="string"||typeof i.clickUrl!="string"||typeof i.sponsorLabel!="string"||typeof i.creative!="object"||i.creative===null)continue;let r=i.creative;typeof r.title!="string"||typeof r.body!="string"||n.push({blip:{impressionId:i.impressionId,...typeof i.campaignId=="string"?{campaignId:i.campaignId}:{},clickUrl:i.clickUrl,sponsorLabel:i.sponsorLabel,creative:{format:"text",title:r.title,body:r.body,...typeof r.cta=="string"?{cta:r.cta}:{}}},renderBy:o.renderBy});}return n}function Oe(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let n={};for(let[t,o]of Object.entries(e)){if(!Array.isArray(o))continue;let i=o.filter(r=>typeof r=="string"&&r.length<=64);n[t]=i.slice(0,64);}return n}function Ae(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t;if(!(typeof o.topic!="string"||!d(o.at))&&(n.push({topic:o.topic.slice(0,32),at:o.at}),n.length>=24))break}return n}function We(e){if(!Array.isArray(e))return [];let n=[],t=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let i=o;if(typeof i.key!="string"||typeof i.package!="string"||i.key===""||i.package==="")continue;let r=`${i.package}\0${i.key}`;if(!t.has(r)&&(t.add(r),n.push({key:i.key,package:i.package}),n.length>=32))break}return n}function Be(e){if(typeof e!="object"||e===null)return null;let n=e,t={};if(typeof n.savedEnv=="object"&&n.savedEnv!==null)for(let[o,i]of Object.entries(n.savedEnv))(typeof i=="string"||i===null)&&(t[o]=i);return {active:n.active===true,savedEnv:t}}function _e(e){if(typeof e!="object"||e===null)return null;let n=e,t=o=>d(o)&&o>=0?o:0;return {turns:t(n.turns),lastLimitAt:t(n.lastLimitAt),lastDepletedAt:t(n.lastDepletedAt),lastBackupAt:t(n.lastBackupAt)}}function Le(e){let n=e.attrTagsAt,t=e.attrTagsCwd;return !d(n)||Date.now()-n>te||typeof t!="string"||t.length===0||t.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(i=>typeof i=="string"&&i.length<=40).slice(0,48):[],attrTagsCwd:t,attrTagsAt:n}}function Me(e){let n=W();if(typeof e!="object"||e===null)return n;let t=e;return {installId:typeof t.installId=="string"&&t.installId.length>0?t.installId:n.installId,lastShownAt:d(t.lastShownAt)&&t.lastShownAt>=0?t.lastShownAt:0,optOut:t.optOut===true,disclosureShown:t.disclosureShown===true,cachedConfig:Pe(t.cachedConfig),allowedPlacements:Oe(t.allowedPlacements),sessionTopics:Ae(t.sessionTopics),integrations:We(t.integrations),devToken:typeof t.devToken=="string"?t.devToken:null,computeRouting:Be(t.computeRouting),computeCards:_e(t.computeCards),configFetchedAt:d(t.configFetchedAt)&&t.configFetchedAt>=0?t.configFetchedAt:0,pool:Ee(t.pool),...Le(t)}}function x(e=process.env){let n=oe(e),t=se(n);if(t.text!==void 0)try{return Me(JSON.parse(t.text))}catch{let o=W();try{p(o,e);}catch{}return o}if(t.missing){let o=W();try{p(o,e);}catch{}return o}return W()}function p(e,n=process.env,t={}){let o=oe(n),i=S.dirname(o);m.mkdirSync(i,{recursive:true});let r=se(o),s=null;if(r.text!==void 0)try{s=JSON.parse(r.text);}catch{s=null;}if(s)typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt}),!t.allowClearToken&&typeof s.devToken=="string"&&e.devToken==null&&(e={...e,devToken:s.devToken}),typeof s.installId=="string"&&s.installId.length>0&&s.installId!==e.installId&&(e={...e,installId:s.installId});else if(!t.allowClearToken&&e.devToken==null&&r.text===void 0&&!r.missing)return;let a=S.join(i,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);m.writeFileSync(a,JSON.stringify(e,null,2)+`
|
|
6
|
-
`,"utf8");for(let f=0;;f++)try{m.renameSync(a,o);return}catch(l){let u=l.code??"";if(f>=4||!re.has(u)){try{m.rmSync(a,{force:!0});}catch{}if(f>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(f+1));}catch{}}}var qe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Y(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return Y(e.OPENCRATER_DISABLE)||Y(e.TSN_DISABLE)}function De(e){return qe.some(n=>Y(e[n]))}function H(e){return e?{...w,...e}:w}function C(e,n={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let t=H(e.state.cachedConfig);if(t.killSwitch)return "kill_switch";if(De(e.env))return "ci";if(!n.skipTTY&&!e.isTTY)return "not_tty";if(!n.skipFrequency){let o=t.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<o)return "frequency"}return null}async function B(e){try{return await e()}catch(n){return c("suppressed error:",n),null}}function _(e,n){let t=H(n.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:t.serveTimeoutMs,installId:n.installId,config:t}}function Fe(e,n){let t=!n.disclosureShown,o=h(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:t});return process.stdout.write(o),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function ae(e,n){let t=await
|
|
6
|
+
`,"utf8");for(let f=0;;f++)try{m.renameSync(a,o);return}catch(l){let u=l.code??"";if(f>=4||!re.has(u)){try{m.rmSync(a,{force:!0});}catch{}if(f>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(f+1));}catch{}}}var qe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Y(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return Y(e.OPENCRATER_DISABLE)||Y(e.TSN_DISABLE)}function De(e){return qe.some(n=>Y(e[n]))}function H(e){return e?{...w,...e}:w}function C(e,n={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let t=H(e.state.cachedConfig);if(t.killSwitch)return "kill_switch";if(De(e.env))return "ci";if(!n.skipTTY&&!e.isTTY)return "not_tty";if(!n.skipFrequency){let o=t.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<o)return "frequency"}return null}async function B(e){try{return await e()}catch(n){return c("suppressed error:",n),null}}function _(e,n){let t=H(n.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:t.serveTimeoutMs,installId:n.installId,config:t}}function Fe(e,n){let t=!n.disclosureShown,o=h(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:t});return process.stdout.write(o),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function ae(e,n){let t=await z(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:!n.disclosureShown});return process.stdout.write(t),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function $e(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipFrequency:true});if(t!==null)return c("fetch suppressed:",t),null;let o=_(e,n),i=await F(e,o);return i?(p({...n,cachedConfig:i.config,configFetchedAt:Date.now()}),i.fill&&i.blip?i.blip:null):null}async function Ue(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()});if(t!==null)return c("suppressed:",t),false;let o=_(e,n),i=await F(e,o);return i?(n={...n,cachedConfig:i.config,configFetchedAt:Date.now()},i.fill&&i.blip?(n=await ae(i.blip,n),p(n),$(i.blip.impressionId,o),true):i.fallback?(n=Fe(Z(i.fallback),n),p(n),true):(p(n),false)):false}async function ze(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipTTY:true,skipFrequency:true});if(t!==null)return c("preload suppressed:",t),0;let o=_(e,n),i=Math.max(1,o.config.preloadPoolSize),r=await X(e,i,o);if(!r)return 0;let s=Date.now(),a=ee(r.blips,s);return p({...n,pool:a,cachedConfig:r.config,configFetchedAt:s}),a.length}async function Ge(e){let n=x(),t=Date.now(),o=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:t});if(o!==null)return c("renderFromPool suppressed:",o),false;let{blip:i,pool:r}=ne(n,t);if(!i)return p({...n,pool:r}),false;let s=await ae(i,{...n,pool:r});p(s);let a=_(e,n);return $(i.impressionId,a),true}var kn={show(e){return B(()=>Ue(e)).then(n=>n??false)},fetch(e){return B(()=>$e(e))},preload(e){return B(()=>ze(e)).then(n=>n??0)},renderFromPool(e){return B(()=>Ge(e)).then(n=>n??false)}};export{w as DEFAULT_CONFIG,le as HOOK_CATALOG,N as SDK_VERSION,U as detectImageProtocol,z as renderBlip,h as renderCard,kn as sponsor,A as textCardForBlip};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencrater",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.1",
|
|
4
4
|
"description": "OpenCrater — sponsor cards for AI coding terminals (Claude Code, Codex, Gemini CLI, Copilot CLI). One command, auto-wires every host, opt out anytime.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"opencrater",
|