@zortexhq/indra-v2.5 0.2.6 → 0.2.8
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/README.md +6 -4
- package/dist/auto-sync.js +1 -1
- package/dist/connector-worker.js +1 -1
- package/dist/content-find.js +8 -2
- package/dist/gateway.js +1 -1
- package/dist/local-cloud-policy.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mcp.js +1 -1
- package/dist/public-tool.js +1 -1
- package/dist/resident-ensure-ready.js +1 -1
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +1 -1
- package/dist/source-data.js +1 -0
- package/dist/supervised-sync.js +1 -1
- package/dist/worker-google-auth.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-calendar/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-framework/dist/manifest.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-framework/dist/runtime.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/brokered.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/gmail-source.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-history/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
- package/node_modules/@zortexhq/plugin-device-auth/dist/authority.js +1 -1
- package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/source-sync.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/current-records.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/record-rules.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +8 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +1 -1
- package/node_modules/@zortexhq/rooktrail/dist/record-rules.js +1 -1
- package/node_modules/@zortexhq/rooktrail/dist/registry.js +1 -1
- package/package.json +6 -6
- package/release-provenance.json +21 -21
- package/update-manifest.json +125 -95
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{HELP_MANUAL_SOURCES}from"./help-manual-sources.js";import{createPreparedDiscordSource}from"@zortexhq/plugin-connector-level1";import{validateJoplinSelection}from"./joplin-selection.js";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{execFile,spawn}from"node:child_process";import{chmod,lstat,mkdir,readFile,realpath,rename,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{dirname,isAbsolute,join,resolve}from"node:path";import{createConnection,createServer}from"node:net";import{promisify}from"node:util";import{DatabaseSync}from"node:sqlite";import{residentRuntimeIdentity}from"./resident-runtime-identity.js";import{preserveResidentStartupOrigin}from"./installation-origin.js";import{currentOperationalExecution,isOperationalContext,withOperationalContext,withoutOperationalContext}from"@zortexhq/plugin-telemetry/api";import{observeResidentHandlers,traceResidentControl}from"./resident-telemetry.js";const execute=promisify(execFile);const delay=ms=>new Promise(done=>setTimeout(done,ms));export const RESIDENT_IPC_PROTOCOL_VERSION=4;const REQUEST_BYTES=2*1024*1024,RESPONSE_BYTES=4*1024*1024;const RESIDENT_MANAGEMENT=new Set(["plugins","plugin.set-enabled","status","sources","onboarding","startup"]);export function isResidentGatewayRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value,args=request2.args;if(Object.keys(request2).some(key=>key!=="operation"&&key!=="args")||!args||typeof args!=="object"||Array.isArray(args))return false;return request2.operation==="actions"||request2.operation==="manage"&&RESIDENT_MANAGEMENT.has(String(args.what))}function isLocalCloudControlRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value;return request2.action==="grants"&&Object.keys(request2).length===1||request2.action==="revoke"&&Object.keys(request2).length===2&&typeof request2.id==="string"&&/^[a-zA-Z0-9_-]{1,200}$/.test(request2.id)}async function unixEndpoint(hash){const name=`zortex-indra-${hash}.sock`,preferred=join(tmpdir(),name);if(Buffer.byteLength(preferred)<=103)return preferred;const unavailable=()=>Object.assign(new Error("Resident socket path is too long and no safe short system temporary directory is available"),{code:"RESIDENT_SOCKET_PATH_UNAVAILABLE"});try{const directory=await realpath("/tmp"),info=await lstat(directory),endpoint=join(directory,name);if(!info.isDirectory()||info.uid!==0||(info.mode&18)!==0&&(info.mode&512)===0||Buffer.byteLength(endpoint)>103)throw unavailable();return endpoint}catch{throw unavailable()}}async function identity(root){if(!isAbsolute(root))throw new Error("Resident Vault path must be absolute");const canonical=await realpath(root);const key=process.platform==="win32"?canonical.toLowerCase():canonical;const hash=createHash("sha256").update(key).digest("hex").slice(0,24);const directory=join(canonical,"host");return{root:canonical,directory,file:join(directory,"resident.json"),hash,endpoint:process.platform==="win32"?`\\\\.\\pipe\\zortex-indra-${hash}`:await unixEndpoint(hash)}}async function metadata(id){try{const item=JSON.parse(await readFile(id.file,"utf8"));if(item.endpoint!==id.endpoint||!Number.isSafeInteger(item.pid)||item.pid<1||typeof item.nonce!=="string"||!/^[a-f0-9]{64}$/.test(item.nonce)||typeof item.startedAt!=="string")return null;return item}catch{return null}}class ResidentStatusUnavailable extends Error{disconnected;constructor(disconnected){super("Resident status is unavailable; inspect the running host before retrying");this.disconnected=disconnected}}async function request(id,command,timeout=2e3){let item=await metadata(id);if(!item)return null;const deadline=Date.now()+Math.min(timeout,1e3);for(;;){try{return await requestOnce(id,item,command,timeout)}catch(error){if(!(error instanceof ResidentStatusUnavailable)||!error.disconnected||Date.now()>=deadline)throw error;await delay(20);item=await metadata(id)??item}}}function requestOnce(id,item,command,timeout){const operationalContext=currentOperationalExecution();return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="";let settled=false;let connected=false;const finish=(result,error,disconnected=false)=>{if(settled)return;if(result===null&&!error&&connected&&command==="status"){error=new ResidentStatusUnavailable(disconnected)}settled=true;socket.destroy();if(error)reject(error);else done(result)};const incompatible=()=>finish(null,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));socket.setTimeout(timeout,()=>finish(null));socket.on("error",error=>finish(null,!connected&&error.code!=="ENOENT"&&error.code!=="ECONNREFUSED"?error:void 0,true));socket.on("end",()=>finish(null,void 0,true));socket.on("connect",()=>{connected=true;if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();socket.write(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,command,nonce:item.nonce,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n")});socket.on("data",chunk=>{text+=chunk.toString();if(text.length>65536)return finish(null);if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();finish(typeof value.running==="boolean"?value:null)}catch{finish(null)}})})}export async function residentStatus(root){return await request(await identity(root),"status")??{running:false}}async function residentRpc(root,message,signal){const operationalContext=currentOperationalExecution();const id=await identity(root),item=await metadata(id);if(!item)throw new Error("Resident is not running");return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="",settled=false;const finish=(value,error)=>{if(settled)return;settled=true;signal?.removeEventListener("abort",abort);socket.destroy();if(error)reject(error);else done(value)};const abort=()=>finish(void 0,new Error("Resident request was cancelled"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)return abort();socket.setTimeout(11*6e4,()=>finish(void 0,new Error("Resident request timed out")));socket.on("error",error=>finish(void 0,error));socket.on("end",()=>finish(void 0,new Error("Resident sync ended without a result")));socket.on("connect",()=>{if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return finish(void 0,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));const payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,nonce:item.nonce,...message,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n";if(Buffer.byteLength(payload)>REQUEST_BYTES)return finish(void 0,new Error("Resident request was too large"));socket.write(payload)});socket.on("data",chunk=>{text+=chunk.toString();if(Buffer.byteLength(text)>RESPONSE_BYTES)return finish(void 0,new Error("Resident response was too large"));if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||!value.result)return finish(void 0,new Error("Resident response was invalid"));finish(value.result)}catch{finish(void 0,new Error("Resident response was invalid"))}})})}export function residentLocalCloudControl(root,request2){if(!isLocalCloudControlRequest(request2))return Promise.reject(new Error("Invalid Local Cloud control request"));return residentRpc(root,{command:"local-cloud-control",request:request2})}export function residentSync(root,source,requestId,options={}){return residentRpc(root,{command:"sync",source,requestId,...options.bindingId?{bindingId:options.bindingId}:{}},options.signal)}export function residentGatewayCall(root,request2,signal){return residentRpc(root,{command:"gateway",request:request2},signal)}export function residentEnsureReady(root,source,signal){return residentRpc(root,{command:"ensure-ready",source},signal)}export function residentCheck(root,source,signal){return residentRpc(root,{command:"check",source},signal)}export function residentRead(root,source,request2={},signal){return residentRpc(root,{command:"read",source,request:request2},signal)}export function residentInvoke(root,request2,signal){return residentRpc(root,{command:"invoke",request:request2},signal)}export function residentConnect(root,source,requestId,signal,settings={automatic:false}){return residentRpc(root,{command:"connect",source,requestId,automatic:settings.automatic,...settings.manualPresentation?{manualPresentation:settings.manualPresentation}:{}},signal)}export function residentConnectJob(root,requestId,signal){return residentRpc(root,{command:"connect-job",requestId},signal)}export function residentPauseConnectionAutomation(root,signal){return residentRpc(root,{command:"pause-connection-automation"},signal)}export function residentResumeBackgroundSync(root,signal){return residentRpc(root,{command:"resume-background-sync"},signal)}export function residentConnectManual(root,source,requestId,signal){return residentRpc(root,{command:"connect-manual",source,requestId},signal)}export function residentReconnectSaved(root,source,signal){return residentRpc(root,{command:"reconnect-saved",source},signal)}export function residentConnectGmailWrite(root,requestId,signal){return residentRpc(root,{command:"connect-gmail-write",requestId},signal)}export function residentConnectReadwiseMcpWrite(root,requestId,signal){return residentRpc(root,{command:"connect-readwise-mcp-write",requestId},signal)}export function residentConnectReauthorize(root,source,requestId,signal){return residentRpc(root,{command:"connect-reauthorize",source,requestId},signal)}export function residentConnectRecovery(root,source,requestId,signal){return residentRpc(root,{command:"connect-recovery",source,requestId},signal)}export function residentConnectAutomatic(root,source,requestId,signal){return residentRpc(root,{command:"connect-automatic",source,requestId},signal)}export function residentConfigureWeChat(root,port,signal){return residentRpc(root,{command:"configure-wechat",port},signal)}export async function residentConfigureJoplin(root,selection,signal){validateJoplinSelection(selection);return residentRpc(root,{command:"configure-joplin",selection},signal)}export function residentConfigureThunderbird(root,port,signal){return residentRpc(root,{command:"configure-thunderbird",port},signal)}export function residentConfigureDiscord(root,selection,signal){return residentRpc(root,{command:"configure-discord",selection},signal)}export function residentConfigureProtonMail(root,port,signal){return residentRpc(root,{command:"configure-proton-mail",port},signal)}export function residentConfigureZulip(root,selection,signal){return residentRpc(root,{command:"configure-zulip",selection},signal)}export function residentConfigureFreshRSS(root,selection,signal){return residentRpc(root,{command:"configure-freshrss",selection},signal)}export function residentConfigureMiniflux(root,selection,signal){return residentRpc(root,{command:"configure-miniflux",selection},signal)}export function residentConfigureMattermost(root,selection,signal){return residentRpc(root,{command:"configure-mattermost",selection},signal)}export function residentConfigureWallabag(root,selection,signal){return residentRpc(root,{command:"configure-wallabag",selection},signal)}export function residentConfigureCalcom(root,selection,signal){return residentRpc(root,{command:"configure-calcom",selection},signal)}export function residentConfigureWakatime(root,selection,signal){return residentRpc(root,{command:"configure-wakatime",selection},signal)}export function residentConfigureNextcloud(root,instanceUrl,signal){return residentRpc(root,{command:"configure-nextcloud",instanceUrl},signal)}export function residentConfigureDropbox(root,selection,signal){return residentRpc(root,{command:"configure-dropbox",selection},signal)}export function residentConfigureBox(root,selection,signal){return residentRpc(root,{command:"configure-box",selection},signal)}export function residentConfigureFront(root,selection,signal){return residentRpc(root,{command:"configure-front",selection},signal)}export function residentConfigureHubSpot(root,selection,signal){return residentRpc(root,{command:"configure-hubspot",selection},signal)}export function residentConfigureGoogleContacts(root,selection,signal){return residentRpc(root,{command:"configure-google-contacts",selection},signal)}export function residentConfigureGoogleChat(root,selection,signal){return residentRpc(root,{command:"configure-google-chat",selection},signal)}export function residentConfigureSalesforce(root,selection,signal){return residentRpc(root,{command:"configure-salesforce",selection},signal)}export function residentConfigureZendesk(root,selection,signal){return residentRpc(root,{command:"configure-zendesk",selection},signal)}export function residentConfigureZoom(root,selection,signal){return residentRpc(root,{command:"configure-zoom",selection},signal)}export function residentConfigureSmartsheet(root,region,signal){return residentRpc(root,{command:"configure-smartsheet",region},signal)}export function residentConfigureFigma(root,mode,signal){return residentRpc(root,{command:"configure-figma",mode},signal)}export function residentConfigureFreshdesk(root,subdomain,signal){return residentRpc(root,{command:"configure-freshdesk",subdomain},signal)}export function residentConfigureCopyQ(root,executable,session,signal){return residentRpc(root,{command:"configure-copyq",executable,session},signal)}export function residentConfigureOwnTracks(root,port,signal){return residentRpc(root,{command:"configure-owntracks",port},signal)}export function residentConfigureZotero(root,libraryId,libraryType,signal){return residentRpc(root,{command:"configure-zotero",libraryId,libraryType},signal)}export function residentConfigureNativeFiles(root,source,roots,signal){return residentRpc(root,{command:"configure-native-files",source,roots},signal)}export function residentConnectorStatus(root,signal){return residentRpc(root,{command:"connector-status"},signal)}export function residentConnectorCheck(root,source,signal){return residentRpc(root,{command:"connector-check",source},signal)}export function residentConnectorRead(root,source,signal){return residentRpc(root,{command:"connector-read",source},signal)}export function residentCancelConnect(root,requestId,generation,challengeRef){if(!Number.isSafeInteger(generation)||generation<0||!challengeRef)return Promise.resolve({err:{code:"stale_job_generation"}});return residentRpc(root,{command:"connect-cancel",requestId,generation,challengeRef})}function listen(server,endpoint){return new Promise((done,reject)=>{const fail=error=>{server.off("listening",ready);reject(error)};const ready=()=>{server.off("error",fail);done()};server.once("error",fail);server.once("listening",ready);server.listen(endpoint)})}function unixOwnership(id){const lock=new DatabaseSync(join(id.directory,"resident-owner.sqlite"),{allowExtension:false,timeout:0});try{lock.exec("BEGIN EXCLUSIVE");return lock}catch(error){lock.close();if(error.errcode===5)return null;throw error}}async function recoverUnixEndpoint(endpoint){let before;try{before=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!before.isSocket())return false;const refused=await new Promise(done=>{const socket=createConnection(endpoint);let settled=false;const finish=value=>{if(!settled){settled=true;socket.destroy();done(value)}};socket.once("connect",()=>finish(false));socket.once("error",error=>finish(error.code==="ECONNREFUSED"));socket.setTimeout(2e3,()=>finish(false))});if(!refused)return false;let after;try{after=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!after.isSocket()||after.dev!==before.dev||after.ino!==before.ino)return false;await unlink(endpoint);return true}export async function runResidentServer(root,onStop,status=()=>({}),handlers={}){handlers=observeResidentHandlers(handlers);const id=await identity(root);await mkdir(id.directory,{recursive:true,mode:448});const ownership=process.platform==="win32"?void 0:unixOwnership(id);if(ownership===null)return null;const item={protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,operationalContextVersion:1,pid:process.pid,nonce:randomBytes(32).toString("hex"),endpoint:id.endpoint,startedAt:new Date().toISOString()};const runtime=await residentRuntimeIdentity();const sockets=new Set;let stopping;let closing;const server=createServer(socket=>{socket.setEncoding("utf8");const reply=result=>{if(socket.destroyed)return;let payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n";if(Buffer.byteLength(payload)>RESPONSE_BYTES)payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result:{err:{code:"resource_exhausted",message:"The source result exceeds the resident response limit."}}})+"\n";socket.end(payload)};const disconnected=new AbortController;sockets.add(socket);socket.on("close",()=>{sockets.delete(socket);disconnected.abort()});socket.on("error",()=>{});socket.setTimeout(2e3,()=>socket.destroy());let input="";let handled=false;socket.on("data",chunk=>{if(handled)return;input+=chunk.toString();if(Buffer.byteLength(input)>REQUEST_BYTES){handled=true;socket.destroy();return}if(!input.includes("\n"))return;handled=true;void(async()=>{try{const envelope=JSON.parse(input.split("\n")[0]);if(envelope.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||typeof envelope.nonce!=="string"||envelope.nonce.length!==item.nonce.length||!timingSafeEqual(Buffer.from(envelope.nonce),Buffer.from(item.nonce))){socket.destroy();return}const{operationalContext,...message}=envelope;if(operationalContext!==void 0&&!isOperationalContext(operationalContext)){socket.destroy();return}async function configureSelection(valid,configure){if(!configure||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!valid(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await configure(message.selection))}const dispatch=async()=>{if((stopping||closing)&&message.command!=="status"&&message.command!=="stop"){reply({err:{code:"unavailable",message:"The background host is stopping."}});return}if(message.command==="status"){const{nonce:_nonce,endpoint:_endpoint,...safe}=traceResidentControl(handlers.telemetry,{phase:"runtime",action:"status",operationId:"resident.status"},status,{plainResult:true});socket.end(JSON.stringify({...safe,runtime,protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,pid:item.pid,startedAt:item.startedAt})+"\n")}else if(message.command==="sync"){if(!handlers.sync||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||message.bindingId!==void 0&&(typeof message.bindingId!=="string"||!message.bindingId||message.bindingId.length>200)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.sync(message.source,message.requestId,{signal:disconnected.signal,...message.bindingId?{bindingId:message.bindingId}:{}});reply(result)}else if(message.command==="local-cloud-control"){if(!isLocalCloudControlRequest(message.request)){socket.destroy();return}if(!handlers.localCloud){reply({err:{code:"unavailable",message:"This resident does not provide Local Cloud authorization controls."}});return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.localCloud(message.request))}else if(message.command==="gateway"){if(!handlers.gateway||!isResidentGatewayRequest(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.gateway(message.request,disconnected.signal))}else if(message.command==="ensure-ready"){if(!handlers.ensureReady||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());reply(await handlers.ensureReady(message.source,disconnected.signal))}else if(message.command==="check"){if(!handlers.check||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.check(message.source,disconnected.signal))}else if(message.command==="read"){if(!handlers.read||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||!message.request||typeof message.request!=="object"||Array.isArray(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.read(message.source,message.request,disconnected.signal);reply(result)}else if(message.command==="invoke"){const request2=message.request;if(!handlers.invoke||!request2||typeof request2!=="object"||Array.isArray(request2)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.invoke(request2,disconnected.signal);reply(result)}else if(message.command==="connect"){if(!handlers.connect||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||typeof message.automatic!=="boolean"){socket.destroy();return}const manualPresentation=message.manualPresentation==="return-url"?"return-url":message.manualPresentation==="open"?"open":void 0;socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connect(message.source,message.requestId,disconnected.signal,{automatic:message.automatic,...manualPresentation?{manualPresentation}:{}});reply(result)}else if(message.command==="connect-manual"){if(!handlers.connectManual||typeof message.source!=="string"||!HELP_MANUAL_SOURCES.has(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectManual(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="reconnect-saved"){if(!handlers.reconnectSaved||typeof message.source!=="string"||!supportsSavedReconnect(message.source)||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source"].includes(key))){socket.destroy();return}socket.setTimeout(9e4,()=>socket.destroy());const result=await handlers.reconnectSaved(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-gmail-write"){if(!handlers.connectGmailWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectGmailWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-readwise-mcp-write"){if(!handlers.connectReadwiseMcpWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReadwiseMcpWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-reauthorize"){if(!handlers.connectReauthorize||typeof message.source!=="string"||!["todoist","linear"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReauthorize(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-recovery"){if(!handlers.connectRecovery||typeof message.source!=="string"||!["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectRecovery(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-automatic"){if(!handlers.connectAutomatic||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectAutomatic(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-job"){if(!handlers.connectJob||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}const result=await handlers.connectJob(message.requestId);reply(result)}else if(message.command==="connect-cancel"){if(!handlers.cancelConnect||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||!Number.isSafeInteger(message.generation)||message.generation<0||typeof message.challengeRef!=="string"||!message.challengeRef||message.challengeRef.length>200){socket.destroy();return}const result=await handlers.cancelConnect(message.requestId,message.generation,message.challengeRef);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-wechat"){if(!handlers.configureWeChat||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureWeChat({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-joplin"){if(!handlers.configureJoplin||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{validateJoplinSelection(message.selection)}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureJoplin(message.selection,disconnected.signal);reply(result)}else if(message.command==="configure-thunderbird"){if(!handlers.configureThunderbird||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureThunderbird({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-discord"){if(!handlers.configureDiscord||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{const selection=message.selection;if(!selection||typeof selection!=="object"||Array.isArray(selection)||Reflect.ownKeys(selection).some(key=>typeof key!=="string"||!["clientId","expectedSubject","ipcPath","channelIds"].includes(key)))throw Error("invalid");createPreparedDiscordSource("discord",{mode:"fields",...selection})}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDiscord(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-proton-mail"){if(!handlers.configureProtonMail||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureProtonMail({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zulip"){await configureSelection(validZulipSelection,handlers.configureZulip?.bind(handlers))}else if(message.command==="configure-freshrss"){await configureSelection(validFreshRSSSelection,handlers.configureFreshRSS?.bind(handlers))}else if(message.command==="configure-miniflux"){await configureSelection(validMinifluxSelection,handlers.configureMiniflux?.bind(handlers))}else if(message.command==="configure-mattermost"){await configureSelection(validMattermostSelection,handlers.configureMattermost?.bind(handlers))}else if(message.command==="configure-wallabag"){await configureSelection(validWallabagSelection,handlers.configureWallabag?.bind(handlers))}else if(message.command==="configure-calcom"){await configureSelection(validCalcomSelection,handlers.configureCalcom?.bind(handlers))}else if(message.command==="configure-wakatime"){await configureSelection(validWakatimeSelection,handlers.configureWakatime?.bind(handlers))}else if(message.command==="configure-nextcloud"){if(!handlers.configureNextcloud||Object.keys(message).some(key=>!["protocolVersion","nonce","command","instanceUrl"].includes(key))||!validNextcloudInstanceUrl(message.instanceUrl)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNextcloud({instanceUrl:message.instanceUrl});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-dropbox"){const selection=message.selection;if(!handlers.configureDropbox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDropbox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-box"){const selection=message.selection;if(!handlers.configureBox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureBox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-front"){const selection=message.selection;if(!handlers.configureFront||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFront({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-hubspot"){const selection=message.selection;if(!handlers.configureHubSpot||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureHubSpot({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-contacts"){const selection=message.selection;if(!handlers.configureGoogleContacts||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleContacts({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-chat"){const selection=message.selection;if(!handlers.configureGoogleChat||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleChat({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-salesforce"){const selection=message.selection;if(!handlers.configureSalesforce||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==3||Object.keys(selection).some(key=>!["environment","clientId","loopbackPort"].includes(key))||!["production","sandbox"].includes(selection.environment)||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSalesforce({environment:selection.environment,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zendesk"){const selection=message.selection;if(!handlers.configureZendesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validZendeskSelection(selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZendesk({subdomain:selection.subdomain,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zoom"){const selection=message.selection;if(!handlers.configureZoom||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==1||Object.keys(selection).some(key=>key!=="clientId")||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZoom({clientId:selection.clientId});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-smartsheet"){if(!handlers.configureSmartsheet||Object.keys(message).some(key=>!["protocolVersion","nonce","command","region"].includes(key))||!["us","eu","au"].includes(message.region)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSmartsheet({region:message.region});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-figma"){if(!handlers.configureFigma||Object.keys(message).some(key=>!["protocolVersion","nonce","command","mode"].includes(key))||!["fields","oauth"].includes(message.mode)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFigma(message.mode);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-freshdesk"){if(!handlers.configureFreshdesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","subdomain"].includes(key))||typeof message.subdomain!=="string"||message.subdomain.length>63||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(message.subdomain)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFreshdesk({subdomain:message.subdomain});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-copyq"){if(!handlers.configureCopyQ||typeof message.executable!=="string"||message.executable.length<1||message.executable.length>512||typeof message.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(message.session)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureCopyQ({executable:message.executable,session:message.session});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-owntracks"){if(!handlers.configureOwnTracks||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureOwnTracks({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zotero"){if(!handlers.configureZotero||typeof message.libraryId!=="string"||!["user","group"].includes(message.libraryType)||!/^[1-9][0-9]{0,19}$/.test(message.libraryId)&&!(message.libraryType==="user"&&message.libraryId==="0")){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZotero({libraryId:message.libraryId,libraryType:message.libraryType});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-native-files"){const sources=["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"];if(!handlers.configureNativeFiles||!sources.includes(message.source)||!Array.isArray(message.roots)||message.roots.length<1||message.roots.length>16||!message.roots.every(root2=>typeof root2==="string"&&root2.length>0&&root2.length<=4096)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNativeFiles({source:message.source,roots:message.roots});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-status"){if(!handlers.connectorStatus){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorStatus();if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-check"){if(!handlers.connectorCheck||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorCheck(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-read"){if(!handlers.connectorRead||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorRead(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="pause-connection-automation"){if(!handlers.pauseAutomation||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.pauseAutomation())}else if(message.command==="resume-background-sync"){if(!handlers.resumeBackgroundSync||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.resumeBackgroundSync())}else if(message.command==="stop"){socket.setTimeout(3e4,()=>socket.destroy());stopping??=Promise.resolve().then(()=>traceResidentControl(handlers.telemetry,{phase:"runtime",action:"cleanup",operationId:"resident.stop"},onStop,{plainResult:true}));try{await stopping}catch{stopping=void 0;socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,error:"resident_cleanup_failed"})+"\n");return}socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:false,stopped:true})+"\n");void close()}else socket.destroy()};if(operationalContext)await withOperationalContext(operationalContext,dispatch);else await withoutOperationalContext(dispatch)}catch{socket.destroy()}})()})});const close=()=>closing??=(async()=>{try{const closed=new Promise(done=>server.close(()=>done()));for(const socket of sockets)socket.end();await closed;if((await metadata(id))?.nonce===item.nonce)await unlink(id.file).catch(()=>{})}finally{ownership?.close()}})();try{try{await listen(server,id.endpoint)}catch(error){if(error.code!=="EADDRINUSE")throw error;if(process.platform==="win32"||!await recoverUnixEndpoint(id.endpoint)){await close();return null}try{await listen(server,id.endpoint)}catch(retryError){if(retryError.code!=="EADDRINUSE")throw retryError;await close();return null}}if(process.platform!=="win32")await chmod(id.endpoint,384);const temporary=`${id.file}.${item.nonce}.tmp`;try{await writeFile(temporary,JSON.stringify(item),{mode:384,flag:"wx"});await rename(temporary,id.file)}finally{await unlink(temporary).catch(()=>{})}}catch(error){await close();throw error}return{close}}function windowsQuote(value){return'"'+value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")+'"'}const xml=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");export function residentStartupPlan(root,entrypoint,hash,platform=process.platform,executable=process.execPath,home=homedir(),environment=process.env){if(![root,entrypoint,executable].every(isAbsolute))throw new Error("Resident startup paths must be absolute");if(![root,entrypoint,executable].every(value=>!/[\r\n\0]/.test(value)))throw new Error("Invalid resident startup path");if(!/^[a-f0-9]{24}$/.test(hash))throw new Error("Invalid resident identity");const syncDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_SYNC??"").trim());const args=[entrypoint,"--root",root,"host","run",...syncDisabled?["--sync-disabled"]:[]];const command=[executable,...args].map(windowsQuote).join(" ");const launcherPath=join(root,"host","resident-startup.vbs");const launcher=`Option Explicit\r
|
|
1
|
+
import{supportsSavedReconnect}from"./saved-reconnect.js";import{validZendeskSelection}from"./zendesk-selection.js";import{HELP_MANUAL_SOURCES}from"./help-manual-sources.js";import{createPreparedDiscordSource}from"@zortexhq/plugin-connector-level1";import{validateJoplinSelection}from"./joplin-selection.js";import{validZulipSelection}from"./zulip-selection.js";import{validFreshRSSSelection}from"./freshrss-selection.js";import{validMinifluxSelection}from"./miniflux-selection.js";import{validMattermostSelection}from"./mattermost-selection.js";import{validWallabagSelection}from"./wallabag-selection.js";import{validCalcomSelection}from"./calcom-selection.js";import{validWakatimeSelection}from"./wakatime-selection.js";import{validNextcloudInstanceUrl}from"./nextcloud-url.js";import{createHash,randomBytes,timingSafeEqual}from"node:crypto";import{execFile,spawn}from"node:child_process";import{chmod,lstat,mkdir,readFile,realpath,rename,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{dirname,isAbsolute,join,resolve}from"node:path";import{createConnection,createServer}from"node:net";import{promisify}from"node:util";import{DatabaseSync}from"node:sqlite";import{residentRuntimeIdentity}from"./resident-runtime-identity.js";import{preserveResidentStartupOrigin}from"./installation-origin.js";import{currentOperationalExecution,isOperationalContext,withOperationalContext,withoutOperationalContext}from"@zortexhq/plugin-telemetry/api";import{observeResidentHandlers,traceResidentControl}from"./resident-telemetry.js";const execute=promisify(execFile);const delay=ms=>new Promise(done=>setTimeout(done,ms));export const RESIDENT_IPC_PROTOCOL_VERSION=4;const REQUEST_BYTES=2*1024*1024,RESPONSE_BYTES=4*1024*1024;const RESIDENT_MANAGEMENT=new Set(["plugins","plugin.set-enabled","status","sources","onboarding","startup"]);export function isResidentGatewayRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value,args=request2.args;if(Object.keys(request2).some(key=>key!=="operation"&&key!=="args")||!args||typeof args!=="object"||Array.isArray(args))return false;const fields=args;return request2.operation==="action"&&fields.name==="connector.find"&&Object.keys(fields).every(key=>key==="name"||key==="params")&&!!fields.params&&typeof fields.params==="object"&&!Array.isArray(fields.params)||request2.operation==="actions"||request2.operation==="manage"&&RESIDENT_MANAGEMENT.has(String(fields.what))}function isLocalCloudControlRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))return false;const request2=value;return request2.action==="grants"&&Object.keys(request2).length===1||request2.action==="revoke"&&Object.keys(request2).length===2&&typeof request2.id==="string"&&/^[a-zA-Z0-9_-]{1,200}$/.test(request2.id)}async function unixEndpoint(hash){const name=`zortex-indra-${hash}.sock`,preferred=join(tmpdir(),name);if(Buffer.byteLength(preferred)<=103)return preferred;const unavailable=()=>Object.assign(new Error("Resident socket path is too long and no safe short system temporary directory is available"),{code:"RESIDENT_SOCKET_PATH_UNAVAILABLE"});try{const directory=await realpath("/tmp"),info=await lstat(directory),endpoint=join(directory,name);if(!info.isDirectory()||info.uid!==0||(info.mode&18)!==0&&(info.mode&512)===0||Buffer.byteLength(endpoint)>103)throw unavailable();return endpoint}catch{throw unavailable()}}async function identity(root){if(!isAbsolute(root))throw new Error("Resident Vault path must be absolute");const canonical=await realpath(root);const key=process.platform==="win32"?canonical.toLowerCase():canonical;const hash=createHash("sha256").update(key).digest("hex").slice(0,24);const directory=join(canonical,"host");return{root:canonical,directory,file:join(directory,"resident.json"),hash,endpoint:process.platform==="win32"?`\\\\.\\pipe\\zortex-indra-${hash}`:await unixEndpoint(hash)}}async function metadata(id){try{const item=JSON.parse(await readFile(id.file,"utf8"));if(item.endpoint!==id.endpoint||!Number.isSafeInteger(item.pid)||item.pid<1||typeof item.nonce!=="string"||!/^[a-f0-9]{64}$/.test(item.nonce)||typeof item.startedAt!=="string")return null;return item}catch{return null}}class ResidentStatusUnavailable extends Error{disconnected;constructor(disconnected){super("Resident status is unavailable; inspect the running host before retrying");this.disconnected=disconnected}}async function request(id,command,timeout=2e3){let item=await metadata(id);if(!item)return null;const deadline=Date.now()+Math.min(timeout,1e3);for(;;){try{return await requestOnce(id,item,command,timeout)}catch(error){if(!(error instanceof ResidentStatusUnavailable)||!error.disconnected||Date.now()>=deadline)throw error;await delay(20);item=await metadata(id)??item}}}function requestOnce(id,item,command,timeout){const operationalContext=currentOperationalExecution();return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="";let settled=false;let connected=false;const finish=(result,error,disconnected=false)=>{if(settled)return;if(result===null&&!error&&connected&&command==="status"){error=new ResidentStatusUnavailable(disconnected)}settled=true;socket.destroy();if(error)reject(error);else done(result)};const incompatible=()=>finish(null,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));socket.setTimeout(timeout,()=>finish(null));socket.on("error",error=>finish(null,!connected&&error.code!=="ENOENT"&&error.code!=="ECONNREFUSED"?error:void 0,true));socket.on("end",()=>finish(null,void 0,true));socket.on("connect",()=>{connected=true;if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();socket.write(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,command,nonce:item.nonce,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n")});socket.on("data",chunk=>{text+=chunk.toString();if(text.length>65536)return finish(null);if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return incompatible();finish(typeof value.running==="boolean"?value:null)}catch{finish(null)}})})}export async function residentStatus(root){return await request(await identity(root),"status")??{running:false}}async function residentRpc(root,message,signal){const operationalContext=currentOperationalExecution();const id=await identity(root),item=await metadata(id);if(!item)throw new Error("Resident is not running");return new Promise((done,reject)=>{const socket=createConnection(id.endpoint);socket.setEncoding("utf8");let text="",settled=false;const finish=(value,error)=>{if(settled)return;settled=true;signal?.removeEventListener("abort",abort);socket.destroy();if(error)reject(error);else done(value)};const abort=()=>finish(void 0,new Error("Resident request was cancelled"));signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted)return abort();socket.setTimeout(11*6e4,()=>finish(void 0,new Error("Resident request timed out")));socket.on("error",error=>finish(void 0,error));socket.on("end",()=>finish(void 0,new Error("Resident sync ended without a result")));socket.on("connect",()=>{if(item.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION)return finish(void 0,new Error("Resident IPC protocol is incompatible; stop it using its installed version before upgrading"));const payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,nonce:item.nonce,...message,...item.operationalContextVersion===1&&operationalContext?{operationalContext}:{}})+"\n";if(Buffer.byteLength(payload)>REQUEST_BYTES)return finish(void 0,new Error("Resident request was too large"));socket.write(payload)});socket.on("data",chunk=>{text+=chunk.toString();if(Buffer.byteLength(text)>RESPONSE_BYTES)return finish(void 0,new Error("Resident response was too large"));if(!text.includes("\n"))return;try{const value=JSON.parse(text.split("\n")[0]);if(value.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||!value.result)return finish(void 0,new Error("Resident response was invalid"));finish(value.result)}catch{finish(void 0,new Error("Resident response was invalid"))}})})}export function residentLocalCloudControl(root,request2){if(!isLocalCloudControlRequest(request2))return Promise.reject(new Error("Invalid Local Cloud control request"));return residentRpc(root,{command:"local-cloud-control",request:request2})}export function residentSync(root,source,requestId,options={}){return residentRpc(root,{command:"sync",source,requestId,...options.bindingId?{bindingId:options.bindingId}:{}},options.signal)}export function residentGatewayCall(root,request2,signal){return residentRpc(root,{command:"gateway",request:request2},signal)}export function residentEnsureReady(root,source,signal){return residentRpc(root,{command:"ensure-ready",source},signal)}export function residentCheck(root,source,signal){return residentRpc(root,{command:"check",source},signal)}export function residentRead(root,source,request2={},signal){return residentRpc(root,{command:"read",source,request:request2},signal)}export function residentInvoke(root,request2,signal){return residentRpc(root,{command:"invoke",request:request2},signal)}export function residentConnect(root,source,requestId,signal,settings={automatic:false}){return residentRpc(root,{command:"connect",source,requestId,automatic:settings.automatic,...settings.manualPresentation?{manualPresentation:settings.manualPresentation}:{}},signal)}export function residentConnectJob(root,requestId,signal){return residentRpc(root,{command:"connect-job",requestId},signal)}export function residentPauseConnectionAutomation(root,signal){return residentRpc(root,{command:"pause-connection-automation"},signal)}export function residentResumeBackgroundSync(root,signal){return residentRpc(root,{command:"resume-background-sync"},signal)}export function residentConnectManual(root,source,requestId,signal){return residentRpc(root,{command:"connect-manual",source,requestId},signal)}export function residentReconnectSaved(root,source,signal){return residentRpc(root,{command:"reconnect-saved",source},signal)}export function residentConnectGmailWrite(root,requestId,signal){return residentRpc(root,{command:"connect-gmail-write",requestId},signal)}export function residentConnectReadwiseMcpWrite(root,requestId,signal){return residentRpc(root,{command:"connect-readwise-mcp-write",requestId},signal)}export function residentConnectReauthorize(root,source,requestId,signal){return residentRpc(root,{command:"connect-reauthorize",source,requestId},signal)}export function residentConnectRecovery(root,source,requestId,signal){return residentRpc(root,{command:"connect-recovery",source,requestId},signal)}export function residentConnectAutomatic(root,source,requestId,signal){return residentRpc(root,{command:"connect-automatic",source,requestId},signal)}export function residentConfigureWeChat(root,port,signal){return residentRpc(root,{command:"configure-wechat",port},signal)}export async function residentConfigureJoplin(root,selection,signal){validateJoplinSelection(selection);return residentRpc(root,{command:"configure-joplin",selection},signal)}export function residentConfigureThunderbird(root,port,signal){return residentRpc(root,{command:"configure-thunderbird",port},signal)}export function residentConfigureDiscord(root,selection,signal){return residentRpc(root,{command:"configure-discord",selection},signal)}export function residentConfigureProtonMail(root,port,signal){return residentRpc(root,{command:"configure-proton-mail",port},signal)}export function residentConfigureZulip(root,selection,signal){return residentRpc(root,{command:"configure-zulip",selection},signal)}export function residentConfigureFreshRSS(root,selection,signal){return residentRpc(root,{command:"configure-freshrss",selection},signal)}export function residentConfigureMiniflux(root,selection,signal){return residentRpc(root,{command:"configure-miniflux",selection},signal)}export function residentConfigureMattermost(root,selection,signal){return residentRpc(root,{command:"configure-mattermost",selection},signal)}export function residentConfigureWallabag(root,selection,signal){return residentRpc(root,{command:"configure-wallabag",selection},signal)}export function residentConfigureCalcom(root,selection,signal){return residentRpc(root,{command:"configure-calcom",selection},signal)}export function residentConfigureWakatime(root,selection,signal){return residentRpc(root,{command:"configure-wakatime",selection},signal)}export function residentConfigureNextcloud(root,instanceUrl,signal){return residentRpc(root,{command:"configure-nextcloud",instanceUrl},signal)}export function residentConfigureDropbox(root,selection,signal){return residentRpc(root,{command:"configure-dropbox",selection},signal)}export function residentConfigureBox(root,selection,signal){return residentRpc(root,{command:"configure-box",selection},signal)}export function residentConfigureFront(root,selection,signal){return residentRpc(root,{command:"configure-front",selection},signal)}export function residentConfigureHubSpot(root,selection,signal){return residentRpc(root,{command:"configure-hubspot",selection},signal)}export function residentConfigureGoogleContacts(root,selection,signal){return residentRpc(root,{command:"configure-google-contacts",selection},signal)}export function residentConfigureGoogleChat(root,selection,signal){return residentRpc(root,{command:"configure-google-chat",selection},signal)}export function residentConfigureSalesforce(root,selection,signal){return residentRpc(root,{command:"configure-salesforce",selection},signal)}export function residentConfigureZendesk(root,selection,signal){return residentRpc(root,{command:"configure-zendesk",selection},signal)}export function residentConfigureZoom(root,selection,signal){return residentRpc(root,{command:"configure-zoom",selection},signal)}export function residentConfigureSmartsheet(root,region,signal){return residentRpc(root,{command:"configure-smartsheet",region},signal)}export function residentConfigureFigma(root,mode,signal){return residentRpc(root,{command:"configure-figma",mode},signal)}export function residentConfigureFreshdesk(root,subdomain,signal){return residentRpc(root,{command:"configure-freshdesk",subdomain},signal)}export function residentConfigureCopyQ(root,executable,session,signal){return residentRpc(root,{command:"configure-copyq",executable,session},signal)}export function residentConfigureOwnTracks(root,port,signal){return residentRpc(root,{command:"configure-owntracks",port},signal)}export function residentConfigureZotero(root,libraryId,libraryType,signal){return residentRpc(root,{command:"configure-zotero",libraryId,libraryType},signal)}export function residentConfigureNativeFiles(root,source,roots,signal){return residentRpc(root,{command:"configure-native-files",source,roots},signal)}export function residentConnectorStatus(root,signal){return residentRpc(root,{command:"connector-status"},signal)}export function residentConnectorCheck(root,source,signal){return residentRpc(root,{command:"connector-check",source},signal)}export function residentConnectorRead(root,source,signal){return residentRpc(root,{command:"connector-read",source},signal)}export function residentCancelConnect(root,requestId,generation,challengeRef){if(!Number.isSafeInteger(generation)||generation<0||!challengeRef)return Promise.resolve({err:{code:"stale_job_generation"}});return residentRpc(root,{command:"connect-cancel",requestId,generation,challengeRef})}function listen(server,endpoint){return new Promise((done,reject)=>{const fail=error=>{server.off("listening",ready);reject(error)};const ready=()=>{server.off("error",fail);done()};server.once("error",fail);server.once("listening",ready);server.listen(endpoint)})}function unixOwnership(id){const lock=new DatabaseSync(join(id.directory,"resident-owner.sqlite"),{allowExtension:false,timeout:0});try{lock.exec("BEGIN EXCLUSIVE");return lock}catch(error){lock.close();if(error.errcode===5)return null;throw error}}async function recoverUnixEndpoint(endpoint){let before;try{before=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!before.isSocket())return false;const refused=await new Promise(done=>{const socket=createConnection(endpoint);let settled=false;const finish=value=>{if(!settled){settled=true;socket.destroy();done(value)}};socket.once("connect",()=>finish(false));socket.once("error",error=>finish(error.code==="ECONNREFUSED"));socket.setTimeout(2e3,()=>finish(false))});if(!refused)return false;let after;try{after=await lstat(endpoint)}catch(error){if(error.code==="ENOENT")return true;throw error}if(!after.isSocket()||after.dev!==before.dev||after.ino!==before.ino)return false;await unlink(endpoint);return true}export async function runResidentServer(root,onStop,status=()=>({}),handlers={}){handlers=observeResidentHandlers(handlers);const id=await identity(root);await mkdir(id.directory,{recursive:true,mode:448});const ownership=process.platform==="win32"?void 0:unixOwnership(id);if(ownership===null)return null;const item={protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,operationalContextVersion:1,pid:process.pid,nonce:randomBytes(32).toString("hex"),endpoint:id.endpoint,startedAt:new Date().toISOString()};const runtime=await residentRuntimeIdentity();const sockets=new Set;let stopping;let closing;const server=createServer(socket=>{socket.setEncoding("utf8");const reply=result=>{if(socket.destroyed)return;let payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n";if(Buffer.byteLength(payload)>RESPONSE_BYTES)payload=JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result:{err:{code:"resource_exhausted",message:"The source result exceeds the resident response limit."}}})+"\n";socket.end(payload)};const disconnected=new AbortController;sockets.add(socket);socket.on("close",()=>{sockets.delete(socket);disconnected.abort()});socket.on("error",()=>{});socket.setTimeout(2e3,()=>socket.destroy());let input="";let handled=false;socket.on("data",chunk=>{if(handled)return;input+=chunk.toString();if(Buffer.byteLength(input)>REQUEST_BYTES){handled=true;socket.destroy();return}if(!input.includes("\n"))return;handled=true;void(async()=>{try{const envelope=JSON.parse(input.split("\n")[0]);if(envelope.protocolVersion!==RESIDENT_IPC_PROTOCOL_VERSION||typeof envelope.nonce!=="string"||envelope.nonce.length!==item.nonce.length||!timingSafeEqual(Buffer.from(envelope.nonce),Buffer.from(item.nonce))){socket.destroy();return}const{operationalContext,...message}=envelope;if(operationalContext!==void 0&&!isOperationalContext(operationalContext)){socket.destroy();return}async function configureSelection(valid,configure){if(!configure||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!valid(message.selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await configure(message.selection))}const dispatch=async()=>{if((stopping||closing)&&message.command!=="status"&&message.command!=="stop"){reply({err:{code:"unavailable",message:"The background host is stopping."}});return}if(message.command==="status"){const{nonce:_nonce,endpoint:_endpoint,...safe}=traceResidentControl(handlers.telemetry,{phase:"runtime",action:"status",operationId:"resident.status"},status,{plainResult:true});socket.end(JSON.stringify({...safe,runtime,protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:!stopping,pid:item.pid,startedAt:item.startedAt})+"\n")}else if(message.command==="sync"){if(!handlers.sync||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||message.bindingId!==void 0&&(typeof message.bindingId!=="string"||!message.bindingId||message.bindingId.length>200)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.sync(message.source,message.requestId,{signal:disconnected.signal,...message.bindingId?{bindingId:message.bindingId}:{}});reply(result)}else if(message.command==="local-cloud-control"){if(!isLocalCloudControlRequest(message.request)){socket.destroy();return}if(!handlers.localCloud){reply({err:{code:"unavailable",message:"This resident does not provide Local Cloud authorization controls."}});return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.localCloud(message.request))}else if(message.command==="gateway"){if(!handlers.gateway||!isResidentGatewayRequest(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.gateway(message.request,disconnected.signal))}else if(message.command==="ensure-ready"){if(!handlers.ensureReady||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());reply(await handlers.ensureReady(message.source,disconnected.signal))}else if(message.command==="check"){if(!handlers.check||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());reply(await handlers.check(message.source,disconnected.signal))}else if(message.command==="read"){if(!handlers.read||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||!message.request||typeof message.request!=="object"||Array.isArray(message.request)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.read(message.source,message.request,disconnected.signal);reply(result)}else if(message.command==="invoke"){const request2=message.request;if(!handlers.invoke||!request2||typeof request2!=="object"||Array.isArray(request2)){socket.destroy();return}socket.setTimeout(3*6e4,()=>socket.destroy());const result=await handlers.invoke(request2,disconnected.signal);reply(result)}else if(message.command==="connect"){if(!handlers.connect||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||typeof message.automatic!=="boolean"){socket.destroy();return}const manualPresentation=message.manualPresentation==="return-url"?"return-url":message.manualPresentation==="open"?"open":void 0;socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connect(message.source,message.requestId,disconnected.signal,{automatic:message.automatic,...manualPresentation?{manualPresentation}:{}});reply(result)}else if(message.command==="connect-manual"){if(!handlers.connectManual||typeof message.source!=="string"||!HELP_MANUAL_SOURCES.has(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectManual(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="reconnect-saved"){if(!handlers.reconnectSaved||typeof message.source!=="string"||!supportsSavedReconnect(message.source)||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source"].includes(key))){socket.destroy();return}socket.setTimeout(9e4,()=>socket.destroy());const result=await handlers.reconnectSaved(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-gmail-write"){if(!handlers.connectGmailWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectGmailWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-readwise-mcp-write"){if(!handlers.connectReadwiseMcpWrite||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReadwiseMcpWrite(message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-reauthorize"){if(!handlers.connectReauthorize||typeof message.source!=="string"||!["todoist","linear"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectReauthorize(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-recovery"){if(!handlers.connectRecovery||typeof message.source!=="string"||!["gmail","google-drive","google-calendar","youtube","google-tasks"].includes(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||Object.keys(message).some(key=>!["protocolVersion","nonce","command","source","requestId"].includes(key))){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectRecovery(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-automatic"){if(!handlers.connectAutomatic||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectAutomatic(message.source,message.requestId,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connect-job"){if(!handlers.connectJob||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150){socket.destroy();return}const result=await handlers.connectJob(message.requestId);reply(result)}else if(message.command==="connect-cancel"){if(!handlers.cancelConnect||typeof message.requestId!=="string"||!message.requestId||message.requestId.length>150||!Number.isSafeInteger(message.generation)||message.generation<0||typeof message.challengeRef!=="string"||!message.challengeRef||message.challengeRef.length>200){socket.destroy();return}const result=await handlers.cancelConnect(message.requestId,message.generation,message.challengeRef);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-wechat"){if(!handlers.configureWeChat||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureWeChat({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-joplin"){if(!handlers.configureJoplin||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{validateJoplinSelection(message.selection)}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureJoplin(message.selection,disconnected.signal);reply(result)}else if(message.command==="configure-thunderbird"){if(!handlers.configureThunderbird||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureThunderbird({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-discord"){if(!handlers.configureDiscord||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))){socket.destroy();return}try{const selection=message.selection;if(!selection||typeof selection!=="object"||Array.isArray(selection)||Reflect.ownKeys(selection).some(key=>typeof key!=="string"||!["clientId","expectedSubject","ipcPath","channelIds"].includes(key)))throw Error("invalid");createPreparedDiscordSource("discord",{mode:"fields",...selection})}catch{socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDiscord(message.selection);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-proton-mail"){if(!handlers.configureProtonMail||Object.keys(message).some(key=>!["protocolVersion","nonce","command","port"].includes(key))||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureProtonMail({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zulip"){await configureSelection(validZulipSelection,handlers.configureZulip?.bind(handlers))}else if(message.command==="configure-freshrss"){await configureSelection(validFreshRSSSelection,handlers.configureFreshRSS?.bind(handlers))}else if(message.command==="configure-miniflux"){await configureSelection(validMinifluxSelection,handlers.configureMiniflux?.bind(handlers))}else if(message.command==="configure-mattermost"){await configureSelection(validMattermostSelection,handlers.configureMattermost?.bind(handlers))}else if(message.command==="configure-wallabag"){await configureSelection(validWallabagSelection,handlers.configureWallabag?.bind(handlers))}else if(message.command==="configure-calcom"){await configureSelection(validCalcomSelection,handlers.configureCalcom?.bind(handlers))}else if(message.command==="configure-wakatime"){await configureSelection(validWakatimeSelection,handlers.configureWakatime?.bind(handlers))}else if(message.command==="configure-nextcloud"){if(!handlers.configureNextcloud||Object.keys(message).some(key=>!["protocolVersion","nonce","command","instanceUrl"].includes(key))||!validNextcloudInstanceUrl(message.instanceUrl)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNextcloud({instanceUrl:message.instanceUrl});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-dropbox"){const selection=message.selection;if(!handlers.configureDropbox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureDropbox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-box"){const selection=message.selection;if(!handlers.configureBox||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureBox({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-front"){const selection=message.selection;if(!handlers.configureFront||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFront({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-hubspot"){const selection=message.selection;if(!handlers.configureHubSpot||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==2||Object.keys(selection).some(key=>!["clientId","loopbackPort"].includes(key))||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureHubSpot({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-contacts"){const selection=message.selection;if(!handlers.configureGoogleContacts||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleContacts({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-google-chat"){const selection=message.selection;if(!handlers.configureGoogleChat||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length<2||Object.keys(selection).length>3||Object.keys(selection).some(key=>!["clientId","loopbackPort","developerPreview"].includes(key))||selection.developerPreview!==void 0&&typeof selection.developerPreview!=="boolean"||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureGoogleChat({clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-salesforce"){const selection=message.selection;if(!handlers.configureSalesforce||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==3||Object.keys(selection).some(key=>!["environment","clientId","loopbackPort"].includes(key))||!["production","sandbox"].includes(selection.environment)||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)||!Number.isInteger(selection.loopbackPort)||selection.loopbackPort<1024||selection.loopbackPort>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSalesforce({environment:selection.environment,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zendesk"){const selection=message.selection;if(!handlers.configureZendesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!validZendeskSelection(selection)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZendesk({subdomain:selection.subdomain,clientId:selection.clientId,loopbackPort:selection.loopbackPort});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zoom"){const selection=message.selection;if(!handlers.configureZoom||Object.keys(message).some(key=>!["protocolVersion","nonce","command","selection"].includes(key))||!selection||typeof selection!=="object"||Array.isArray(selection)||Object.keys(selection).length!==1||Object.keys(selection).some(key=>key!=="clientId")||typeof selection.clientId!=="string"||!selection.clientId||selection.clientId.length>2048||/\s|[\u0000-\u001f\u007f-\u009f]/u.test(selection.clientId)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZoom({clientId:selection.clientId});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-smartsheet"){if(!handlers.configureSmartsheet||Object.keys(message).some(key=>!["protocolVersion","nonce","command","region"].includes(key))||!["us","eu","au"].includes(message.region)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureSmartsheet({region:message.region});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-figma"){if(!handlers.configureFigma||Object.keys(message).some(key=>!["protocolVersion","nonce","command","mode"].includes(key))||!["fields","oauth"].includes(message.mode)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFigma(message.mode);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-freshdesk"){if(!handlers.configureFreshdesk||Object.keys(message).some(key=>!["protocolVersion","nonce","command","subdomain"].includes(key))||typeof message.subdomain!=="string"||message.subdomain.length>63||!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(message.subdomain)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureFreshdesk({subdomain:message.subdomain});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-copyq"){if(!handlers.configureCopyQ||typeof message.executable!=="string"||message.executable.length<1||message.executable.length>512||typeof message.session!=="string"||!/^[\p{L}\p{N}_-]{0,16}$/u.test(message.session)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureCopyQ({executable:message.executable,session:message.session});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-owntracks"){if(!handlers.configureOwnTracks||!Number.isInteger(message.port)||message.port<1024||message.port>65535){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureOwnTracks({port:message.port});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-zotero"){if(!handlers.configureZotero||typeof message.libraryId!=="string"||!["user","group"].includes(message.libraryType)||!/^[1-9][0-9]{0,19}$/.test(message.libraryId)&&!(message.libraryType==="user"&&message.libraryId==="0")){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureZotero({libraryId:message.libraryId,libraryType:message.libraryType});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="configure-native-files"){const sources=["visual-studio","modelsim","quartus","simulink","jianying","epic-games-launcher","ryujinx","modrinth","powerpoint","ti-ccs","pscad","adobe-photoshop","autocad","microsoft-word","microsoft-excel","local-git","vscode-local-history","libreoffice","adobe-acrobat","adobe-camera-raw","adobe-media-encoder","ansys-electronics-desktop","adobe-premiere-pro","packet-tracer","qt-designer","hearthstone-deck-tracker","visio","matlab","adobe-illustrator","minecraft-java","ni-tdms","jupyter","solidworks","lattics","jetbrains","eclipse","multisim","stm32cubemx","plecs","local-audio","obsidian","logseq","computer-files"];if(!handlers.configureNativeFiles||!sources.includes(message.source)||!Array.isArray(message.roots)||message.roots.length<1||message.roots.length>16||!message.roots.every(root2=>typeof root2==="string"&&root2.length>0&&root2.length<=4096)){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());const result=await handlers.configureNativeFiles({source:message.source,roots:message.roots});if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-status"){if(!handlers.connectorStatus){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorStatus();if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-check"){if(!handlers.connectorCheck||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorCheck(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="connector-read"){if(!handlers.connectorRead||typeof message.source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(message.source)){socket.destroy();return}socket.setTimeout(11*6e4,()=>socket.destroy());const result=await handlers.connectorRead(message.source,disconnected.signal);if(!socket.destroyed)socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,result})+"\n")}else if(message.command==="pause-connection-automation"){if(!handlers.pauseAutomation||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.pauseAutomation())}else if(message.command==="resume-background-sync"){if(!handlers.resumeBackgroundSync||Object.keys(message).some(key=>!["protocolVersion","nonce","command"].includes(key))){socket.destroy();return}socket.setTimeout(3e4,()=>socket.destroy());reply(await handlers.resumeBackgroundSync())}else if(message.command==="stop"){socket.setTimeout(3e4,()=>socket.destroy());stopping??=Promise.resolve().then(()=>traceResidentControl(handlers.telemetry,{phase:"runtime",action:"cleanup",operationId:"resident.stop"},onStop,{plainResult:true}));try{await stopping}catch{stopping=void 0;socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:true,error:"resident_cleanup_failed"})+"\n");return}socket.end(JSON.stringify({protocolVersion:RESIDENT_IPC_PROTOCOL_VERSION,running:false,stopped:true})+"\n");void close()}else socket.destroy()};if(operationalContext)await withOperationalContext(operationalContext,dispatch);else await withoutOperationalContext(dispatch)}catch{socket.destroy()}})()})});const close=()=>closing??=(async()=>{try{const closed=new Promise(done=>server.close(()=>done()));for(const socket of sockets)socket.end();await closed;if((await metadata(id))?.nonce===item.nonce)await unlink(id.file).catch(()=>{})}finally{ownership?.close()}})();try{try{await listen(server,id.endpoint)}catch(error){if(error.code!=="EADDRINUSE")throw error;if(process.platform==="win32"||!await recoverUnixEndpoint(id.endpoint)){await close();return null}try{await listen(server,id.endpoint)}catch(retryError){if(retryError.code!=="EADDRINUSE")throw retryError;await close();return null}}if(process.platform!=="win32")await chmod(id.endpoint,384);const temporary=`${id.file}.${item.nonce}.tmp`;try{await writeFile(temporary,JSON.stringify(item),{mode:384,flag:"wx"});await rename(temporary,id.file)}finally{await unlink(temporary).catch(()=>{})}}catch(error){await close();throw error}return{close}}function windowsQuote(value){return'"'+value.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\+)$/g,"$1$1")+'"'}const xml=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");export function residentStartupPlan(root,entrypoint,hash,platform=process.platform,executable=process.execPath,home=homedir(),environment=process.env){if(![root,entrypoint,executable].every(isAbsolute))throw new Error("Resident startup paths must be absolute");if(![root,entrypoint,executable].every(value=>!/[\r\n\0]/.test(value)))throw new Error("Invalid resident startup path");if(!/^[a-f0-9]{24}$/.test(hash))throw new Error("Invalid resident identity");const syncDisabled=/^(0|false|off|no)$/i.test((environment.ZORTEX_AUTO_SYNC??"").trim());const args=[entrypoint,"--root",root,"host","run",...syncDisabled?["--sync-disabled"]:[]];const command=[executable,...args].map(windowsQuote).join(" ");const launcherPath=join(root,"host","resident-startup.vbs");const launcher=`Option Explicit\r
|
|
2
2
|
CreateObject("WScript.Shell").Run "${command.replaceAll('"','""')}", 0, False\r
|
|
3
3
|
`;const registryCommand=[windowsQuote("%SystemRoot%\\System32\\wscript.exe"),"//B","//NoLogo",windowsQuote(launcherPath)].join(" ");const label=`com.zortex.indra.${hash}`;const plist=`<?xml version="1.0" encoding="UTF-8"?>
|
|
4
4
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{businessError}from"@zortexhq/plugin-connector-framework/api";import{createHash}from"node:crypto";import{isBrowserSource,locateBrowserProfile}from"@zortexhq/plugin-connector-chrome-history";export function createSourceData(ctx,now=Date.now){const store=ctx.get("zortexSqliteVault")?.createSourceSyncStore?.();async function authority(source,bindingId){if(!bindingId&&isBrowserSource(source)){const root=source==="google-chrome"?process.env.INDRA_CHROME_READ_ROOT??process.env.ZORTEX_CHROME_HISTORY_ROOT:process.env.INDRA_EDGE_READ_ROOT??process.env.ZORTEX_EDGE_HISTORY_ROOT;const profile=locateBrowserProfile(source,root?{root}:{});if(!("ok"in profile))return;return{source,account:createHash("sha256").update(profile.ok.userDataDir).digest("hex"),revision:"local-profile-v1",scopes:["history"]}}const custody=ctx.get("zortexVaultStore")?.bindingCustody;if(!custody)return;const selected=await custody.resolve(bindingId?{kind:"binding",bindingId}:{kind:"selected-source",source});if(!("ok"in selected)||selected.ok.kind!=="resolved")return;const binding=selected.ok.binding;if(binding.state!=="connected"||binding.identity.source!==source)return;const grant=await custody.grantForBinding(binding.id,"L1",binding.provider);if(!("ok"in grant)||!grant.ok||grant.ok.state!=="active")return;return{source,account:binding.identity.subject??binding.id,bindingId:binding.id,revision:`${binding.revision}:${grant.ok.id}:${grant.ok.revision}`,scopes:grant.ok.scopes,scopeEpoch:grant.ok.scopeEpoch}}async function read(source,bindingId){const selected=await authority(source,bindingId);if(!store||!selected)return void 0;const found=store.read(selected);return"ok"in found?found.ok?.state:void 0}async function run(source,signal,action,bindingId){if(signal.aborted)return businessError("aborted","Source sync was cancelled.","connector");if(!store)return action();const selected=await authority(source,bindingId);const previous=selected?store.read(selected):void 0;if(previous&&"err"in previous)return previous;const snapshot=previous&&"ok"in previous?previous.ok:null;const before=snapshot?.state??{source,phase:"pending",coverage:{status:"unknown",resources:[],limitations:[]},appended:0};let revision=snapshot?.revision??0;const started=new Date(now()).toISOString();const running={...before,phase:"syncing",lastAttemptAt:started};delete running.nextAt;delete running.errorCode;if(selected){const saved2=store.write(selected,running,revision);if(!("ok"in saved2))return saved2;revision=saved2.ok.revision}let result;try{result=await action()}catch{result={err:{code:signal.aborted?"aborted":"unavailable"}}}if(signal.aborted)result={err:{code:"aborted"}};const after=await authority(source,bindingId);if(!after)return result;if(selected&&JSON.stringify(after)!==JSON.stringify(selected))return businessError("permission_denied","Source authority changed during sync.","storage");if(!selected){const found=store.read(after);if(!("ok"in found))return found;revision=found.ok?.revision??0}const finished=new Date(now()).toISOString();const metadata=await Promise.resolve().then(()=>ctx.get("zortexConnectorHub")?.status({signal})).catch(()=>void 0);const data=metadata&&"ok"in metadata?metadata.ok.find(row=>row.source===source)?.data:void 0;const value="ok"in result?result.ok:void 0;const complete=value?.complete===true;const limitations=[...data?.limitations??[]];if(!data||data.history!=="sync")limitations.push("coverage_not_declared");if(Array.isArray(value?.warnings)&&value.warnings.length)limitations.push("provider_warnings");const ready=complete&&limitations.length===0;const count=typeof value?.appended==="number"&&Number.isSafeInteger(value.appended)&&value.appended>=0?value.appended:0;const state=value?{...before,phase:ready?"ready":"partial",coverage:{status:ready?"complete":"partial",resources:[...data?.resources??[]],limitations},appended:before.appended+count,lastAttemptAt:started,lastSuccessAt:finished,...complete?{initialCompletedAt:before.initialCompletedAt??finished,checkedAt:finished}:{},nextAt:new Date(now()+(complete?15*6e4:0)).toISOString()}:{...before,phase:signal.aborted?"paused":"blocked",lastAttemptAt:started,errorCode:"err"in result?result.err.code:"unavailable"};if(value)delete state.errorCode;const saved=store.write(after,state,revision);return"ok"in saved?result:saved}return{read,run}}
|
package/dist/supervised-sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isBrowserSource,locateBrowserProfile}from"@zortexhq/plugin-connector-chrome-history";import{Original}from"@zortexhq/plugin-connector-framework/api";import{join,resolve}from"node:path";import{createHash}from"node:crypto";import{fileURLToPath}from"node:url";import{createTraceRecorder,withFeedbackFlow}from"@zortexhq/plugin-telemetry/api";import{createSyncObservation}from"./operational-observation.js";const error=(code,message,layer="connector")=>Original.errResult({code,layer,retryability:"non-retryable",message});async function executeChrome(ctx,root,requestId,observation,options={}){const access=ctx.get("zortexLocalSourceAccess"),supervisor=ctx.get("zortexConnectorSupervisor"),journal=ctx.get("zortexConnectorProcessJournal");if(!access||!supervisor||!journal)return error("failed_precondition","Original synchronization services are unavailable.","kernel");const selected=access.resolve("chrome-history");if(!Original.isOk(selected))return selected;let outcome;try{outcome=await supervisor.execute({requestId,stateDir:join(root,"sync-state","chrome-history",selected.ok.grant.id),argv:[process.execPath,fileURLToPath(new URL("./connector-worker.js",import.meta.url)),resolve(root),fileURLToPath(new URL("../profiles/chrome-worker.yml",import.meta.url)),"chrome-history"],cwd:resolve(root),env:{ZORTEX_SELECTED_LOCAL_SOURCE_DIRECTORY:selected.ok.location}},options)}catch{return error("failed_precondition","Connector service did not admit or execute this request.","kernel")}let business;try{business=journal.readBusiness(outcome.runId)}catch(fault){await observation.admitted(outcome,null);throw fault}await observation.admitted(outcome,business);if(!outcome.cleanupConfirmed)return error("failed_precondition","Process cleanup remains unverified.");if(outcome.phase==="cancelled")return error("aborted","Connector sync was cancelled.");if(outcome.phase==="timed-out")return error("deadline_exceeded","Connector sync exceeded its execution budget.");if(!business||business.source!=="chrome-history")return error("data_loss","Worker has no committed source business receipt.");if(!Original.isOk(business.result))return business.result;if(business.result.ok.error!==void 0){const fault=Original.validateStructuredError(business.result.ok.error);return Original.isOk(fault)?Original.errResult(fault.ok):error("data_loss","Invalid structured worker error.")}if(outcome.phase!=="completed"||business.result.ok.runFailed===true||business.result.ok.stopped===true||business.result.ok.state!=="IDLE")return error("unavailable","Connector worker did not complete the source operation.");return Original.ok({...business.result.ok,executionId:outcome.runId,codeVersion:business.codeVersion})}const WORKERS={gmail:{provider:"google",profile:"google-worker.yml"},"google-drive":{provider:"google",profile:"google-worker.yml"},"google-calendar":{provider:"google",profile:"google-worker.yml"},youtube:{provider:"google",profile:"google-worker.yml"},slack:{provider:"slack",profile:"account-worker.yml"},outlook:{provider:"microsoft",profile:"account-worker.yml"},"google-chrome":{provider:"local",profile:"browser-worker.yml"},"microsoft-edge":{provider:"local",profile:"browser-worker.yml"}};export const WORKER_SYNC_SOURCES=Object.keys(WORKERS);export const isWorkerSyncSource=source=>typeof source==="string"&&Object.hasOwn(WORKERS,source);const browserLocator=source=>{const root=source==="google-chrome"?process.env.INDRA_CHROME_READ_ROOT??process.env.ZORTEX_CHROME_HISTORY_ROOT:process.env.INDRA_EDGE_READ_ROOT??process.env.ZORTEX_EDGE_HISTORY_ROOT;return root?{root}:{}};export function browserReady(source){return WORKERS[source].provider==="local"&&isBrowserSource(source)&&Original.isOk(locateBrowserProfile(source,browserLocator(source)))}export function sourceActive(ctx,source){const id="indra-source-"+source,row=[...ctx.loader.entries()].find(entry=>entry.options.id===id);return!!row&&!row.disabled&&row.fiber?.state===2}const SYNC_HARD_LIMIT_MS=6e5,SYNC_BUDGET_MS=54e4;async function executeWorkerSource(ctx,root,source,requestId,observation,options={}){const vault=ctx.get("zortexVaultStore"),supervisor=ctx.get("zortexConnectorSupervisor"),journal=ctx.get("zortexConnectorProcessJournal");if(!vault||!supervisor||!journal)return error("failed_precondition","Source sync services are unavailable.","kernel");const worker=WORKERS[source];let key,browserRoot;if(worker.provider==="local"){if(!isBrowserSource(source))return error("invalid_argument","Unknown browser source.");const found=locateBrowserProfile(source,browserLocator(source));if(!Original.isOk(found))return found;browserRoot=found.ok.userDataDir;key=createHash("sha256").update(JSON.stringify({source,account:"local"})).digest("hex").slice(0,32)}else if(options.bindingId){const selected=await vault.bindingCustody.resolve({kind:"binding",bindingId:options.bindingId});if(!Original.isOk(selected))return selected;if(selected.ok.kind!=="resolved")return error("failed_precondition","Select one connected account binding before full sync.","auth");const binding=selected.ok.binding;if(binding.identity.source!==source||binding.state!=="connected"||binding.provider!==worker.provider)return error("unauthenticated","Connect and verify this account before full sync.","auth");const grant=await vault.bindingCustody.grantForBinding(binding.id,"L1",binding.provider);if(!Original.isOk(grant))return grant;if(!grant.ok||grant.ok.state!=="active"||options.grantId&&grant.ok.id!==options.grantId||options.scopeEpoch!==void 0&&grant.ok.scopeEpoch!==options.scopeEpoch)return error("permission_denied","Selected account authority changed before full sync.","auth");key=createHash("sha256").update(JSON.stringify({source,binding:binding.id,account:binding.identity.subject,epoch:binding.updatedAt,grant:grant.ok.id,scopeEpoch:grant.ok.scopeEpoch})).digest("hex").slice(0,32);options={...options,bindingId:binding.id,grantId:grant.ok.id,scopeEpoch:grant.ok.scopeEpoch}}else{const selected=await vault.connection(source);if(!Original.isOk(selected))return selected;const connection=selected.ok,account=connection?.accountId??connection?.account;if(!connection||connection.state!=="connected"||connection.provider!==worker.provider||!account||!connection.updatedAt)return error("unauthenticated","Connect and verify this account before full sync.","auth");key=createHash("sha256").update(JSON.stringify({source,account,epoch:connection.updatedAt})).digest("hex").slice(0,32)}let outcome;try{outcome=await supervisor.execute({requestId,stateDir:join(root,"sync-state",source,key),argv:[process.execPath,fileURLToPath(new URL("./connector-worker.js",import.meta.url)),resolve(root),fileURLToPath(new URL("../profiles/"+worker.profile,import.meta.url)),source],cwd:resolve(root),env:{ZORTEX_PROCESS_CODE_VERSION:"indra-v2/"+source+"@0.1.0+full-sync",...worker.provider==="local"?{ZORTEX_BROWSER_SOURCE:source,ZORTEX_BROWSER_READ_ROOT:browserRoot}:{},...options.bindingId?{ZORTEX_SELECTED_BINDING_ID:options.bindingId}:{},...options.grantId?{ZORTEX_SELECTED_GRANT_ID:options.grantId}:{},...options.scopeEpoch!==void 0?{ZORTEX_SELECTED_SCOPE_EPOCH:String(options.scopeEpoch)}:{},ZORTEX_SYNC_BUDGET_MS:String(SYNC_BUDGET_MS)}},{...options.signal?{signal:options.signal}:{},runMs:SYNC_HARD_LIMIT_MS})}catch{return Original.errResult({code:"resource_exhausted",layer:"kernel",retryability:"transient",message:"Another sync of this source is running, or its previous worker was not confirmed stopped; try again later."})}let receipt;try{receipt=journal.readBusiness(outcome.runId)}catch(fault){await observation.admitted(outcome,null,options.bindingId);throw fault}await observation.admitted(outcome,receipt,options.bindingId);if(!outcome.cleanupConfirmed)return error("failed_precondition","Process cleanup remains unverified.","kernel");if(outcome.phase==="cancelled")return error("aborted","Sync was cancelled.");if(outcome.phase==="timed-out")return error("deadline_exceeded","Sync reached its execution limit; the next run resumes from the saved cursor.");if(!receipt||receipt.source!==source)return error("data_loss","Sync worker has no committed source business receipt.");if(!Original.isOk(receipt.result))return receipt.result;if(receipt.result.ok.error!==void 0){const fault=Original.validateStructuredError(receipt.result.ok.error);return Original.isOk(fault)?Original.errResult(fault.ok):error("data_loss","Invalid sync worker error.")}if(receipt.result.ok.ran===false&&receipt.result.ok.state==="RETRY_WAIT"&&typeof receipt.result.ok.skipped==="string")return Original.errResult({code:"unavailable",layer:"connector",retryability:"transient",message:`Sync is waiting to retry after an earlier provider failure; run it again later (${receipt.result.ok.skipped.slice(0,300)}).`});if(outcome.phase!=="completed"||receipt.result.ok.runFailed===true)return error("unavailable","Sync worker did not finish its source operation.");return Original.ok({...receipt.result.ok,executionId:outcome.runId,codeVersion:receipt.codeVersion,complete:receipt.result.ok.state==="IDLE"&&receipt.result.ok.stopped!==true})}async function observeSync(ctx,source,requestId,action){const run=()=>withFeedbackFlow(source,async()=>{const observation=createSyncObservation(ctx,source,requestId);const trace=createTraceRecorder(()=>ctx.get("zortexTelemetry"),source);await trace.step("read_started","started");try{const result=await action(observation);await observation.notAdmitted(result);const value=result;if(value.err)await trace.step("read_verified",value.err.code==="aborted"?"cancelled":"failed",{error:value.err.code==="deadline_exceeded"?"timeout":"provider"});else if(value.ok){await trace.step("read_verified",value.ok.complete===false?"unknown":"completed");const count=value.ok.appended;if(typeof count==="number"&&Number.isSafeInteger(count)&&count>=0&&count<=1e8)await trace.step("vault_saved","completed",{count})}else await trace.step("read_verified","unknown");return result}catch(error2){await observation.notAdmitted(void 0);await trace.step("read_verified","failed",{error:"unknown"});throw error2}});const feedback=ctx.get("zortexConnectionFeedback");return feedback?feedback.run(source,run):run()}export function runSupervisedChrome(ctx,root,requestId,options={}){return observeSync(ctx,"chrome-history",requestId,observation=>executeChrome(ctx,root,requestId,observation,options))}export function runSupervisedSource(ctx,root,source,requestId,options={}){return observeSync(ctx,source,requestId,observation=>executeWorkerSource(ctx,root,source,requestId,observation,options))}export const runSupervisedGoogle=runSupervisedSource;
|
|
1
|
+
import{isBrowserSource,locateBrowserProfile}from"@zortexhq/plugin-connector-chrome-history";import{Original}from"@zortexhq/plugin-connector-framework/api";import{join,resolve}from"node:path";import{createHash}from"node:crypto";import{fileURLToPath}from"node:url";import{createTraceRecorder,withFeedbackFlow}from"@zortexhq/plugin-telemetry/api";import{createSyncObservation}from"./operational-observation.js";const error=(code,message,layer="connector")=>Original.errResult({code,layer,retryability:"non-retryable",message});async function executeChrome(ctx,root,requestId,observation,options={}){const access=ctx.get("zortexLocalSourceAccess"),supervisor=ctx.get("zortexConnectorSupervisor"),journal=ctx.get("zortexConnectorProcessJournal");if(!access||!supervisor||!journal)return error("failed_precondition","Original synchronization services are unavailable.","kernel");const selected=access.resolve("chrome-history");if(!Original.isOk(selected))return selected;let outcome;try{outcome=await supervisor.execute({requestId,stateDir:join(root,"sync-state","chrome-history",selected.ok.grant.id),argv:[process.execPath,fileURLToPath(new URL("./connector-worker.js",import.meta.url)),resolve(root),fileURLToPath(new URL("../profiles/chrome-worker.yml",import.meta.url)),"chrome-history"],cwd:resolve(root),env:{ZORTEX_SELECTED_LOCAL_SOURCE_DIRECTORY:selected.ok.location}},options)}catch{return error("failed_precondition","Connector service did not admit or execute this request.","kernel")}let business;try{business=journal.readBusiness(outcome.runId)}catch(fault){await observation.admitted(outcome,null);throw fault}await observation.admitted(outcome,business);if(!outcome.cleanupConfirmed)return error("failed_precondition","Process cleanup remains unverified.");if(outcome.phase==="cancelled")return error("aborted","Connector sync was cancelled.");if(outcome.phase==="timed-out")return error("deadline_exceeded","Connector sync exceeded its execution budget.");if(!business||business.source!=="chrome-history")return error("data_loss","Worker has no committed source business receipt.");if(!Original.isOk(business.result))return business.result;if(business.result.ok.error!==void 0){const fault=Original.validateStructuredError(business.result.ok.error);return Original.isOk(fault)?Original.errResult(fault.ok):error("data_loss","Invalid structured worker error.")}if(outcome.phase!=="completed"||business.result.ok.runFailed===true||business.result.ok.stopped===true||business.result.ok.state!=="IDLE")return error("unavailable","Connector worker did not complete the source operation.");return Original.ok({...business.result.ok,executionId:outcome.runId,codeVersion:business.codeVersion})}const WORKERS={gmail:{provider:"google",profile:"google-worker.yml"},"google-drive":{provider:"google",profile:"google-worker.yml"},"google-calendar":{provider:"google",profile:"google-worker.yml"},youtube:{provider:"google",profile:"google-worker.yml"},slack:{provider:"slack",profile:"account-worker.yml"},outlook:{provider:"microsoft",profile:"account-worker.yml"},"google-chrome":{provider:"local",profile:"browser-worker.yml"},"microsoft-edge":{provider:"local",profile:"browser-worker.yml"}};export const WORKER_SYNC_SOURCES=Object.keys(WORKERS);export const isWorkerSyncSource=source=>typeof source==="string"&&Object.hasOwn(WORKERS,source);const browserLocator=source=>{const root=source==="google-chrome"?process.env.INDRA_CHROME_READ_ROOT??process.env.ZORTEX_CHROME_HISTORY_ROOT:process.env.INDRA_EDGE_READ_ROOT??process.env.ZORTEX_EDGE_HISTORY_ROOT;return root?{root}:{}};export function browserReady(source){return WORKERS[source].provider==="local"&&isBrowserSource(source)&&Original.isOk(locateBrowserProfile(source,browserLocator(source)))}export function sourceActive(ctx,source){const id="indra-source-"+source,row=[...ctx.loader.entries()].find(entry=>entry.options.id===id);return!!row&&!row.disabled&&row.fiber?.state===2}const SYNC_HARD_LIMIT_MS=6e5,SYNC_BUDGET_MS=54e4;async function executeWorkerSource(ctx,root,source,requestId,observation,options={}){const vault=ctx.get("zortexVaultStore"),supervisor=ctx.get("zortexConnectorSupervisor"),journal=ctx.get("zortexConnectorProcessJournal");if(!vault||!supervisor||!journal)return error("failed_precondition","Source sync services are unavailable.","kernel");const worker=WORKERS[source];let key,browserRoot;if(worker.provider==="local"){if(!isBrowserSource(source))return error("invalid_argument","Unknown browser source.");const found=locateBrowserProfile(source,browserLocator(source));if(!Original.isOk(found))return found;browserRoot=found.ok.userDataDir;key=createHash("sha256").update(JSON.stringify({source,account:"local"})).digest("hex").slice(0,32)}else if(options.bindingId){const selected=await vault.bindingCustody.resolve({kind:"binding",bindingId:options.bindingId});if(!Original.isOk(selected))return selected;if(selected.ok.kind!=="resolved")return error("failed_precondition","Select one connected account binding before full sync.","auth");const binding=selected.ok.binding;if(binding.identity.source!==source||binding.state!=="connected"||binding.provider!==worker.provider)return error("unauthenticated","Connect and verify this account before full sync.","auth");const grant=await vault.bindingCustody.grantForBinding(binding.id,"L1",binding.provider);if(!Original.isOk(grant))return grant;if(!grant.ok||grant.ok.state!=="active"||options.grantId&&grant.ok.id!==options.grantId||options.scopeEpoch!==void 0&&grant.ok.scopeEpoch!==options.scopeEpoch)return error("permission_denied","Selected account authority changed before full sync.","auth");key=createHash("sha256").update(JSON.stringify({source,binding:binding.id,account:binding.identity.subject,epoch:binding.updatedAt,grant:grant.ok.id,scopeEpoch:grant.ok.scopeEpoch})).digest("hex").slice(0,32);options={...options,bindingId:binding.id,grantId:grant.ok.id,scopeEpoch:grant.ok.scopeEpoch}}else{const selected=await vault.connection(source);if(!Original.isOk(selected))return selected;const connection=selected.ok,account=connection?.accountId??connection?.account;if(!connection||connection.state!=="connected"||connection.provider!==worker.provider||!account||!connection.updatedAt)return error("unauthenticated","Connect and verify this account before full sync.","auth");key=createHash("sha256").update(JSON.stringify({source,account,epoch:connection.updatedAt})).digest("hex").slice(0,32)}let outcome;try{outcome=await supervisor.execute({requestId,stateDir:join(root,"sync-state",source,key),argv:[process.execPath,fileURLToPath(new URL("./connector-worker.js",import.meta.url)),resolve(root),fileURLToPath(new URL("../profiles/"+worker.profile,import.meta.url)),source],cwd:resolve(root),env:{ZORTEX_PROCESS_CODE_VERSION:"indra-v2/"+source+"@0.1.0+full-sync",...worker.provider==="local"?{ZORTEX_BROWSER_SOURCE:source,ZORTEX_BROWSER_READ_ROOT:browserRoot}:{},...options.bindingId?{ZORTEX_SELECTED_BINDING_ID:options.bindingId}:{},...options.grantId?{ZORTEX_SELECTED_GRANT_ID:options.grantId}:{},...options.scopeEpoch!==void 0?{ZORTEX_SELECTED_SCOPE_EPOCH:String(options.scopeEpoch)}:{},ZORTEX_SYNC_BUDGET_MS:String(SYNC_BUDGET_MS),ZORTEX_SYNC_USER_RETRY:options.userRetry?"1":"0"}},{...options.signal?{signal:options.signal}:{},runMs:SYNC_HARD_LIMIT_MS})}catch{return Original.errResult({code:"resource_exhausted",layer:"kernel",retryability:"transient",message:"Another sync of this source is running, or its previous worker was not confirmed stopped; try again later."})}let receipt;try{receipt=journal.readBusiness(outcome.runId)}catch(fault){await observation.admitted(outcome,null,options.bindingId);throw fault}await observation.admitted(outcome,receipt,options.bindingId);if(!outcome.cleanupConfirmed)return error("failed_precondition","Process cleanup remains unverified.","kernel");if(outcome.phase==="cancelled")return error("aborted","Sync was cancelled.");if(outcome.phase==="timed-out")return error("deadline_exceeded","Sync reached its execution limit; the next run resumes from the saved cursor.");if(!receipt||receipt.source!==source)return error("data_loss","Sync worker has no committed source business receipt.");if(!Original.isOk(receipt.result))return receipt.result;if(receipt.result.ok.error!==void 0){const fault=Original.validateStructuredError(receipt.result.ok.error);return Original.isOk(fault)?Original.errResult(fault.ok):error("data_loss","Invalid sync worker error.")}if(receipt.result.ok.ran===false&&receipt.result.ok.state==="RETRY_WAIT"&&typeof receipt.result.ok.skipped==="string")return Original.errResult({code:"unavailable",layer:"connector",retryability:"transient",message:`Sync is waiting to retry after an earlier provider failure; run it again later (${receipt.result.ok.skipped.slice(0,300)}).`});if(outcome.phase!=="completed"||receipt.result.ok.runFailed===true)return error("unavailable","Sync worker did not finish its source operation.");return Original.ok({...receipt.result.ok,executionId:outcome.runId,codeVersion:receipt.codeVersion,complete:receipt.result.ok.state==="IDLE"&&receipt.result.ok.stopped!==true})}async function observeSync(ctx,source,requestId,action){const run=()=>withFeedbackFlow(source,async()=>{const observation=createSyncObservation(ctx,source,requestId);const trace=createTraceRecorder(()=>ctx.get("zortexTelemetry"),source);await trace.step("read_started","started");try{const result=await action(observation);await observation.notAdmitted(result);const value=result;if(value.err)await trace.step("read_verified",value.err.code==="aborted"?"cancelled":"failed",{error:value.err.code==="deadline_exceeded"?"timeout":"provider"});else if(value.ok){await trace.step("read_verified",value.ok.complete===false?"unknown":"completed");const count=value.ok.appended;if(typeof count==="number"&&Number.isSafeInteger(count)&&count>=0&&count<=1e8)await trace.step("vault_saved","completed",{count})}else await trace.step("read_verified","unknown");return result}catch(error2){await observation.notAdmitted(void 0);await trace.step("read_verified","failed",{error:"unknown"});throw error2}});const feedback=ctx.get("zortexConnectionFeedback");return feedback?feedback.run(source,run):run()}export function runSupervisedChrome(ctx,root,requestId,options={}){return observeSync(ctx,"chrome-history",requestId,observation=>executeChrome(ctx,root,requestId,observation,options))}export function runSupervisedSource(ctx,root,source,requestId,options={}){return observeSync(ctx,source,requestId,observation=>executeWorkerSource(ctx,root,source,requestId,observation,options))}export const runSupervisedGoogle=runSupervisedSource;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{businessError}from"@zortexhq/plugin-connector-framework/api";export function selectedWorkerGoogleAuth(auth,source,bindingId){const denied=()=>businessError("permission_denied","Request is outside the selected worker account.","auth");return{...auth,request:(requested,url,options={})=>requested!==source||options.bindingId&&options.bindingId!==bindingId?Promise.resolve(denied()):auth.request(requested,url,{...options,bindingId}),requestRaw:(requested,url,options={})=>requested!==source||options.bindingId&&options.bindingId!==bindingId?Promise.resolve(denied()):auth.requestRaw(requested,url,{...options,bindingId})}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,cache,connectionState}from"@zortexhq/plugin-connector-core/api";import{createCalendarModules,createCalendarRead}from"./kit.js";import{createCalendarActions}from"./actions.js";const WINDOW_DAYS=[7,30,365],DAY_MS=864e5,BOUND_SLACK_MS=1e3,MAX_RFC3339_MS=0xe677d21fdbff;export function createCalendarProvider({parts,auth,vault,now=()=>new Date().toISOString()}){const kit=createCalendarModules(parts),info={source:"google-calendar",label:"Google Calendar",group:"Connector / Google",auth:"oauth-browser"},stop=new AbortController,pending=new Set;let closed=false;const readScope=scopes=>scopes.includes(kit.GOOGLE_CALENDAR_SCOPE)?kit.GOOGLE_CALENDAR_SCOPE:scopes.includes(kit.GOOGLE_CALENDAR_READONLY_SCOPE)?kit.GOOGLE_CALENDAR_READONLY_SCOPE:void 0;let refusedWindowMs=Number.POSITIVE_INFINITY;const failure=(code,message,layer="connector")=>businessError(code,message,layer);async function resolveGrant(){if(closed)return parts.connectorError("aborted","Calendar source is inactive","non-retryable");const connection=await vault.connection(info.source);if(!("ok"in connection))return"err"in connection?connection:parts.connectorError("data_loss","Calendar connection metadata was unconfirmed","non-retryable");if(!connection.ok||connection.ok.state!=="connected")return parts.connectorError("unauthenticated","Connect Google Calendar before reading","non-retryable");if(!connection.ok.accountId?.trim())return parts.connectorError("failed_precondition","Calendar requires custody-verified primary Calendar id; no account or grant-id fallback","non-retryable");const scope=readScope(connection.ok.scopes);if(!scope)return parts.connectorError("permission_denied","Calendar read authority is missing","non-retryable");if(closed)return parts.connectorError("aborted","Calendar source is inactive","non-retryable");return Original.ok({id:"0"+createHash("sha256").update(connection.ok.accountId).digest("hex").slice(0,25).toUpperCase(),source:info.source,account:connection.ok.accountId,scopes:[scope],expiresAt:new Date(Date.parse(now())+36e5).toISOString()})}async function fence(grant,signal){if(closed||signal.aborted)return parts.connectorError("aborted","Calendar operation was stopped","non-retryable");const current=await vault.connection(info.source);if(!("ok"in current))return"err"in current?current:parts.connectorError("data_loss","Calendar account fence was unconfirmed","non-retryable");if(closed||signal.aborted)return parts.connectorError("aborted","Calendar response arrived after cancellation","non-retryable");if(current.ok?.state!=="connected"||current.ok.accountId!==grant.account)return parts.connectorError("permission_denied","Calendar verified primary identity changed during the operation","non-retryable");const scope=readScope(current.ok.scopes);if(!scope||!grant.scopes.includes(scope))return parts.connectorError("permission_denied","Calendar read consent changed during the operation","non-retryable");return Original.ok(void 0)}function owned(task){const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled}async function run(grant,options,operation,updatedMin){grant=structuredClone(grant);const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(grant.source!==info.source||!grant.account?.trim())return parts.connectorError("permission_denied","Calendar grant is not bound to this source identity","non-retryable");if(!readScope(grant.scopes))return parts.connectorError("permission_denied","Calendar operation grant is missing read authority","non-retryable");const valid=await fence(grant,signal);if(!Original.isOk(valid))return valid;const talon={grant,execute:()=>parts.gateRefusal("Calendar synchronous provider I/O","Fixture oracle only; production uses public async custody"),executeAsync:async(_presented,request)=>{const before=await fence(grant,signal);if(!Original.isOk(before))return before;if(request.method!=="GET"||Object.keys(request.headers).some(key=>key.toLowerCase()==="authorization"))return parts.connectorError("permission_denied","Calendar custody accepts credential-free readonly requests only","non-retryable");const response=await auth.requestRaw("google-calendar",request.url,{method:"GET",signal}),after=await fence(grant,signal);if(!Original.isOk(after))return after;if(!("ok"in response))return"err"in response?response:parts.connectorError("data_loss","Calendar custody response was unconfirmed","non-retryable");return Original.ok({...response.ok,body:new TextEncoder().encode(response.ok.body)})},resolveAccountId:()=>Original.ok(grant.account),close:()=>Original.ok(void 0)};const built=createCalendarRead(parts,talon,updatedMin===void 0?{}:{updatedMin});if(!Original.isOk(built))return built;try{const result=await operation(built.ok.connector),after=await fence(grant,signal);return Original.isOk(after)?result:after}finally{built.ok.close()}}const unavailable={census:()=>parts.gateRefusal("Calendar synchronous census","Production provider is async; use discoverAsync"),calendars:()=>parts.gateRefusal("Calendar synchronous listing","Production provider is async; use pullAsync"),eventsPage:()=>parts.gateRefusal("Calendar synchronous events","Production provider is async; use pullAsync")};const oracle=kit.createGoogleCalendarConnector(unavailable);const connector={...oracle,discoverAsync:(grant,scope)=>owned(run(grant,{},inner=>inner.discoverAsync(grant,scope))),pullAsync:(grant,cursor,budget)=>owned(run(grant,{},inner=>inner.pullAsync(grant,cursor,budget)))};const provider={info,connector,actions:createCalendarActions(auth),resolveGrant,status:async()=>{if(closed)return failure("aborted","Calendar source is inactive");const state=await connectionState(vault,info);return"ok"in state?Original.ok({...state.ok,actions:true}):state},connect:options=>closed?Promise.resolve(failure("aborted","Calendar source is inactive")):auth.connect("google-calendar",options),job:id=>closed?failure("aborted","Calendar source is inactive"):auth.job(id),cancelJob:id=>auth.cancelJob(id),read(request,options={}){return owned((async()=>{const invalid=validateRead(request);if(invalid)return invalid;if(vault.guardedCache!=="atomic-connection")return failure("failed_precondition","Calendar read requires the public atomic connection-guarded cache port");const resolved=await resolveGrant();if(!Original.isOk(resolved))return resolved;const captured=await vault.connection(info.source);if(!("ok"in captured))return captured;if(captured.ok?.state!=="connected"||captured.ok.accountId!==resolved.ok.account)return failure("permission_denied","Calendar connection changed before the captured read","auth");const account=captured.ok.account,grant=resolved.ok,limit=request.limit??1,signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;async function select(from){const updatedMin=from!==void 0&&from-BOUND_SLACK_MS>=0&&from<=MAX_RFC3339_MS?new Date(from-BOUND_SLACK_MS).toISOString():void 0,records2=[];let cursor=null,scanned2=0,matched2=0;const seen=new Set;for(;;){const page=await run(grant,{signal},inner=>inner.pullAsync(grant,cursor),updatedMin);if(!Original.isOk(page))return page;scanned2+=page.ok.items.length;for(const item of page.ok.items){const proto=connector.normalize(item),fields=proto.payload!==null&&typeof proto.payload==="object"&&!Array.isArray(proto.payload)?proto.payload:{};if(request.query&&!(proto.body+"\n"+JSON.stringify(fields)).toLowerCase().includes(request.query.toLowerCase()))continue;if(request.since&&Date.parse(proto.ts)<Date.parse(request.since)||request.until&&Date.parse(proto.ts)>Date.parse(request.until))continue;if(from!==void 0&&Date.parse(proto.ts)<from)continue;const originalBody=proto.body??"",body=[originalBody,JSON.stringify(fields)].filter(Boolean).join("\n\n");matched2++;records2.push({source:info.source,sourceId:encodeURIComponent(grant.account)+":"+proto.nk.sourceId,stream:proto.nk.stream,kind:proto.kind,ts:proto.ts,body,fields:{...fields,originalBody}});records2.sort((a,b)=>(b.ts??"").localeCompare(a.ts??"")||(a.sourceId??"").localeCompare(b.sourceId??""));if(records2.length>limit)records2.length=limit}if(page.ok.exhausted)break;if(page.ok.next===null||seen.has(page.ok.next))return failure("data_loss","Calendar cursor made no progress; collection is incomplete");seen.add(page.ok.next);cursor=page.ok.next}return Original.ok({records:records2,scanned:scanned2,matched:matched2})}const refused=result2=>"err"in result2&&result2.err.code==="failed_precondition"&&result2.err.retryability==="retry-at-higher-level";const nowMs=Date.parse(now()),since=request.since===void 0?void 0:Date.parse(request.since),anchor=Math.min(nowMs,request.until===void 0?nowMs:Date.parse(request.until));const windows=Number.isFinite(anchor)?WINDOW_DAYS.map(days=>anchor-days*DAY_MS).filter(from=>from-BOUND_SLACK_MS>=0&&(since===void 0||from>since)):[];let chosen,windowFrom;for(const from of windows){if(nowMs-from>=refusedWindowMs)continue;const pass=await select(from);if(refused(pass)){refusedWindowMs=Math.min(refusedWindowMs,nowMs-from);break}if(!Original.isOk(pass))return pass;if(pass.ok.matched>=limit){chosen=pass.ok;windowFrom=from;break}}if(!chosen){let from=since!==void 0&&nowMs-since<refusedWindowMs?since:void 0,pass=await select(from);if(from!==void 0&&refused(pass)){refusedWindowMs=Math.min(refusedWindowMs,nowMs-from);from=void 0;pass=await select(void 0)}if(!Original.isOk(pass))return pass;chosen=pass.ok}const{records,scanned,matched}=chosen,warnings=windowFrom===void 0?[]:[`Calendar read covered only events updated since ${new Date(windowFrom).toISOString()}: that window already held the newest ${limit} match(es), so older events were not downloaded; scanned and matched count this window only.`];if(Buffer.byteLength(JSON.stringify(records))>2097152)return failure("resource_exhausted","Calendar query projection exceeds the 2 MiB response bound; no partial records were accepted");const valid=await fence(grant,signal);if(!Original.isOk(valid))return valid;const scope=readScope(grant.scopes);if(!scope)return failure("permission_denied","Calendar read authority disappeared","auth");const stored=await cache(vault,info.source,records,{source:info.source,account,accountId:grant.account,requiredScopes:[scope],signal});if(!("ok"in stored))return stored;const after=await fence(grant,signal);if(!Original.isOk(after))return after;const result=readResult(info.source,records,warnings);return"ok"in result?Original.ok({...result.ok,scanned,matched}):result})())},async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}};return provider}
|
|
1
|
+
import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,cache,connectionState}from"@zortexhq/plugin-connector-core/api";import{createCalendarModules,createCalendarRead}from"./kit.js";import{createCalendarActions}from"./actions.js";const WINDOW_DAYS=[7,30,365],DAY_MS=864e5,BOUND_SLACK_MS=1e3,MAX_RFC3339_MS=0xe677d21fdbff;export function createCalendarProvider({parts,auth,vault,now=()=>new Date().toISOString()}){const kit=createCalendarModules(parts),info={source:"google-calendar",label:"Google Calendar",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["events"],limitations:[]}},stop=new AbortController,pending=new Set;let closed=false;const readScope=scopes=>scopes.includes(kit.GOOGLE_CALENDAR_SCOPE)?kit.GOOGLE_CALENDAR_SCOPE:scopes.includes(kit.GOOGLE_CALENDAR_READONLY_SCOPE)?kit.GOOGLE_CALENDAR_READONLY_SCOPE:void 0;let refusedWindowMs=Number.POSITIVE_INFINITY;const failure=(code,message,layer="connector")=>businessError(code,message,layer);async function resolveGrant(){if(closed)return parts.connectorError("aborted","Calendar source is inactive","non-retryable");const connection=await vault.connection(info.source);if(!("ok"in connection))return"err"in connection?connection:parts.connectorError("data_loss","Calendar connection metadata was unconfirmed","non-retryable");if(!connection.ok||connection.ok.state!=="connected")return parts.connectorError("unauthenticated","Connect Google Calendar before reading","non-retryable");if(!connection.ok.accountId?.trim())return parts.connectorError("failed_precondition","Calendar requires custody-verified primary Calendar id; no account or grant-id fallback","non-retryable");const scope=readScope(connection.ok.scopes);if(!scope)return parts.connectorError("permission_denied","Calendar read authority is missing","non-retryable");if(closed)return parts.connectorError("aborted","Calendar source is inactive","non-retryable");return Original.ok({id:"0"+createHash("sha256").update(connection.ok.accountId).digest("hex").slice(0,25).toUpperCase(),source:info.source,account:connection.ok.accountId,scopes:[scope],expiresAt:new Date(Date.parse(now())+36e5).toISOString()})}async function fence(grant,signal){if(closed||signal.aborted)return parts.connectorError("aborted","Calendar operation was stopped","non-retryable");const current=await vault.connection(info.source);if(!("ok"in current))return"err"in current?current:parts.connectorError("data_loss","Calendar account fence was unconfirmed","non-retryable");if(closed||signal.aborted)return parts.connectorError("aborted","Calendar response arrived after cancellation","non-retryable");if(current.ok?.state!=="connected"||current.ok.accountId!==grant.account)return parts.connectorError("permission_denied","Calendar verified primary identity changed during the operation","non-retryable");const scope=readScope(current.ok.scopes);if(!scope||!grant.scopes.includes(scope))return parts.connectorError("permission_denied","Calendar read consent changed during the operation","non-retryable");return Original.ok(void 0)}function owned(task){const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled}async function run(grant,options,operation,updatedMin){grant=structuredClone(grant);const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(grant.source!==info.source||!grant.account?.trim())return parts.connectorError("permission_denied","Calendar grant is not bound to this source identity","non-retryable");if(!readScope(grant.scopes))return parts.connectorError("permission_denied","Calendar operation grant is missing read authority","non-retryable");const valid=await fence(grant,signal);if(!Original.isOk(valid))return valid;const talon={grant,execute:()=>parts.gateRefusal("Calendar synchronous provider I/O","Fixture oracle only; production uses public async custody"),executeAsync:async(_presented,request)=>{const before=await fence(grant,signal);if(!Original.isOk(before))return before;if(request.method!=="GET"||Object.keys(request.headers).some(key=>key.toLowerCase()==="authorization"))return parts.connectorError("permission_denied","Calendar custody accepts credential-free readonly requests only","non-retryable");const response=await auth.requestRaw("google-calendar",request.url,{method:"GET",signal}),after=await fence(grant,signal);if(!Original.isOk(after))return after;if(!("ok"in response))return"err"in response?response:parts.connectorError("data_loss","Calendar custody response was unconfirmed","non-retryable");return Original.ok({...response.ok,body:new TextEncoder().encode(response.ok.body)})},resolveAccountId:()=>Original.ok(grant.account),close:()=>Original.ok(void 0)};const built=createCalendarRead(parts,talon,updatedMin===void 0?{}:{updatedMin});if(!Original.isOk(built))return built;try{const result=await operation(built.ok.connector),after=await fence(grant,signal);return Original.isOk(after)?result:after}finally{built.ok.close()}}const unavailable={census:()=>parts.gateRefusal("Calendar synchronous census","Production provider is async; use discoverAsync"),calendars:()=>parts.gateRefusal("Calendar synchronous listing","Production provider is async; use pullAsync"),eventsPage:()=>parts.gateRefusal("Calendar synchronous events","Production provider is async; use pullAsync")};const oracle=kit.createGoogleCalendarConnector(unavailable);const connector={...oracle,discoverAsync:(grant,scope)=>owned(run(grant,{},inner=>inner.discoverAsync(grant,scope))),pullAsync:(grant,cursor,budget)=>owned(run(grant,{},inner=>inner.pullAsync(grant,cursor,budget)))};const provider={info,connector,actions:createCalendarActions(auth),resolveGrant,status:async()=>{if(closed)return failure("aborted","Calendar source is inactive");const state=await connectionState(vault,info);return"ok"in state?Original.ok({...state.ok,actions:true}):state},connect:options=>closed?Promise.resolve(failure("aborted","Calendar source is inactive")):auth.connect("google-calendar",options),job:id=>closed?failure("aborted","Calendar source is inactive"):auth.job(id),cancelJob:id=>auth.cancelJob(id),read(request,options={}){return owned((async()=>{const invalid=validateRead(request);if(invalid)return invalid;if(vault.guardedCache!=="atomic-connection")return failure("failed_precondition","Calendar read requires the public atomic connection-guarded cache port");const resolved=await resolveGrant();if(!Original.isOk(resolved))return resolved;const captured=await vault.connection(info.source);if(!("ok"in captured))return captured;if(captured.ok?.state!=="connected"||captured.ok.accountId!==resolved.ok.account)return failure("permission_denied","Calendar connection changed before the captured read","auth");const account=captured.ok.account,grant=resolved.ok,limit=request.limit??1,signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;async function select(from){const updatedMin=from!==void 0&&from-BOUND_SLACK_MS>=0&&from<=MAX_RFC3339_MS?new Date(from-BOUND_SLACK_MS).toISOString():void 0,records2=[];let cursor=null,scanned2=0,matched2=0;const seen=new Set;for(;;){const page=await run(grant,{signal},inner=>inner.pullAsync(grant,cursor),updatedMin);if(!Original.isOk(page))return page;scanned2+=page.ok.items.length;for(const item of page.ok.items){const proto=connector.normalize(item),fields=proto.payload!==null&&typeof proto.payload==="object"&&!Array.isArray(proto.payload)?proto.payload:{};if(request.query&&!(proto.body+"\n"+JSON.stringify(fields)).toLowerCase().includes(request.query.toLowerCase()))continue;if(request.since&&Date.parse(proto.ts)<Date.parse(request.since)||request.until&&Date.parse(proto.ts)>Date.parse(request.until))continue;if(from!==void 0&&Date.parse(proto.ts)<from)continue;const originalBody=proto.body??"",body=[originalBody,JSON.stringify(fields)].filter(Boolean).join("\n\n");matched2++;records2.push({source:info.source,sourceId:encodeURIComponent(grant.account)+":"+proto.nk.sourceId,stream:proto.nk.stream,kind:proto.kind,ts:proto.ts,body,fields:{...fields,originalBody}});records2.sort((a,b)=>(b.ts??"").localeCompare(a.ts??"")||(a.sourceId??"").localeCompare(b.sourceId??""));if(records2.length>limit)records2.length=limit}if(page.ok.exhausted)break;if(page.ok.next===null||seen.has(page.ok.next))return failure("data_loss","Calendar cursor made no progress; collection is incomplete");seen.add(page.ok.next);cursor=page.ok.next}return Original.ok({records:records2,scanned:scanned2,matched:matched2})}const refused=result2=>"err"in result2&&result2.err.code==="failed_precondition"&&result2.err.retryability==="retry-at-higher-level";const nowMs=Date.parse(now()),since=request.since===void 0?void 0:Date.parse(request.since),anchor=Math.min(nowMs,request.until===void 0?nowMs:Date.parse(request.until));const windows=Number.isFinite(anchor)?WINDOW_DAYS.map(days=>anchor-days*DAY_MS).filter(from=>from-BOUND_SLACK_MS>=0&&(since===void 0||from>since)):[];let chosen,windowFrom;for(const from of windows){if(nowMs-from>=refusedWindowMs)continue;const pass=await select(from);if(refused(pass)){refusedWindowMs=Math.min(refusedWindowMs,nowMs-from);break}if(!Original.isOk(pass))return pass;if(pass.ok.matched>=limit){chosen=pass.ok;windowFrom=from;break}}if(!chosen){let from=since!==void 0&&nowMs-since<refusedWindowMs?since:void 0,pass=await select(from);if(from!==void 0&&refused(pass)){refusedWindowMs=Math.min(refusedWindowMs,nowMs-from);from=void 0;pass=await select(void 0)}if(!Original.isOk(pass))return pass;chosen=pass.ok}const{records,scanned,matched}=chosen,warnings=windowFrom===void 0?[]:[`Calendar read covered only events updated since ${new Date(windowFrom).toISOString()}: that window already held the newest ${limit} match(es), so older events were not downloaded; scanned and matched count this window only.`];if(Buffer.byteLength(JSON.stringify(records))>2097152)return failure("resource_exhausted","Calendar query projection exceeds the 2 MiB response bound; no partial records were accepted");const valid=await fence(grant,signal);if(!Original.isOk(valid))return valid;const scope=readScope(grant.scopes);if(!scope)return failure("permission_denied","Calendar read authority disappeared","auth");const stored=await cache(vault,info.source,records,{source:info.source,account,accountId:grant.account,requiredScopes:[scope],signal});if(!("ok"in stored))return stored;const after=await fence(grant,signal);if(!Original.isOk(after))return after;const result=readResult(info.source,records,warnings);return"ok"in result?Original.ok({...result.ok,scanned,matched}):result})())},async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}};return provider}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createDriveActions}from"./actions.js";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{readResult,validateRead,connectionState}from"@zortexhq/plugin-connector-core/api";import{createHash}from"node:crypto";import{createOriginalDrive}from"./index.js";import{createDriveFileSnapshot}from"./file-snapshot.js";export const name="zortex-drive-content",inject=["zortexConnectorHub","zortexOriginalAuthoring","zortexGoogleAuth","zortexVaultStore"];export function createDriveProvider({parts,auth,vault,content}){const api=createOriginalDrive(parts),info={source:"google-drive",label:"Google Drive",group:"Connector / Google",auth:"oauth-browser",readById:true},stop=new AbortController;let closed=false;const pending=new Set;const mcp=vault.credential?createDriveActions(auth,vault):void 0;const service={info,...mcp?{actions:mcp.actions}:{},status:()=>connectionState(vault,info),connect:options=>auth.connect("google-drive",options),job:id=>auth.job(id),cancelJob:id=>auth.cancelJob(id),async read(request,options={}){if(closed)return businessError("unavailable","Drive source is inactive.","plugin");const invalid=validateRead(request,["fileId"]);if(invalid)return invalid;if(request.fileId!==void 0&&(!/^[A-Za-z0-9_-]{1,500}$/.test(request.fileId)||(request.limit??1)!==1||request.query!==void 0||request.since!==void 0||request.until!==void 0))return businessError("invalid_argument","Exact Drive file reads require one fileId without query or time filters.","plugin");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return businessError("aborted","Drive read was cancelled.","plugin");const selected=await vault.connection("google-drive");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return businessError("unauthenticated","Connect Google Drive before reading content.","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return businessError("failed_precondition","Select a verified native account before reading.","auth");const grant={id:"0"+createHash("sha256").update(selected.ok.accountId).digest("hex").slice(0,25).toUpperCase(),source:"google-drive",scopes:selected.ok.scopes,expiresAt:"2036-01-01T00:00:00.000Z"};const escape=v=>v.replaceAll("\\","\\\\").replaceAll("'","\\'");const query=["trashed = false",request.query?"fullText contains '"+escape(request.query)+"'":"",request.since?"modifiedTime >= '"+new Date(request.since).toISOString()+"'":"",request.until?"modifiedTime <= '"+new Date(request.until).toISOString()+"'":""].filter(Boolean).join(" and ");const client=api.DriveApiClient.create({authHeader:()=>Original.ok("opaque-host-custody"),query,capabilityPageSize:()=>request.limit??1,transportAsync:async req=>{const url=new URL(req.url);const exact=request.fileId!==void 0&&url.pathname==="/drive/v3/files";if(url.pathname==="/drive/v3/files"){if(exact){url.pathname+="/"+request.fileId;url.search="";url.searchParams.set("fields",api.DRIVE_FILE_FIELDS.slice("nextPageToken,files(".length,-1));url.searchParams.set("supportsAllDrives","true")}else url.searchParams.set("orderBy","modifiedTime desc")}const raw=await auth.requestRaw("google-drive",url.href,{signal});if(!("ok"in raw)){if(!("err"in raw))return{ok:false,error:"Raw Drive request returned an unconfirmed empty response."};const validated=Original.validateStructuredError(raw.err);return{ok:false,error:raw.err.message,...Original.isOk(validated)?{structuredError:validated.ok}:{}}}if(exact&&raw.ok.status===200){try{return{ok:true,...raw.ok,body:JSON.stringify({files:[JSON.parse(raw.ok.body)]})}}catch{return{ok:false,error:"Drive exact-file metadata was invalid JSON."}}}return{ok:true,...raw.ok}}});if(!Original.isOk(client))return client;const listing=await client.ok.listAsync(grant,null,request.limit??1);if(!Original.isOk(listing))return listing;const connector=api.createGoogleDriveConnector(client.ok),records=[],warnings=[];try{for(const metadata of listing.ok.files){if(closed||signal.aborted)return businessError("aborted","Drive read was stopped.","plugin");const plan=api.driveContentPlan(metadata);let enriched;let structured={};let exportFence;const reader=content?.();if(reader?.supports(metadata.mimeType??"")){const result=await reader.read({fileId:metadata.id,mimeType:metadata.mimeType,...typeof metadata.version==="string"?{expectedDriveVersion:metadata.version}:{}},{signal});if(!("ok"in result)){if(!("err"in result))return result;if(result.err.code==="resource_exhausted"&&result.err.layer==="plugin"&&result.err.retryability==="non-retryable"&&result.err.message==="Google response exceeds the 2097152-byte body I-7 return-guard limit."&&plan.kind==="export"&&["application/vnd.google-apps.document","application/vnd.google-apps.spreadsheet"].includes(metadata.mimeType??"")){if(!/^[A-Za-z0-9_-]{1,200}$/.test(metadata.id)||typeof metadata.version!=="string"||!/^\d{1,19}$/.test(metadata.version)||BigInt(metadata.version)>9223372036854775807n)return businessError("failed_precondition","Drive export recovery requires a valid listed file ID and int64 source version.","connector");exportFence=async()=>{if(closed||signal.aborted)return businessError("aborted","Drive export recovery was stopped.","plugin");const raw=await auth.requestRaw("google-drive","https://www.googleapis.com/drive/v3/files/"+encodeURIComponent(metadata.id)+"?fields=id,mimeType,version",{signal});if(closed||signal.aborted)return businessError("aborted","Drive export recovery was stopped.","plugin");if(!("ok"in raw))return raw;if(raw.ok.status!==200)return businessError("failed_precondition","Drive export version fence did not return confirmed metadata.","connector");let row;try{row=JSON.parse(raw.ok.body)}catch{return businessError("data_loss","Drive export version fence was invalid JSON.","connector")}if(!row||typeof row!=="object"||Array.isArray(row))return businessError("data_loss","Drive export version fence was invalid metadata.","connector");const value=row;if(value.id!==metadata.id||value.mimeType!==metadata.mimeType||value.version!==metadata.version)return businessError("aborted","Drive identity, MIME type or version changed around the export; no mixed snapshot was returned.","connector");return{ok:void 0}};structured={contentCoverage:{complete:false,representation:"original-export",versionVerified:true},contentVersion:metadata.version};warnings.push("Structured content for "+metadata.id+" exceeded the host body guard; returned a version-fenced original export. It does not certify all document tabs or complete structured metadata.")}else{if(result.err.code!=="failed_precondition"||result.err.layer!=="auth"||!/\bprotected\b/i.test(result.err.message))return result;warnings.push("Structured content for "+metadata.id+" carries protected authority; returned the original export.")}}else{enriched={...metadata,content:result.ok.body,contentBytes:Buffer.byteLength(result.ok.body),contentMime:result.ok.contentMime};structured={contentCoverage:result.ok.coverage,contentMetadata:result.ok.metadata,contentVersion:result.ok.version}}}if(enriched){}else if(plan.kind==="skip")enriched={...metadata,content:null,contentOmitted:plan.reason,...plan.bytes===void 0?{}:{contentBytes:plan.bytes}};else{if(exportFence){const checked=await exportFence();if(!("ok"in checked))return checked}const fetched=plan.kind==="export"?await client.ok.exportFileAsync(grant,metadata.id,plan.mime):await client.ok.downloadFileAsync(grant,metadata.id,metadata.mimeType??"");if("itemMediaQuota"in fetched)enriched={...metadata,content:null,contentOmitted:"quota"};else if(!Original.isOk(fetched))return fetched;else{const c=fetched.ok;enriched={...metadata,content:c.content,contentBytes:c.bytes,contentMime:c.mime,...c.sha256?{contentSha256:c.sha256}:{},...c.omitted?{contentOmitted:c.omitted}:{}}}if(exportFence){const checked=await exportFence();if(!("ok"in checked))return checked}}const proto=connector.normalize({streamRef:"file",raw:JSON.parse(JSON.stringify(enriched))});if(enriched.contentOmitted)warnings.push("Content for "+metadata.id+" is "+enriched.contentOmitted+"; metadata is not the file body.");if((!reader||exportFence)&&metadata.mimeType==="application/vnd.google-apps.spreadsheet")warnings.push("The original CSV export covers its exported tab. Enable the structured-content child to read all worksheets.");records.push({source:"google-drive",sourceId:metadata.id,stream:proto.nk.stream,kind:proto.kind,ts:proto.ts,body:enriched.content??proto.body??"",fields:{...enriched,...structured}})}}finally{connector.releaseNativeReadState()}if(closed||signal.aborted)return businessError("aborted","Drive read was stopped.","plugin");const current=await vault.connection("google-drive");if(!("ok"in current))return current;if(current.ok?.state!=="connected"||current.ok.account!==selected.ok.account||current.ok.accountId!==selected.ok.accountId||!selected.ok.scopes.every(scope=>current.ok.scopes.includes(scope)))return businessError("permission_denied","Drive authorization changed during the read.","auth");if(closed||signal.aborted)return businessError("aborted","Drive read was stopped.","plugin");if(listing.ok.nextPageToken)warnings.push("More files are available beyond this requested batch.");return readResult("google-drive",records,warnings)},async close(){closed=true;stop.abort()}};return{...service,read(request,options){if(pending.size)return Promise.resolve(businessError("resource_exhausted","This Drive provider has an active read.","plugin"));const task=service.read(request,options).finally(()=>pending.delete(task));pending.add(task);return task},async close(){closed=true;stop.abort();await Promise.allSettled([...pending]);await mcp?.close()}}}export function createDriveConnectorFileSnapshots(snapshot){return{async inspect(input,options){const result=await snapshot.inspect({fileId:input.id},options?.signal);return"ok"in result?{ok:{source:"google-drive",locator:result.ok.fileId,path:result.ok.path,mimeType:result.ok.mimeType,version:result.ok.version,modified:result.ok.modified,size:result.ok.size,opaque:result.ok}}:result},async materialize(file,options){const descriptor=file.opaque;if(!descriptor||typeof descriptor!=="object"||Array.isArray(descriptor))return businessError("invalid_argument","Drive file snapshot descriptor is missing.","plugin");const result=await snapshot.materialize(descriptor,options?.signal);return"ok"in result?{ok:{file,content:result.ok.content,mimeType:result.ok.mimeType,size:result.ok.size}}:result}}}export async function apply(ctx){const provider=createDriveProvider({parts:ctx.zortexOriginalAuthoring,auth:ctx.zortexGoogleAuth,vault:ctx.zortexVaultStore,content:()=>ctx.reflect.get("zortexDriveContent")}),snapshot=createDriveFileSnapshot({auth:ctx.zortexGoogleAuth});provider.fileSnapshots=createDriveConnectorFileSnapshots(snapshot);const withdraw=ctx.zortexConnectorHub.register(provider);ctx.provide("zortexDriveFileSnapshot",snapshot);return async()=>{withdraw();await Promise.all([provider.close(),snapshot.close()])}}
|
|
1
|
+
import{createDriveActions}from"./actions.js";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{readResult,validateRead,connectionState}from"@zortexhq/plugin-connector-core/api";import{createHash}from"node:crypto";import{createOriginalDrive}from"./index.js";import{createDriveFileSnapshot}from"./file-snapshot.js";export const name="zortex-drive-content",inject=["zortexConnectorHub","zortexOriginalAuthoring","zortexGoogleAuth","zortexVaultStore"];export function createDriveProvider({parts,auth,vault,content}){const api=createOriginalDrive(parts),info={source:"google-drive",label:"Google Drive",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["files","text"],limitations:["content_budgets"]},readById:true},stop=new AbortController;let closed=false;const pending=new Set;const mcp=vault.credential?createDriveActions(auth,vault):void 0;const service={info,...mcp?{actions:mcp.actions}:{},status:()=>connectionState(vault,info),connect:options=>auth.connect("google-drive",options),job:id=>auth.job(id),cancelJob:id=>auth.cancelJob(id),async read(request,options={}){if(closed)return businessError("unavailable","Drive source is inactive.","plugin");const invalid=validateRead(request,["fileId"]);if(invalid)return invalid;if(request.fileId!==void 0&&(!/^[A-Za-z0-9_-]{1,500}$/.test(request.fileId)||(request.limit??1)!==1||request.query!==void 0||request.since!==void 0||request.until!==void 0))return businessError("invalid_argument","Exact Drive file reads require one fileId without query or time filters.","plugin");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return businessError("aborted","Drive read was cancelled.","plugin");const selected=await vault.connection("google-drive");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return businessError("unauthenticated","Connect Google Drive before reading content.","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return businessError("failed_precondition","Select a verified native account before reading.","auth");const grant={id:"0"+createHash("sha256").update(selected.ok.accountId).digest("hex").slice(0,25).toUpperCase(),source:"google-drive",scopes:selected.ok.scopes,expiresAt:"2036-01-01T00:00:00.000Z"};const escape=v=>v.replaceAll("\\","\\\\").replaceAll("'","\\'");const query=["trashed = false",request.query?"fullText contains '"+escape(request.query)+"'":"",request.since?"modifiedTime >= '"+new Date(request.since).toISOString()+"'":"",request.until?"modifiedTime <= '"+new Date(request.until).toISOString()+"'":""].filter(Boolean).join(" and ");const client=api.DriveApiClient.create({authHeader:()=>Original.ok("opaque-host-custody"),query,capabilityPageSize:()=>request.limit??1,transportAsync:async req=>{const url=new URL(req.url);const exact=request.fileId!==void 0&&url.pathname==="/drive/v3/files";if(url.pathname==="/drive/v3/files"){if(exact){url.pathname+="/"+request.fileId;url.search="";url.searchParams.set("fields",api.DRIVE_FILE_FIELDS.slice("nextPageToken,files(".length,-1));url.searchParams.set("supportsAllDrives","true")}else url.searchParams.set("orderBy","modifiedTime desc")}const raw=await auth.requestRaw("google-drive",url.href,{signal});if(!("ok"in raw)){if(!("err"in raw))return{ok:false,error:"Raw Drive request returned an unconfirmed empty response."};const validated=Original.validateStructuredError(raw.err);return{ok:false,error:raw.err.message,...Original.isOk(validated)?{structuredError:validated.ok}:{}}}if(exact&&raw.ok.status===200){try{return{ok:true,...raw.ok,body:JSON.stringify({files:[JSON.parse(raw.ok.body)]})}}catch{return{ok:false,error:"Drive exact-file metadata was invalid JSON."}}}return{ok:true,...raw.ok}}});if(!Original.isOk(client))return client;const listing=await client.ok.listAsync(grant,null,request.limit??1);if(!Original.isOk(listing))return listing;const connector=api.createGoogleDriveConnector(client.ok),records=[],warnings=[];try{for(const metadata of listing.ok.files){if(closed||signal.aborted)return businessError("aborted","Drive read was stopped.","plugin");const plan=api.driveContentPlan(metadata);let enriched;let structured={};let exportFence;const reader=content?.();if(reader?.supports(metadata.mimeType??"")){const result=await reader.read({fileId:metadata.id,mimeType:metadata.mimeType,...typeof metadata.version==="string"?{expectedDriveVersion:metadata.version}:{}},{signal});if(!("ok"in result)){if(!("err"in result))return result;if(result.err.code==="resource_exhausted"&&result.err.layer==="plugin"&&result.err.retryability==="non-retryable"&&result.err.message==="Google response exceeds the 2097152-byte body I-7 return-guard limit."&&plan.kind==="export"&&["application/vnd.google-apps.document","application/vnd.google-apps.spreadsheet"].includes(metadata.mimeType??"")){if(!/^[A-Za-z0-9_-]{1,200}$/.test(metadata.id)||typeof metadata.version!=="string"||!/^\d{1,19}$/.test(metadata.version)||BigInt(metadata.version)>9223372036854775807n)return businessError("failed_precondition","Drive export recovery requires a valid listed file ID and int64 source version.","connector");exportFence=async()=>{if(closed||signal.aborted)return businessError("aborted","Drive export recovery was stopped.","plugin");const raw=await auth.requestRaw("google-drive","https://www.googleapis.com/drive/v3/files/"+encodeURIComponent(metadata.id)+"?fields=id,mimeType,version",{signal});if(closed||signal.aborted)return businessError("aborted","Drive export recovery was stopped.","plugin");if(!("ok"in raw))return raw;if(raw.ok.status!==200)return businessError("failed_precondition","Drive export version fence did not return confirmed metadata.","connector");let row;try{row=JSON.parse(raw.ok.body)}catch{return businessError("data_loss","Drive export version fence was invalid JSON.","connector")}if(!row||typeof row!=="object"||Array.isArray(row))return businessError("data_loss","Drive export version fence was invalid metadata.","connector");const value=row;if(value.id!==metadata.id||value.mimeType!==metadata.mimeType||value.version!==metadata.version)return businessError("aborted","Drive identity, MIME type or version changed around the export; no mixed snapshot was returned.","connector");return{ok:void 0}};structured={contentCoverage:{complete:false,representation:"original-export",versionVerified:true},contentVersion:metadata.version};warnings.push("Structured content for "+metadata.id+" exceeded the host body guard; returned a version-fenced original export. It does not certify all document tabs or complete structured metadata.")}else{if(result.err.code!=="failed_precondition"||result.err.layer!=="auth"||!/\bprotected\b/i.test(result.err.message))return result;warnings.push("Structured content for "+metadata.id+" carries protected authority; returned the original export.")}}else{enriched={...metadata,content:result.ok.body,contentBytes:Buffer.byteLength(result.ok.body),contentMime:result.ok.contentMime};structured={contentCoverage:result.ok.coverage,contentMetadata:result.ok.metadata,contentVersion:result.ok.version}}}if(enriched){}else if(plan.kind==="skip")enriched={...metadata,content:null,contentOmitted:plan.reason,...plan.bytes===void 0?{}:{contentBytes:plan.bytes}};else{if(exportFence){const checked=await exportFence();if(!("ok"in checked))return checked}const fetched=plan.kind==="export"?await client.ok.exportFileAsync(grant,metadata.id,plan.mime):await client.ok.downloadFileAsync(grant,metadata.id,metadata.mimeType??"");if("itemMediaQuota"in fetched)enriched={...metadata,content:null,contentOmitted:"quota"};else if(!Original.isOk(fetched))return fetched;else{const c=fetched.ok;enriched={...metadata,content:c.content,contentBytes:c.bytes,contentMime:c.mime,...c.sha256?{contentSha256:c.sha256}:{},...c.omitted?{contentOmitted:c.omitted}:{}}}if(exportFence){const checked=await exportFence();if(!("ok"in checked))return checked}}const proto=connector.normalize({streamRef:"file",raw:JSON.parse(JSON.stringify(enriched))});if(enriched.contentOmitted)warnings.push("Content for "+metadata.id+" is "+enriched.contentOmitted+"; metadata is not the file body.");if((!reader||exportFence)&&metadata.mimeType==="application/vnd.google-apps.spreadsheet")warnings.push("The original CSV export covers its exported tab. Enable the structured-content child to read all worksheets.");records.push({source:"google-drive",sourceId:metadata.id,stream:proto.nk.stream,kind:proto.kind,ts:proto.ts,body:enriched.content??proto.body??"",fields:{...enriched,...structured}})}}finally{connector.releaseNativeReadState()}if(closed||signal.aborted)return businessError("aborted","Drive read was stopped.","plugin");const current=await vault.connection("google-drive");if(!("ok"in current))return current;if(current.ok?.state!=="connected"||current.ok.account!==selected.ok.account||current.ok.accountId!==selected.ok.accountId||!selected.ok.scopes.every(scope=>current.ok.scopes.includes(scope)))return businessError("permission_denied","Drive authorization changed during the read.","auth");if(closed||signal.aborted)return businessError("aborted","Drive read was stopped.","plugin");if(listing.ok.nextPageToken)warnings.push("More files are available beyond this requested batch.");return readResult("google-drive",records,warnings)},async close(){closed=true;stop.abort()}};return{...service,read(request,options){if(pending.size)return Promise.resolve(businessError("resource_exhausted","This Drive provider has an active read.","plugin"));const task=service.read(request,options).finally(()=>pending.delete(task));pending.add(task);return task},async close(){closed=true;stop.abort();await Promise.allSettled([...pending]);await mcp?.close()}}}export function createDriveConnectorFileSnapshots(snapshot){return{async inspect(input,options){const result=await snapshot.inspect({fileId:input.id},options?.signal);return"ok"in result?{ok:{source:"google-drive",locator:result.ok.fileId,path:result.ok.path,mimeType:result.ok.mimeType,version:result.ok.version,modified:result.ok.modified,size:result.ok.size,opaque:result.ok}}:result},async materialize(file,options){const descriptor=file.opaque;if(!descriptor||typeof descriptor!=="object"||Array.isArray(descriptor))return businessError("invalid_argument","Drive file snapshot descriptor is missing.","plugin");const result=await snapshot.materialize(descriptor,options?.signal);return"ok"in result?{ok:{file,content:result.ok.content,mimeType:result.ok.mimeType,size:result.ok.size}}:result}}}export async function apply(ctx){const provider=createDriveProvider({parts:ctx.zortexOriginalAuthoring,auth:ctx.zortexGoogleAuth,vault:ctx.zortexVaultStore,content:()=>ctx.reflect.get("zortexDriveContent")}),snapshot=createDriveFileSnapshot({auth:ctx.zortexGoogleAuth});provider.fileSnapshots=createDriveConnectorFileSnapshots(snapshot);const withdraw=ctx.zortexConnectorHub.register(provider);ctx.provide("zortexDriveFileSnapshot",snapshot);return async()=>{withdraw();await Promise.all([provider.close(),snapshot.close()])}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{validateManifestV2}from"./api/index.js";import{ok}from"./original-contracts.js";import{connectorError}from"./errors.js";export function streamContextFor(manifest,stream){const decl=manifest.streams.find(s=>s.stream===stream);if(decl===void 0){return connectorError("invalid_argument",`undeclared stream '${stream}' in an emit \u2014 every emitted event belongs to a declared stream (connectors \xA72.1 lint)`)}return ok({revOrder:decl.revOrder,quality:decl.identity.quality})}export function streamDeclFor(manifest,stream){const decl=manifest.streams.find(s=>s.stream===stream);if(decl===void 0){return connectorError("invalid_argument",`undeclared stream '${stream}'`)}return ok(decl)}export function streamRegistrationsFor(manifest,comparators={}){return manifest.streams.map(s=>{const reg={source:manifest.source,stream:s.stream,revOrder:s.revOrder,quality:s.identity.quality};if(s.identity.noneIdentity!==void 0)reg.noneIdentity=s.identity.noneIdentity;if(s.revOrder==="upstream-version")reg.comparator=comparators[s.stream]??"numeric";return reg})}
|
|
1
|
+
export{validateManifestV2}from"./api/index.js";import{ok}from"./original-contracts.js";import{connectorError}from"./errors.js";export function streamContextFor(manifest,stream){const decl=manifest.streams.find(s=>s.stream===stream);if(decl===void 0){return connectorError("invalid_argument",`undeclared stream '${stream}' in an emit \u2014 every emitted event belongs to a declared stream (connectors \xA72.1 lint)`)}return ok({revOrder:decl.revOrder,quality:decl.identity.quality})}export function streamDeclFor(manifest,stream){const decl=manifest.streams.find(s=>s.stream===stream);if(decl===void 0){return connectorError("invalid_argument",`undeclared stream '${stream}'`)}return ok(decl)}export function streamRegistrationsFor(manifest,comparators={}){return manifest.streams.map(s=>{const reg={source:manifest.source,stream:s.stream,revOrder:s.revOrder,quality:s.identity.quality};if(s.deleteKind!==void 0)reg.deleteKind=s.deleteKind;if(s.identity.noneIdentity!==void 0)reg.noneIdentity=s.identity.noneIdentity;if(s.revOrder==="upstream-version")reg.comparator=comparators[s.stream]??"numeric";return reg})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Original,OriginalLog}from"./api/index.js";import{streamRegistrationsFor}from"./manifest.js";import{isAbsolute}from"node:path";import{SyncRunner}from"./runner.js";import{localEventLogAppendPortV1}from"./append-port.js";import{createOriginalAuthoring}from"./authoring.js";import{createOriginalProviderRead}from"./provider-read.js";import{createOriginalChromium}from"./chromium.js";export const name="zortex-original-sync",inject=["zortexOriginalEventLog"];const error=(code,message)=>Original.errResult({code,layer:"connector",retryability:"non-retryable",message});export function createOriginalSync(ctx,config={},storage){if(config.stateRoot!==void 0&&!isAbsolute(config.stateRoot))throw Error("Original sync stateRoot must be absolute.");const entries=new Map,pending=new Map,stops=new Set;let closed=false;const service={register(connector,resolveGrant){if(closed)throw Error("Original sync is inactive.");const source=connector.manifest.source;if(entries.has(source))throw Error("Duplicate original source registration.");if(storage?.declareStreams){const admitted=storage.declareStreams([...streamRegistrationsFor(connector.manifest),OriginalLog.SYNC_STREAM_REGISTRATION]);if(!Original.isOk(admitted))throw Error("Source stream authority was refused: "+("err"in admitted?admitted.err.code:"unconfirmed"))}const entry={connector,resolveGrant,active:true};entries.set(source,entry);return()=>{entry.active=false;if(entries.get(source)===entry)entries.delete(source)}},sources(){return[...entries.keys()].sort()},async run(source,options={}){const entry=entries.get(source);if(closed||!entry)return error("failed_precondition","Original connector source is not enabled.");if(pending.has(source))return error("resource_exhausted","This source already has an active sync.");if(options.signal?.aborted)return error("aborted","Sync was cancelled before it started.");const stop=new AbortController;stops.add(stop);const abort=()=>stop.abort();options.signal?.addEventListener("abort",abort,{once:true});const task=(async()=>{try{const grant=await entry.resolveGrant();if(!Original.isOk(grant))return grant;if(!entry.active||closed||stop.signal.aborted)return error("aborted","Source was disabled or sync was cancelled.");const base=storage?.appendPort??localEventLogAppendPortV1(ctx.zortexOriginalEventLog),port={...base,appendConnectorBatch:async(...args)=>entry.active&&!closed?base.appendConnectorBatch(...args):error("aborted","Source was disabled before append."),...base.appendConnectorBatchSync?{appendConnectorBatchSync:(...args)=>entry.active&&!closed?base.appendConnectorBatchSync(...args):error("aborted","Source was disabled before append.")}:{}};const runner=await SyncRunner.create({connector:entry.connector,appendPort:port,grant:grant.ok,...config.stateRoot?{stateRoot:config.stateRoot}:{},...storage?{startupFoldKeySalt:storage.identity}:{},stopRequested:()=>closed||!entry.active||stop.signal.aborted});if(!Original.isOk(runner))return runner;const asyncDiscover=entry.connector.discoverAsync!==void 0,asyncPull=entry.connector.pullAsync!==void 0;if(asyncDiscover!==asyncPull)return error("failed_precondition","Original source must declare both native async capabilities or neither.");const result=asyncDiscover?await runner.ok.runOnceAsync(options.trigger??"schedule"):runner.ok.runOnce(options.trigger??"schedule");return JSON.parse(JSON.stringify(result))}catch{return error("unavailable","Original connector sync did not finish.")}})();pending.set(source,task);try{return await task}finally{if(pending.get(source)===task)pending.delete(source);stops.delete(stop);options.signal?.removeEventListener("abort",abort)}},async close(){closed=true;for(const entry of entries.values())entry.active=false;entries.clear();for(const stop of stops)stop.abort();await Promise.allSettled([...pending.values()])}};return service}export async function apply(ctx,config={}){const service=createOriginalSync(ctx,config);ctx.reflect.provide("zortexOriginalSync",service);ctx.reflect.provide("zortexOriginalAuthoring",createOriginalAuthoring());ctx.reflect.provide("zortexOriginalProviderRead",createOriginalProviderRead());ctx.reflect.provide("zortexOriginalChromium",createOriginalChromium());return()=>service.close()}
|
|
1
|
+
import{Original,OriginalLog}from"./api/index.js";import{streamRegistrationsFor}from"./manifest.js";import{isAbsolute}from"node:path";import{SyncRunner}from"./runner.js";import{localEventLogAppendPortV1}from"./append-port.js";import{createOriginalAuthoring}from"./authoring.js";import{createOriginalProviderRead}from"./provider-read.js";import{createOriginalChromium}from"./chromium.js";export const name="zortex-original-sync",inject=["zortexOriginalEventLog"];const error=(code,message)=>Original.errResult({code,layer:"connector",retryability:"non-retryable",message});export function createOriginalSync(ctx,config={},storage){if(config.stateRoot!==void 0&&!isAbsolute(config.stateRoot))throw Error("Original sync stateRoot must be absolute.");const entries=new Map,pending=new Map,stops=new Set;let closed=false;const service={register(connector,resolveGrant){if(closed)throw Error("Original sync is inactive.");const source=connector.manifest.source;if(entries.has(source))throw Error("Duplicate original source registration.");if(storage?.declareStreams){const admitted=storage.declareStreams([...streamRegistrationsFor(connector.manifest),OriginalLog.SYNC_STREAM_REGISTRATION]);if(!Original.isOk(admitted))throw Error("Source stream authority was refused: "+("err"in admitted?admitted.err.code:"unconfirmed"))}const entry={connector,resolveGrant,active:true};entries.set(source,entry);return()=>{entry.active=false;if(entries.get(source)===entry)entries.delete(source)}},sources(){return[...entries.keys()].sort()},async run(source,options={}){const entry=entries.get(source);if(closed||!entry)return error("failed_precondition","Original connector source is not enabled.");if(pending.has(source))return error("resource_exhausted","This source already has an active sync.");if(options.signal?.aborted)return error("aborted","Sync was cancelled before it started.");const stop=new AbortController;stops.add(stop);const abort=()=>stop.abort();options.signal?.addEventListener("abort",abort,{once:true});const task=(async()=>{try{const grant=await entry.resolveGrant();if(!Original.isOk(grant))return grant;if(!entry.active||closed||stop.signal.aborted)return error("aborted","Source was disabled or sync was cancelled.");const base=storage?.appendPort??localEventLogAppendPortV1(ctx.zortexOriginalEventLog),port={...base,appendConnectorBatch:async(...args)=>entry.active&&!closed?base.appendConnectorBatch(...args):error("aborted","Source was disabled before append."),...base.appendConnectorBatchSync?{appendConnectorBatchSync:(...args)=>entry.active&&!closed?base.appendConnectorBatchSync(...args):error("aborted","Source was disabled before append.")}:{}};const runner=await SyncRunner.create({connector:entry.connector,appendPort:port,grant:grant.ok,...config.stateRoot?{stateRoot:config.stateRoot}:{},...storage?{startupFoldKeySalt:storage.identity}:{},stopRequested:()=>closed||!entry.active||stop.signal.aborted});if(!Original.isOk(runner))return runner;const asyncDiscover=entry.connector.discoverAsync!==void 0,asyncPull=entry.connector.pullAsync!==void 0;if(asyncDiscover!==asyncPull)return error("failed_precondition","Original source must declare both native async capabilities or neither.");if(options.userRetry&&runner.ok.machine.state==="ERRORED"){const retried=runner.ok.machine.userRetry();if(!Original.isOk(retried))return retried}const result=asyncDiscover?await runner.ok.runOnceAsync(options.trigger??"schedule"):runner.ok.runOnce(options.trigger??"schedule");return JSON.parse(JSON.stringify(result))}catch{return error("unavailable","Original connector sync did not finish.")}})();pending.set(source,task);try{return await task}finally{if(pending.get(source)===task)pending.delete(source);stops.delete(stop);options.signal?.removeEventListener("abort",abort)}},async close(){closed=true;for(const entry of entries.values())entry.active=false;entries.clear();for(const stop of stops)stop.abort();await Promise.allSettled([...pending.values()])}};return service}export async function apply(ctx,config={}){const service=createOriginalSync(ctx,config);ctx.reflect.provide("zortexOriginalSync",service);ctx.reflect.provide("zortexOriginalAuthoring",createOriginalAuthoring());ctx.reflect.provide("zortexOriginalProviderRead",createOriginalProviderRead());ctx.reflect.provide("zortexOriginalChromium",createOriginalChromium());return()=>service.close()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Original}from"@zortexhq/plugin-connector-framework/api";import{createOriginalGmail}from"./index.js";export const name="zortex-original-gmail-brokered",inject=["zortexOriginalAuthoring","zortexOriginalProviderRead","zortexOriginalSync"];export function createBrokeredGmail(parts,provider,config={}){const api=createOriginalGmail(parts);return provider.create({source:api.GMAIL_SOURCE,bounds:config.bounds??provider.defaultBounds,...config.talon?{talon:config.talon}:{},...config.lanes?{lanes:config.lanes}:{},build:bridge=>{const base=api.HttpGmailSource.create({transport:(url,headers,init)=>{const result=bridge.execute({method:init?.method??"GET",url,headers,...init?.body===void 0?{}:{body:init.body}});if(Original.isOk(result))return{ok:true,...result.ok};if(Original.isErr(result))return{ok:false,error:result.err.message,structuredError:result.err};return{ok:false,error:`credential talon returned empty (${result.empty.how})`}},authHeaders:grant=>bridge.authHeaders(grant),prefetch:requests=>bridge.prefetch(requests.map(r=>({method:r.method??"GET",url:r.url,headers:r.headers,...r.body===void 0?{}:{body:r.body}}))),pageSize:bridge.pageWidth(),...config.query===void 0?{}:{query:config.query},...config.messageFormat===void 0?{}:{messageFormat:config.messageFormat},...config.retrievalLimit===void 0?{}:{fetchAttachments:false}});return Original.ok(config.retrievalLimit===void 0?api.createGmailConnector(base):api.createGmailSelectedConnector(new api.StarterGmailSource(base,config.retrievalLimit)))}})}export async function apply(ctx,config={}){const session=createBrokeredGmail(ctx.zortexOriginalAuthoring,ctx.zortexOriginalProviderRead,config);if(!Original.isOk(session))throw Error("Original Gmail request bridge could not be admitted.");let withdraw;try{withdraw=ctx.zortexOriginalSync.register(session.ok.connector,async()=>config.talon?Original.ok(config.talon.grant):Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Gmail has no credential custody session; use the Connector connection flow."}))}catch(error){session.ok.close();throw error}return()=>{withdraw();session.ok.close()}}
|
|
1
|
+
import{Original}from"@zortexhq/plugin-connector-framework/api";import{createOriginalGmail}from"./index.js";export const name="zortex-original-gmail-brokered",inject=["zortexOriginalAuthoring","zortexOriginalProviderRead","zortexOriginalSync"];export function createBrokeredGmail(parts,provider,config={}){const api=createOriginalGmail(parts);return provider.create({source:api.GMAIL_SOURCE,bounds:config.bounds??provider.defaultBounds,...config.talon?{talon:config.talon}:{},...config.lanes?{lanes:config.lanes}:{},build:bridge=>{const base=api.HttpGmailSource.create({transport:(url,headers,init)=>{const result=bridge.execute({method:init?.method??"GET",url,headers,...init?.body===void 0?{}:{body:init.body}});if(Original.isOk(result))return{ok:true,...result.ok};if(Original.isErr(result))return{ok:false,error:result.err.message,structuredError:result.err};return{ok:false,error:`credential talon returned empty (${result.empty.how})`}},authHeaders:grant=>bridge.authHeaders(grant),prefetch:requests=>bridge.prefetch(requests.map(r=>({method:r.method??"GET",url:r.url,headers:r.headers,...r.body===void 0?{}:{body:r.body}}))),pageSize:bridge.pageWidth(),...config.query===void 0?{}:{query:config.query},...config.selectedMessageIds===void 0?{}:{selectedMessageIds:config.selectedMessageIds},...config.messageFormat===void 0?{}:{messageFormat:config.messageFormat},...config.retrievalLimit===void 0?{}:{fetchAttachments:false}});return Original.ok(config.retrievalLimit===void 0?api.createGmailConnector(base):api.createGmailSelectedConnector(new api.StarterGmailSource(base,config.retrievalLimit)))}})}export async function apply(ctx,config={}){const session=createBrokeredGmail(ctx.zortexOriginalAuthoring,ctx.zortexOriginalProviderRead,config);if(!Original.isOk(session))throw Error("Original Gmail request bridge could not be admitted.");let withdraw;try{withdraw=ctx.zortexOriginalSync.register(session.ok.connector,async()=>config.talon?Original.ok(config.talon.grant):Original.errResult({code:"unauthenticated",layer:"auth",retryability:"non-retryable",message:"Gmail has no credential custody session; use the Connector connection flow."}))}catch(error){session.ok.close();throw error}return()=>{withdraw();session.ok.close()}}
|