@zortexhq/indra-v2.5 0.2.7 → 0.3.0
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 +11 -4
- package/bin/codex-postinstall.mjs +1 -1
- package/dist/auto-sync.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/codex-install.js +1 -1
- package/dist/codex-setup.js +1 -1
- package/dist/connector-worker.js +1 -1
- package/dist/content-find.js +2 -2
- package/dist/find-snapshots.js +1 -0
- package/dist/gateway.js +1 -1
- package/dist/imessage-sync.js +1 -0
- package/dist/local-cloud-policy.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mail-search-body.js +1 -0
- package/dist/match-excerpt.js +1 -0
- package/dist/mcp.js +1 -1
- package/dist/native-connect.js +1 -0
- package/dist/native-level1-setup.js +1 -1
- package/dist/public-tool.js +1 -1
- package/dist/read-route.js +1 -0
- package/dist/recovery-support.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/sync-sources.js +1 -0
- 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-computer-files/dist/catalog.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/index.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/policy.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/result.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-computer-files/package.json +18 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/native-file-roots.js +1 -0
- 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-google-tasks/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-history/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/attributed-body.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/chatdb-source.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/connector.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/index.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/manifest.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/dist/sqlite-snapshot.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-imessage/package.json +16 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/api/index.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/computer-files-pages.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/computer-files.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/sources.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/package.json +5 -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-galaxy-ui/dist/file-catalog.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-renderer.js +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/galaxy-text.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/snapshot.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/package.json +1 -0
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/galaxy-renderer.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/live-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/portrait-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
- package/node_modules/@zortexhq/plugin-google-auth/default-client.json +1 -0
- package/node_modules/@zortexhq/plugin-google-auth/dist/desktop-client.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/search-text.js +1 -0
- 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 +19 -2
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -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 +11 -7
- package/release-provenance.json +45 -31
- package/update-manifest.json +380 -164
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{SYNC_WORKERS as WORKERS}from"./sync-sources.js";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{imessageNativeIdentity}from"./imessage-sync.js";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})}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=source==="imessage"?"indra-level1-connectors":"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(source==="imessage"){if(!sourceActive(ctx,source))return error("unavailable","The iMessage connector is disabled.","plugin");if(options.bindingId)return error("invalid_argument","iMessage sync uses the signed-in macOS user.");const native=await imessageNativeIdentity();if(!Original.isOk(native))return native;key=native.ok.key}else 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
|
+
export const SYNC_WORKERS={gmail:{provider:"google",profile:"google-worker.yml"},"google-drive":{provider:"google",profile:"google-worker.yml"},"google-tasks":{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"},imessage:{provider:"macos-messages",profile:"account-worker.yml"},"google-chrome":{provider:"local",profile:"browser-worker.yml"},"microsoft-edge":{provider:"local",profile:"browser-worker.yml"}};
|
|
@@ -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}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash,randomUUID}from"node:crypto";import{constants}from"node:fs";import{lstat,open,opendir,realpath,stat}from"node:fs/promises";import{dirname,extname,isAbsolute,join,relative,resolve}from"node:path";import{homedir}from"node:os";import{budgets as validateBudgets,defaultComputerFileRoots,excludedDirectory,isExcludedFile,isProject,noSymlinkComponents,roots as validateRoots,within}from"./policy.js";import{fail,ok,Refused,requireOk}from"./result.js";const SOURCE="computer-files",NAMESPACE="computer-files.catalog",PAGE=128,RESPONSE_BYTES=256*1024,LEASE="0:lease",STATUS="0:status",CONTROL="0:control";const hash=text=>createHash("sha256").update(text).digest("hex");const json=value=>value;const bytes=value=>Buffer.byteLength(JSON.stringify(value));const object=value=>!!value&&typeof value==="object"&&!Array.isArray(value);const code=error=>error?.code;const problem=error=>error instanceof Refused?error.result:fail(code(error)==="EACCES"||code(error)==="EPERM"?"permission_denied":code(error)==="ENOENT"||code(error)==="ENOTDIR"?"not_found":code(error)==="ELOOP"?"permission_denied":"unavailable","Computer Files could not complete the selected local operation.");const file=row2=>({id:row2.id,rootId:row2.rootId,relativePath:row2.relativePath,name:row2.name,extension:row2.extension,size:row2.size,modifiedAt:row2.modifiedAt,observedAt:row2.observedAt,version:row2.version});const version=s=>`${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}:${s.ctimeMs}`;function row(value){return object(value)&&value.kind==="file"&&typeof value.id==="string"&&/^[a-f0-9]{64}$/.test(value.id)&&typeof value.scope==="string"&&typeof value.rootPath==="string"&&typeof value.relativePath==="string"&&typeof value.rootId==="string"&&typeof value.name==="string"&&typeof value.extension==="string"&&typeof value.modifiedAt==="string"&&typeof value.observedAt==="string"&&typeof value.version==="string"&&typeof value.generation==="string"&&typeof value.device==="string"&&typeof value.inode==="string"&&typeof value.size==="number"&&Number.isSafeInteger(value.size)&&value.size>=0}export async function createComputerFiles(deps){const home=resolve(deps.home??homedir()),limits=validateBudgets(deps.budgets),now=deps.now??(()=>new Date);const paths=validateRoots(deps.roots??await defaultComputerFileRoots(home),home);const selected=paths.map(path=>({id:hash(path),path}));const excludes=validateRoots(deps.excludeRoots??[],home);if(isAbsolute(deps.vault.identity))excludes.push(resolve(deps.vault.identity));const scope=hash(JSON.stringify({paths,excludes,maxDepth:limits.maxDepth,policy:1}));const store=deps.vault.createPrivateStore(NAMESPACE);if(!store.delete)throw Error("Computer Files requires revision-fenced private-store deletion.");const owner=randomUUID(),stop=new AbortController,jobs=new Map;let closed=false,running,reading=0;const reads=new Set;let snapshot={source:SOURCE,state:"unavailable",enabled:false,roots:selected.map(r=>({...r,state:"pending"})),catalogItems:0,metadataBytes:0,partial:true,reasons:["not_scanned"],scannedEntries:0,scannedDirectories:0,skipped:0,lastScanAt:null,lastCompleteAt:null,limits,storage:"metadata-only",fileContentsStored:false};let statusRevision=0;function refreshSnapshot(){if(running)return;const saved=requireOk(store.get(STATUS));if(!saved||saved.revision<=statusRevision||!object(saved.value)||saved.value.scope!==scope||!object(saved.value.status))return;const prior=saved.value.status;if(!Number.isSafeInteger(prior.catalogItems)||Number(prior.catalogItems)<0||!Number.isSafeInteger(prior.metadataBytes)||Number(prior.metadataBytes)<0)return;const validDate=value=>typeof value==="string"&&Number.isFinite(Date.parse(value))?value:null;const count=value=>typeof value==="number"&&Number.isSafeInteger(value)&&value>=0?value:0;const savedRoots=Array.isArray(prior.roots)?prior.roots:[];const rootStates=selected.map(root=>{const found=savedRoots.find(value=>object(value)&&value.id===root.id),state2=object(found)&&["pending","complete","partial","unavailable"].includes(String(found.state))?found.state:"pending";return{...root,state:state2}});const state=["ready","partial","unavailable"].includes(String(prior.state))?prior.state:"partial";snapshot={...snapshot,catalogItems:Number(prior.catalogItems),metadataBytes:Number(prior.metadataBytes),lastScanAt:validDate(prior.lastScanAt),lastCompleteAt:validDate(prior.lastCompleteAt),state,roots:rootStates,partial:prior.partial!==false,reasons:Array.isArray(prior.reasons)?prior.reasons.filter(value=>typeof value==="string"&&value.length<=64).slice(0,16):["refresh_pending"],scannedEntries:count(prior.scannedEntries),scannedDirectories:count(prior.scannedDirectories),skipped:count(prior.skipped)};statusRevision=saved.revision}refreshSnapshot();function access(){if(closed||stop.signal.aborted)throw new Refused(fail("unavailable","Computer Files is inactive."));const preference=requireOk(store.get(CONTROL));if(preference&&object(preference.value)&&preference.value.enabled===false)throw new Refused(fail("permission_denied","The file catalog is paused. Resume it to read these folders."));return String(preference?.revision??0)}function guard(authority,signal){if(signal?.aborted)throw new Refused(fail("aborted","Computer Files operation was cancelled."));if(access()!==authority)throw new Refused(fail("permission_denied","Computer Files permission changed during the operation."))}function statusRaw(){try{refreshSnapshot();const control=requireOk(store.get(CONTROL)),paused=!!control&&object(control.value)&&control.value.enabled===false,enabled=!paused&&!closed,lease=requireOk(store.get(LEASE)),scanning=!!running||!!lease&&object(lease.value)&&lease.value.scope===scope&&Number(lease.value.expiresAt)>now().getTime();return ok({...snapshot,enabled,partial:snapshot.partial||scanning,state:closed?"unavailable":paused?"paused":scanning?"scanning":snapshot.state,limits,roots:snapshot.roots.map(r=>({...r}))})}catch(error){return problem(error)}}const excluded=path=>excludes.some(root=>within(root,path));function current(value){return row(value)&&value.scope===scope&&selected.some(root=>root.id===value.rootId&&root.path===value.rootPath)&&within(value.rootPath,resolve(value.rootPath,value.relativePath))&&!excluded(resolve(value.rootPath,value.relativePath))}function leaseCurrent(lease,authority,signal){guard(authority,signal);const found=requireOk(store.get(LEASE));if(!found||found.revision!==lease.guard.revision||!object(found.value)||found.value.owner!==owner||Number(found.value.expiresAt)<=now().getTime())throw new Refused(fail("aborted","Another file scan owns the current catalog generation."))}function acquire(){const prior=requireOk(store.get(LEASE));if(prior&&object(prior.value)&&typeof prior.value.expiresAt==="number"&&prior.value.expiresAt>now().getTime())return null;const value={owner,scope,expiresAt:now().getTime()+limits.scanMs+3e4};const saved=store.put(LEASE,json(value),prior?.revision??0);if("err"in saved&&saved.err.code==="aborted")return null;const receipt=requireOk(saved);return{value,guard:{key:LEASE,revision:receipt.revision}}}function*pages(){let after,seen=0;do{const page=requireOk(store.listPage({limit:PAGE,...after?{after}:{}}));for(const item of page.items){if(++seen>100010)throw new Refused(fail("resource_exhausted","Computer Files catalog exceeded its recovery bound."));yield item}after=page.next}while(after)}function remove(item,lease){requireOk(store.delete(item.key,item.revision,lease.guard))}async function recount(lease,authority,native,signal){let count=0,total=0,visited=0;for(const item of pages()){if(visited++%PAGE===0)requireOk(await native.check(signal));leaseCurrent(lease,authority,signal);if(!item.key.startsWith("f:"))continue;const size=bytes(item.value);if(!current(item.value)||count>=limits.maxFiles||size>limits.maxRecordBytes||total+size>limits.maxMetadataBytes){remove(item,lease);continue}count++;total+=size}snapshot={...snapshot,catalogItems:count,metadataBytes:total}}function putFile(next,lease,authority,signal){leaseCurrent(lease,authority,signal);const key="f:"+next.id,prior=requireOk(store.get(key)),size=bytes(next),old=prior?bytes(prior.value):0;if(size>limits.maxRecordBytes||!prior&&snapshot.catalogItems>=limits.maxFiles||snapshot.metadataBytes-old+size>limits.maxMetadataBytes)return false;requireOk(store.put(key,json(next),prior?.revision??0,lease.guard));snapshot={...snapshot,catalogItems:snapshot.catalogItems+(prior?0:1),metadataBytes:snapshot.metadataBytes-old+size};return true}async function runScan(signal){let lease,authority="";try{authority=access();const native=requireOk(await deps.authorize(signal));requireOk(await native.check(signal));guard(authority,signal);const captured=acquire();if(!captured)return ok({...requireOk(statusRaw()),state:"scanning",partial:true,reasons:["scan_in_progress"]});lease=captured;await recount(lease,authority,native,signal);const generation=randomUUID(),started=performance.now(),reasons=new Set,rootStates=[];let entries=0,directories=0,skipped=0;const check=async()=>{requireOk(await native.check(signal));leaseCurrent(lease,authority,signal);if(performance.now()-started>=limits.scanMs){reasons.add("time_limit");throw new Refused(fail("resource_exhausted","Computer Files scan reached its time limit."))}};const rootPathCheck=async root=>{await check();await noSymlinkComponents(root.path);await check();const value=await lstat(root.path);await check();if(!value.isDirectory()||value.isSymbolicLink()||excluded(root.path))throw Object.assign(Error("Selected root is not accessible."),{code:"EACCES"});return value};for(const root of selected){let rootState="complete",complete=true,rootStat;try{rootStat=await rootPathCheck(root);async function visit(directory,depth){await check();if(directories>=limits.maxDirectories){reasons.add("directory_limit");throw new Refused(fail("resource_exhausted","Computer Files reached its directory limit."))}directories++;await noSymlinkComponents(directory);const canonicalDirectory=await realpath(directory),directoryStat=await lstat(directory);await check();if(canonicalDirectory!==directory||!within(root.path,canonicalDirectory)||!directoryStat.isDirectory()||directoryStat.isSymbolicLink()||directoryStat.dev!==rootStat.dev)throw Object.assign(Error("Directory moved outside the selected scope."),{code:"ELOOP"});const project=await isProject(directory);await check();const dir=await opendir(directory,{bufferSize:32});try{await noSymlinkComponents(directory);const openedPath=await realpath(directory),openedStat=await lstat(directory);await check();if(openedPath!==canonicalDirectory||openedStat.dev!==directoryStat.dev||openedStat.ino!==directoryStat.ino)throw Object.assign(Error("Directory changed while opening."),{code:"ELOOP"});for await(const entry of dir){await check();if(entries>=limits.maxEntries){reasons.add("entry_limit");throw new Refused(fail("resource_exhausted","Computer Files reached its visited-entry limit."))}entries++;const path=join(directory,entry.name);if(excluded(path)||entry.isSymbolicLink()||!entry.isDirectory()&&!entry.isFile()){skipped++;continue}if(entry.isDirectory()){if(excludedDirectory(entry.name,project,directory===home)){skipped++;continue}if(depth>=limits.maxDepth){complete=false;reasons.add("depth_limit");skipped++;continue}try{const info2=await lstat(path);await check();if(info2.isSymbolicLink()||!info2.isDirectory()||info2.dev!==rootStat.dev){skipped++;continue}await visit(path,depth+1)}catch(error){if(error instanceof Refused)throw error;complete=false;reasons.add(code(error)==="EACCES"||code(error)==="EPERM"?"permission_unavailable":"directory_unavailable")}continue}if(isExcludedFile(entry.name)){skipped++;continue}try{await noSymlinkComponents(path);const canonical=await realpath(path),info2=await lstat(path);await check();if(canonical!==path||!within(root.path,canonical)||excluded(canonical)){complete=false;reasons.add("path_changed");continue}if(!info2.isFile()||info2.isSymbolicLink()||!Number.isSafeInteger(info2.size)||info2.size<0){skipped++;continue}const rel=relative(root.path,path),next={kind:"file",scope,rootPath:root.path,generation,id:hash(root.id+"\0"+rel),rootId:root.id,relativePath:rel,name:entry.name,extension:extname(entry.name).toLowerCase(),size:info2.size,modifiedAt:info2.mtime.toISOString(),observedAt:now().toISOString(),version:version(info2),device:String(info2.dev),inode:String(info2.ino)};await noSymlinkComponents(path);const finalPath=await realpath(path),finalInfo=await lstat(path);await check();if(finalPath!==canonical||finalInfo.dev!==info2.dev||finalInfo.ino!==info2.ino||version(finalInfo)!==version(info2)){complete=false;reasons.add("path_changed");continue}if(!putFile(next,lease,authority,signal)){reasons.add(bytes(next)>limits.maxRecordBytes?"metadata_record_limit":snapshot.catalogItems>=limits.maxFiles?"catalog_limit":"metadata_limit");skipped++}}catch(error){if(error instanceof Refused)throw error;complete=false;reasons.add("file_unavailable")}}}finally{await dir.close().catch(()=>void 0)}}await visit(root.path,0);await check();const after=await rootPathCheck(root);if(after.dev!==rootStat.dev||after.ino!==rootStat.ino){complete=false;reasons.add("root_changed")}if(complete){for(const item of pages())if(current(item.value)&&item.value.rootId===root.id&&item.value.generation!==generation){await check();const oldPath=resolve(root.path,item.value.relativePath);try{await lstat(oldPath);await check()}catch(error){if(error instanceof Refused)throw error;if(code(error)!=="ENOENT"&&code(error)!=="ENOTDIR"){complete=false;reasons.add("file_unavailable");continue}const alive=await rootPathCheck(root);if(alive.dev!==rootStat.dev||alive.ino!==rootStat.ino){complete=false;reasons.add("root_changed");break}await check();remove(item,lease);snapshot={...snapshot,catalogItems:snapshot.catalogItems-1,metadataBytes:snapshot.metadataBytes-bytes(item.value)}}}}if(!complete)rootState="partial"}catch(error){complete=false;rootState=rootStat?"partial":"unavailable";if(error instanceof Refused){if(error.result.err.code!=="resource_exhausted")throw error;rootState="partial";reasons.add("scan_limit")}else reasons.add(code(error)==="EACCES"||code(error)==="EPERM"||code(error)==="ELOOP"?"permission_unavailable":"root_unavailable")}rootStates.push({...root,state:rootState});snapshot={...snapshot,scannedEntries:entries,scannedDirectories:directories,skipped};if(reasons.has("time_limit")||reasons.has("entry_limit")||reasons.has("directory_limit"))break}for(const root of selected)if(!rootStates.some(found=>found.id===root.id))rootStates.push({...root,state:"partial"});const unavailable=!rootStates.length||rootStates.every(root=>root.state==="unavailable"),partial=reasons.size>0||rootStates.some(root=>root.state!=="complete");if(!selected.length)reasons.add("no_folders");snapshot={...snapshot,state:unavailable?"unavailable":partial?"partial":"ready",enabled:true,roots:rootStates,partial:partial||unavailable,reasons:[...reasons],scannedEntries:entries,scannedDirectories:directories,skipped,lastScanAt:now().toISOString(),lastCompleteAt:!partial&&!unavailable?now().toISOString():snapshot.lastCompleteAt};requireOk(await native.check(signal));leaseCurrent(lease,authority,signal);const prior=requireOk(store.get(STATUS));statusRevision=requireOk(store.put(STATUS,json({scope,status:snapshot}),prior?.revision??0,lease.guard)).revision;return ok({...snapshot})}catch(error){snapshot={...snapshot,state:"partial",partial:true,reasons:[error instanceof Refused?error.result.err.code==="aborted"?"cancelled":error.result.err.code==="permission_denied"?"permission_changed":error.result.err.code==="resource_exhausted"?"resource_limit":"scan_failed":"scan_failed"]};return problem(error)}finally{if(lease){try{const currentLease=requireOk(store.get(LEASE));if(currentLease?.revision===lease.guard.revision)store.put(LEASE,json({...lease.value,expiresAt:0}),lease.guard.revision,lease.guard)}catch{}}}}function scan(options={}){if(options.signal?.aborted)return Promise.resolve(fail("aborted","Computer Files scan was cancelled."));if(running)return running;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;running=runScan(signal).finally(()=>{running=void 0});return running}function listRaw(input={}){try{refreshSnapshot();const authority=access(),limit=input.limit??50;if(!Number.isSafeInteger(limit)||limit<1||limit>PAGE||input.query!==void 0&&(typeof input.query!=="string"||input.query.length>256)||input.cursor!==void 0&&!/^f:[a-f0-9]{64}$/.test(input.cursor))return fail("invalid_argument","Choose a bounded file page, query and catalog cursor.");const query=input.query?.trim().toLocaleLowerCase(),items=[];let after=input.cursor,scanned=0,visited=0,total=0,next;outer:do{const page=requireOk(store.listPage({limit:PAGE,...after?{after}:{}}));for(const item of page.items){guard(authority);if(++visited>100010)throw new Refused(fail("resource_exhausted","File search reached the catalog recovery bound."));after=item.key;if(!current(item.value))continue;scanned++;if(query&&!item.value.relativePath.toLocaleLowerCase().includes(query))continue;const value=file(item.value),size=bytes(value);if(items.length>=limit||total+size>RESPONSE_BYTES){next=items.length?"f:"+items.at(-1).id:input.cursor;break outer}items.push(value);total+=size}after=page.next;if(after&&items.length>=limit){next=after;break}}while(after&&scanned<=limits.maxFiles);guard(authority);return ok({items,...next?{next}:{},catalogItems:snapshot.catalogItems,partial:snapshot.partial,scanned})}catch(error){return problem(error)}}function graphRaw(input={}){const limit=input.limit??1e3;if(!Number.isSafeInteger(limit)||limit<1||limit>1e3)return fail("invalid_argument","File graph samples contain 1\u20131000 references.");const s=statusRaw();if(!("ok"in s))return s;if(!s.ok.enabled||s.ok.state==="unavailable")return ok({source:SOURCE,state:s.ok.state,catalogItems:0,partial:s.ok.partial,records:[]});try{const authority=access(),records=[];for(const item of pages()){guard(authority);if(!current(item.value))continue;records.push({id:item.value.id,modifiedAt:item.value.modifiedAt,observedAt:item.value.observedAt,rootId:item.value.rootId,parentId:hash(item.value.rootId+"\0"+dirname(item.value.relativePath))});if(records.length>=limit)break}guard(authority);return ok({source:SOURCE,state:s.ok.state,catalogItems:Math.max(s.ok.catalogItems,records.length),partial:s.ok.partial||s.ok.catalogItems>records.length,records})}catch(error){return problem(error)}}async function read(input){let handle;try{const authority=access(),signal=input.signal?AbortSignal.any([input.signal,stop.signal]):stop.signal,maxBytes=input.maxBytes??Math.min(256*1024,limits.maxReadBytes),format=input.format??"text";if(!/^[a-f0-9]{64}$/.test(input.id)||!Number.isSafeInteger(maxBytes)||maxBytes<1||maxBytes>limits.maxReadBytes||!["text","base64"].includes(format))return fail("invalid_argument","Choose a known file reference and bounded content read.");const native=requireOk(await deps.authorize(signal)),verify=async()=>{guard(authority,signal);requireOk(await native.check(signal));guard(authority,signal)};await verify();const stored=requireOk(store.get("f:"+input.id));if(!stored||!current(stored.value))return fail("not_found","This file reference is outside the current catalog.");const entry=stored.value,path=resolve(entry.rootPath,entry.relativePath);await noSymlinkComponents(path);await verify();const canonicalRoot=await realpath(entry.rootPath),canonicalPath=await realpath(path);await verify();if(canonicalRoot!==entry.rootPath||canonicalPath!==path||!within(canonicalRoot,canonicalPath)||excluded(canonicalPath))return fail("permission_denied","The file reference no longer resolves within its selected folder.");const before=await lstat(path);await verify();if(!before.isFile()||before.isSymbolicLink())return fail("failed_precondition","This reference is not a regular local file.");handle=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));await verify();const opened=await handle.stat();await verify();if(!opened.isFile()||opened.dev!==before.dev||opened.ino!==before.ino)return fail("aborted","The file changed while it was being opened.");if(process.platform==="linux"){const descriptorPath=await realpath(`/proc/self/fd/${handle.fd}`);await verify();if(descriptorPath!==canonicalPath||!within(canonicalRoot,descriptorPath))return fail("permission_denied","The opened file is outside the selected folder.")}const buffer=Buffer.alloc(maxBytes+1);let count=0;while(count<buffer.length){await verify();const chunk=await handle.read(buffer,count,Math.min(64*1024,buffer.length-count),count);await verify();if(!chunk.bytesRead)break;count+=chunk.bytesRead}const after=await handle.stat();await verify();await noSymlinkComponents(path);const finalPath=await realpath(path),finalInfo=await stat(path);await verify();if(finalPath!==canonicalPath||finalInfo.dev!==opened.dev||finalInfo.ino!==opened.ino||version(opened)!==version(after))return fail("aborted","The file changed during the read; refresh and try again.");const contentBytes=buffer.subarray(0,Math.min(count,maxBytes));let content;if(format==="base64")content=contentBytes.toString("base64");else{try{content=new TextDecoder("utf-8",{fatal:true}).decode(contentBytes,{stream:count>maxBytes})}catch{return fail("failed_precondition","This file is not UTF-8 text; request a bounded base64 read.")}if(content.includes("\0"))return fail("failed_precondition","This file contains binary data; request a bounded base64 read.")}await verify();return ok({file:{...file(entry),size:opened.size,modifiedAt:opened.mtime.toISOString(),version:version(opened)},format,content,bytes:contentBytes.length,truncated:count>maxBytes})}catch(error){return problem(error)}finally{await handle?.close()}}function trackedRead(operation){if(reading>=limits.maxConcurrentReads)return Promise.resolve(fail("resource_exhausted","Computer Files already has the maximum concurrent reads."));reading++;const pending=Promise.resolve().then(operation).catch(problem).finally(()=>{reading--;reads.delete(pending)});reads.add(pending);return pending}function readFile(input){return trackedRead(()=>read(input))}function setEnabledRaw(enabled){try{if(typeof enabled!=="boolean")return fail("invalid_argument","Choose whether the file catalog is enabled.");if(closed)return fail("unavailable","Computer Files is inactive.");const previous=requireOk(store.get(CONTROL));requireOk(store.put(CONTROL,{enabled},previous?.revision??0));return statusRaw()}catch(error){return problem(error)}}async function status(){try{const native=requireOk(await deps.authorize(stop.signal));requireOk(await native.check(stop.signal));const result=statusRaw();requireOk(await native.check(stop.signal));return result}catch(error){return problem(error)}}async function setEnabled(enabled){try{const native=requireOk(await deps.authorize(stop.signal));requireOk(await native.check(stop.signal));const result=setEnabledRaw(enabled);requireOk(await native.check(stop.signal));return result}catch(error){return problem(error)}}async function withAccess(operation,signal){try{const lifetime=signal?AbortSignal.any([signal,stop.signal]):stop.signal,authority=access(),native=requireOk(await deps.authorize(lifetime));requireOk(await native.check(lifetime));guard(authority,lifetime);const result=await operation();requireOk(await native.check(lifetime));guard(authority,lifetime);return result}catch(error){return problem(error)}}function withReadAccess(operation,signal){return trackedRead(()=>withAccess(operation,signal))}async function list(input={}){return withAccess(async()=>listRaw(input))}async function graph(input={}){const observed=await status();if(!("ok"in observed))return observed;if(!observed.ok.enabled)return ok({source:SOURCE,state:observed.ok.state,catalogItems:0,partial:observed.ok.partial,records:[]});return withAccess(async()=>graphRaw(input))}const actions=[{name:"computer-files.catalog.list",description:"Find files by name or path in the bounded metadata catalog. File contents are not searched.",effect:"read",inputSchema:{type:"object",properties:{query:{type:"string",maxLength:256},cursor:{type:"string"},limit:{type:"integer",minimum:1,maximum:PAGE}},additionalProperties:false}},{name:"computer-files.catalog.read",description:"Read bounded current bytes from a catalog file reference without storing its contents.",effect:"read",inputSchema:{type:"object",properties:{id:{type:"string",pattern:"^[a-f0-9]{64}$"},maxBytes:{type:"integer",minimum:1,maximum:limits.maxReadBytes},format:{enum:["text","base64"]}},required:["id"],additionalProperties:false}},{name:"computer-files.catalog.status",description:"Inspect selected folders, scan coverage, exclusions and storage limits.",effect:"read",inputSchema:{type:"object",additionalProperties:false}},{name:"computer-files.catalog.refresh",description:"Refresh the bounded local file metadata catalog; this reads no file content.",effect:"read",inputSchema:{type:"object",additionalProperties:false}},{name:"computer-files.catalog.pause",description:"Pause file discovery and access. Automatic connection will preserve this choice.",effect:"write",inputSchema:{type:"object",additionalProperties:false}},{name:"computer-files.catalog.resume",description:"Resume the selected local file folders and refresh their metadata.",effect:"write",inputSchema:{type:"object",additionalProperties:false}}];const info={source:SOURCE,label:"Computer Files",group:"Connector / Local files",auth:"none"};const provider={info,async status(){const state=await status();if(!("ok"in state))return state;const value=state.ok;return ok({...info,state:value.state==="paused"||value.lastScanAt===null?"not-connected":value.state==="unavailable"?"unavailable":value.enabled?"connected":"not-connected",actions:true,message:value.state==="paused"?"Computer Files is paused.":`Small metadata catalog of ${value.catalogItems} files. File contents stay on this computer.${value.partial?" Coverage is partial.":""}`})},async connect(options){const began=now().toISOString(),result=await scan(options?.signal?{signal:options.signal}:{});if(!("ok"in result))return result;if(result.ok.state==="unavailable")return fail("unavailable","No selected local file folder is available.");const job={id:randomUUID(),source:SOURCE,state:"connected",startedAt:began,account:"Local files",instructions:result.ok.partial?"Connected with partial catalog coverage; inspect computer-files.catalog.status for the limit or unavailable folder.":"Local folders are connected. Only file metadata is stored."};jobs.set(job.id,job);while(jobs.size>16)jobs.delete(jobs.keys().next().value);return ok(job)},job(id){return jobs.has(id)?ok(jobs.get(id)):fail("not_found","The file connection job was not found.")},async check(options){try{access();const native=requireOk(await deps.authorize(options?.signal));requireOk(await native.check(options?.signal));if(options?.signal?.aborted)return fail("aborted","File readiness check was cancelled.");return ok({source:SOURCE,basis:"actions",actions:actions.length,operation:{state:"not-run"}})}catch(error){return problem(error)}},async read(request={},options){try{access();if(options?.signal?.aborted)return fail("aborted","File search was cancelled.");if(!snapshot.lastScanAt||now().getTime()-Date.parse(snapshot.lastScanAt)>15*6e4){const refresh=await scan(options?.signal?{signal:options.signal}:{});if(!("ok"in refresh))return refresh}const limit=request.limit??1;if(!Number.isSafeInteger(limit)||limit<1||limit>PAGE)return fail("invalid_argument","Choose a bounded metadata result count.");const selectedFiles=[];let cursor,scanned=0,partial=snapshot.partial;do{if(options?.signal?.aborted)return fail("aborted","File search was cancelled.");const page=await list({...request.query?{query:request.query}:{},...cursor?{cursor}:{},limit:PAGE});if(!("ok"in page))return page;scanned+=page.ok.scanned;partial||=page.ok.partial;for(const item of page.ok.items)if((!request.since||item.modifiedAt>=request.since)&&(!request.until||item.modifiedAt<=request.until)){selectedFiles.push(item);if(selectedFiles.length>=limit)break}cursor=page.ok.next}while(cursor&&selectedFiles.length<limit&&scanned<=limits.maxFiles);const records=selectedFiles.map(item=>({source:SOURCE,sourceId:item.id,ref:`computer-files:${item.id}`,kind:"file-reference",body:item.relativePath,fields:{...item,storage:"metadata-only"}}));return ok({source:SOURCE,scanned,matched:records.length,returned:records.length,records,warnings:partial?["File catalog coverage is partial; this is not a whole-computer search."]:[]})}catch(error){return problem(error)}},actions:{catalog(input){const query=input?.query?.toLocaleLowerCase();const found=actions.filter(action=>!query||action.name.includes(query)||action.description.toLocaleLowerCase().includes(query));return ok({source:SOURCE,actions:found.map(({name,description,effect})=>({name,description,effect})),total:found.length})},method(name){const action=actions.find(action2=>action2.name===name);return action?ok(action):fail("not_found","This Computer Files action is not available.")},async invoke(name,input,options){const p=input.params;if(options?.signal?.aborted)return fail("aborted","The file action was cancelled.");if(name==="computer-files.catalog.status")return status();if(name==="computer-files.catalog.pause")return setEnabled(false);if(name==="computer-files.catalog.resume"){const enabled=await setEnabled(true);return"ok"in enabled?scan(options?.signal?{signal:options.signal}:{}):enabled}if(name==="computer-files.catalog.refresh")return scan(options?.signal?{signal:options.signal}:{});if(name==="computer-files.catalog.list")return list(p);if(name==="computer-files.catalog.read")return readFile({...p,...options?.signal?{signal:options.signal}:{}});return fail("not_found","This Computer Files action is not available.")}}};return{provider,status,scan,list,readFile,graph,setEnabled,withAccess,withReadAccess,async close(){closed=true;stop.abort();await Promise.allSettled([...running?[running]:[],...reads]);jobs.clear()}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{createComputerFiles}from"./catalog.js";export{DEFAULT_BUDGETS,defaultComputerFileRoots}from"./policy.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{homedir}from"node:os";import{dirname,isAbsolute,join,parse,relative,resolve,sep}from"node:path";import{open,lstat,realpath}from"node:fs/promises";export const DEFAULT_BUDGETS=Object.freeze({maxFiles:2e4,maxMetadataBytes:16*1024*1024,maxRecordBytes:4096,maxEntries:1e5,maxDirectories:5e3,maxDepth:12,scanMs:15e3,maxReadBytes:1024*1024,maxConcurrentReads:2});const MAXIMA={maxFiles:1e5,maxMetadataBytes:64*1024*1024,maxRecordBytes:8192,maxEntries:5e5,maxDirectories:2e4,maxDepth:24,scanMs:6e4,maxReadBytes:1024*1024,maxConcurrentReads:4};export function budgets(value={}){const result={...DEFAULT_BUDGETS};for(const key of Object.keys(value)){if(!(key in result))throw Error("Unknown Computer Files budget.");const k=key,n=value[k];if(!Number.isSafeInteger(n)||n<1||n>MAXIMA[k])throw Error("Computer Files budget is outside the supported bound.");result[k]=n}return Object.freeze(result)}export function within(root,path){const r=relative(root,path);return r===""||r!==".."&&!r.startsWith(`..${sep}`)&&!isAbsolute(r)}export function roots(input,home){if(!Array.isArray(input)||input.length>16)throw Error("Computer Files supports at most 16 explicit roots.");const found=[];for(const value of input){if(typeof value!=="string"||!isAbsolute(value)||value.length>2048||/[\x00-\x1f]/.test(value))throw Error("Computer Files roots must be bounded absolute directories.");const path=resolve(value);if(path===parse(path).root)throw Error("A whole filesystem cannot be a Computer Files root.");if(found.some(prior=>within(prior,path)))continue;for(let i=found.length-1;i>=0;i--)if(within(path,found[i]))found.splice(i,1);found.push(path)}void home;return found}export async function defaultComputerFileRoots(home=homedir(),platform=process.platform,env=process.env){const paths=new Map([["DOCUMENTS",join(home,"Documents")],["DESKTOP",join(home,"Desktop")],["DOWNLOAD",join(home,"Downloads")]]);if(platform==="linux"){let file;try{const config=env.XDG_CONFIG_HOME&&isAbsolute(env.XDG_CONFIG_HOME)?env.XDG_CONFIG_HOME:join(home,".config");file=await open(join(config,"user-dirs.dirs"),"r");const buffer=Buffer.alloc(16*1024+1),read=await file.read(buffer,0,buffer.length,0);if(read.bytesRead<=16*1024)for(const line of buffer.subarray(0,read.bytesRead).toString("utf8").split("\n")){const match=/^\s*XDG_(DOCUMENTS|DESKTOP|DOWNLOAD)_DIR="([^"\r\n]*)"\s*(?:#.*)?$/.exec(line);if(!match)continue;const value=match[2].replace(/^\$HOME(?=\/|$)/,home);if(!value.includes("$")&&!value.includes("`")&&isAbsolute(value))paths.set(match[1],value)}}catch{}finally{await file?.close()}}const available=[],canonicalHome=await realpath(home).catch(()=>resolve(home));for(const candidate of paths.values())try{const info=await lstat(candidate);if(!info.isDirectory()||info.isSymbolicLink())continue;const path=await realpath(candidate);if(path===canonicalHome)continue;await noSymlinkComponents(path);available.push(path)}catch{}return roots(available,canonicalHome)}const ALWAYS=new Set([".git",".hg",".svn","node_modules","bower_components",".venv","venv","__pycache__",".cache",".npm",".pnpm-store",".yarn",".gradle",".m2",".cargo",".rustup",".tox",".pytest_cache",".mypy_cache",".next",".nuxt",".turbo",".parcel-cache",".Trash",".Trashes","$RECYCLE.BIN","System Volume Information","lost+found"]);const HOME_SYSTEM=new Set(["AppData","Library"]);const BUILD=new Set(["build","dist","target","vendor","coverage","out"]);const MANIFESTS=["package.json","Cargo.toml","go.mod","pyproject.toml","pom.xml","build.gradle","CMakeLists.txt","Makefile",".git"];const BUNDLE=/\.(?:app|framework|bundle|photoslibrary|photolibrary|pvm|vmwarevm)$/i;export const isExcludedFile=name=>/^\.env(?:\.|$)/i.test(name)||/\.(?:pem|key|p12|pfx|kdbx|sqlite(?:3)?|db|wal|journal|lock|tmp|swp|pyc|o|a|so|dll|exe|dmg|iso)$/i.test(name)||["id_rsa","id_ed25519",".DS_Store","Thumbs.db"].includes(name);export function excludedDirectory(name,project,homeChild=false){return ALWAYS.has(name)||homeChild&&HOME_SYSTEM.has(name)||name===".ssh"||name===".gnupg"||name===".aws"||name===".kube"||BUNDLE.test(name)||project&&BUILD.has(name)}export async function isProject(directory){for(const marker of MANIFESTS)try{const stat=await lstat(join(directory,marker));if(stat.isFile()||stat.isDirectory())return true}catch{}return false}export async function noSymlinkComponents(path){const chain=[];let current=resolve(path);while(current!==parse(current).root){chain.push(current);current=dirname(current)}for(let i=chain.length-1;i>=0;i--){const stat=await lstat(chain[i]);if(stat.isSymbolicLink())throw Object.assign(Error("A selected file path crosses a symbolic link."),{code:"ELOOP"})}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const ok=value=>({ok:value});export const fail=(code,message)=>({err:{code,message,layer:"connector",retryability:"non-retryable"}});export class Refused extends Error{result;constructor(result){super(result.err.message);this.result=result}}export function requireOk(value){if("ok"in value)return value.ok;throw new Refused("err"in value?value:fail("data_loss","The file catalog returned no storage receipt."))}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zortexhq/plugin-connector-computer-files",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": {
|
|
7
|
+
"default": "./dist/index.js"
|
|
8
|
+
}
|
|
9
|
+
},
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"@zortexhq/plugin-connector-core": "0.1.0",
|
|
12
|
+
"@zortexhq/plugin-connector-framework": "0.1.0",
|
|
13
|
+
"@zortexhq/plugin-vault-sqlite": "0.1.0"
|
|
14
|
+
},
|
|
15
|
+
"zortex": {
|
|
16
|
+
"role": "plugin"
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./connections.js";export*from"./connection-feedback.js";export*from"./wait-authorization.js";export*from"./connector-utils.js";export*from"./connector-v3.js";export*from"./connectors.js";export*from"./local-read-custody.js";export*from"./selected-account.js";export{isTransientConnectorAction,withTransientConnectorAction}from"../transient-action-context.js";export{currentNativePrincipal,saveNativeReadPermission}from"../native-principal.js";export{createPinnedLoopbackHttp}from"../transport.js";
|
|
1
|
+
export*from"./connections.js";export*from"./connection-feedback.js";export*from"./wait-authorization.js";export*from"./connector-utils.js";export*from"./connector-v3.js";export*from"./connectors.js";export*from"./local-read-custody.js";export*from"./selected-account.js";export{isTransientConnectorAction,withTransientConnectorAction}from"../transient-action-context.js";export{currentNativePrincipal,saveNativeReadPermission}from"../native-principal.js";export{readNativeUserFileRoots}from"../native-file-roots.js";export{createPinnedLoopbackHttp}from"../transport.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{usageOutcome,usageResultSummary,usageErrorCategory,withFeedbackFlow,createTraceRecorder}from"@zortexhq/plugin-telemetry/api";import{instrumentConnectorHub}from"./operational-hub.js";import{validateRead}from"./api/index.js";import{sharedReadDiscovery}from"./shared-read-discovery.js";import{createEnrollment}from"./enrollment.js";import{createConnectorHttp}from"./transport.js";import{createAuthorizationMetrics}from"./authorization-metrics.js";import{createConnectionFeedback}from"./connection-feedback.js";import{actionReview,sameActionReview,validateReviewedInput}from"./action-review.js";import{createResourceAdmission}from"./resource-admission.js";import{bindConnectorActionRetention,isTransientConnectorAction,withTransientConnectorAction}from"./transient-action-context.js";import{informationFingerprint,publicFileSnapshot,sameProviderFile,validFileHandle,validInformationHandle,validProviderFile}from"./share-snapshot.js";export const name="zortex-connector-hub";export const inject=["zortexVaultStore"];function readiness(source,value){const invalid=()=>businessError("data_loss","Source returned invalid readiness metadata.","plugin");if(!value||value.source!==source||value.basis!=="actions"&&value.basis!=="read"||!value.operation)return invalid();if(value.basis==="actions"&&(!Number.isSafeInteger(value.actions)||value.actions<0))return invalid();const operation=value.operation;if(operation.state!=="not-run"&&operation.state!=="succeeded")return invalid();if(value.basis==="read"&&(operation.state!=="succeeded"||!Number.isSafeInteger(operation.returned)||operation.returned<0))return invalid();if(operation.state==="not-run")return ok({source,basis:value.basis,...value.basis==="actions"?{actions:value.actions}:{},operation:{state:"not-run"}});if(operation.returned!==void 0&&(!Number.isSafeInteger(operation.returned)||operation.returned<0))return invalid();let evidence;if(operation.evidence!==void 0){const{origin,observedAt,stage,ownRecords}=operation.evidence;if(!["live","connection-first-read","vault-cache"].includes(origin)||!["read-page","read-own-posts"].includes(stage)||typeof observedAt!=="string"||observedAt.length>27||!Number.isFinite(Date.parse(observedAt))||new Date(observedAt).toISOString()!==observedAt||ownRecords!==void 0&&(!Number.isSafeInteger(ownRecords)||ownRecords<0))return invalid();evidence={origin,observedAt,stage,...ownRecords!==void 0?{ownRecords}:{}}}return ok({source,basis:value.basis,...value.basis==="actions"?{actions:value.actions}:{},operation:{state:"succeeded",...operation.returned!==void 0?{returned:operation.returned}:{},...evidence?{evidence}:{}}})}function shareReadSchema(schema){const effect=schema.effect,http=schema.httpMethod;const effectClass=effect==="read"?"read":effect&&typeof effect==="object"&&!Array.isArray(effect)&&effect.class==="read"?"read":effect===void 0?void 0:"other";const httpClass=http===void 0?void 0:http==="GET"?"read":"other";return(effectClass==="read"||httpClass==="read")&&effectClass!=="other"&&httpClass!=="other"}export function createConnectorHub(dependencies={}){const statusTimeoutMs=dependencies.statusTimeoutMs??15e3;if(!Number.isSafeInteger(statusTimeoutMs)||statusTimeoutMs<1||statusTimeoutMs>3e4)throw Error("Invalid source metadata deadline.");const authorization=createAuthorizationMetrics(dependencies.metrics,dependencies.authorizationPollMs,dependencies.authorizationObserveMs);const sources=new Map,sourceEpochs=new Map,jobs=new Map,usability=new Map,observations=new Set;let closed=false,closing,admissionSequence=0;const SNAPSHOT_TTL_MS=30*60*1e3;const informationSnapshots=new Map;const fileSnapshots=new Map;const statusStop=new AbortController,statusProbes=new Map;const fail=message=>businessError("failed_precondition",message,"plugin");const provider=source=>closed?void 0:sources.get(source);const purgeSnapshots=()=>{const now=Date.now();for(const[handle,row]of informationSnapshots)if(Date.parse(row.public.expiresAt)<=now)informationSnapshots.delete(handle);for(const[handle,row]of fileSnapshots)if(Date.parse(row.public.expiresAt)<=now)fileSnapshots.delete(handle)};const samePublic=(left,right)=>{try{return JSON.stringify(left)===JSON.stringify(right)}catch{return false}};const admitted=(kind,source,needs,task,signal)=>{const retained=bindConnectorActionRetention(task);return dependencies.admission?.run(`${kind}/${source}/${++admissionSequence}`,needs,()=>Promise.resolve(retained()),{...signal?{signal}:{}})??retained()};const providerNeeds=(source,extra={})=>({http:1,[`provider:${source}`]:1,...extra});const unavailableStatus=(item,message)=>({...item.info,state:"unavailable",...item.actions?{actions:true}:{},message});function probeStatus(item){if(item.registration==="deferred")return Promise.resolve({...item.info,state:"unavailable",registration:"deferred",actions:false,message:"Setup required; no active provider is registered. Restart after setup."});const epoch=sourceEpochs.get(item.info.source)??0,existing=statusProbes.get(item);if(existing)return existing.epoch===epoch?existing.result:Promise.resolve(unavailableStatus(item,"A previous source registration is still settling."));const deadline=new AbortController,signal=AbortSignal.any([deadline.signal,statusStop.signal]);const timer=setTimeout(()=>deadline.abort(),statusTimeoutMs);let removeAbort=()=>{};const interrupted=new Promise(resolve=>{const cancel=()=>{clearTimeout(timer);resolve(unavailableStatus(item,closed?"Connector hub is inactive.":"Source status timed out."))};if(signal.aborted)cancel();else{signal.addEventListener("abort",cancel,{once:true});removeAbort=()=>signal.removeEventListener("abort",cancel)}});const operation=Promise.resolve().then(()=>admitted("probe",item.info.source,{[`provider:${item.info.source}`]:1},()=>signal.aborted?businessError("aborted","Source metadata inspection was cancelled.","plugin"):item.status({signal}),signal));const observed=operation.then(result2=>"ok"in result2?{...result2.ok,...item.actions?{actions:true}:{}}:unavailableStatus(item,"err"in result2?result2.err.message:"Source state was not confirmed."),()=>unavailableStatus(item,"Source status failed."));const result=Promise.race([observed,interrupted]);statusProbes.set(item,{epoch,result});const settled=()=>{clearTimeout(timer);removeAbort();if(statusProbes.get(item)?.result===result)statusProbes.delete(item)};void operation.then(settled,settled);return result}const retentionFailure=(item,options)=>options?.retention!==void 0&&options.retention!=="transient"?businessError("invalid_argument","Unsupported connector result retention policy.","plugin"):(options?.retention==="transient"||isTransientConnectorAction())&&item?.requiresPersistentPayloads?fail("This source requires persistent payload storage and has no qualified transient operation."):void 0;function observe(source,usable){if(!dependencies.availabilityMetrics||usability.get(source)===usable)return Promise.resolve();const task=(async()=>{try{const saved=await dependencies.metrics?.()?.record({operation:"connector.usable",source,outcome:usable?"ok":"cancelled",durationMs:0,internal:true});if(saved&&"ok"in saved&&saved.ok.recorded)usability.set(source,usable)}catch{}})();observations.add(task);void task.finally(()=>observations.delete(task));return task}async function observeResult(source,result,enabled){if(!enabled)return observe(source,false);const outcome=usageOutcome(result);if(outcome==="ok"||outcome==="empty")await observe(source,true);else if(outcome==="fault"||outcome==="auth-blocked")await observe(source,false)}const service={hasSource:source=>provider(source)!==void 0,...dependencies.metrics?{queryMetrics:"owned"}:{},register(item){if(closed)throw Error("Connector hub is inactive.");if(!/^[a-z][a-z0-9-]{0,63}$/.test(item.info.source))throw Error("Invalid source identity.");if(sources.has(item.info.source))throw Error("Duplicate connector source.");sources.set(item.info.source,item);sourceEpochs.set(item.info.source,(sourceEpochs.get(item.info.source)??0)+1);return()=>{if(sources.get(item.info.source)===item){sources.delete(item.info.source);sourceEpochs.set(item.info.source,(sourceEpochs.get(item.info.source)??0)+1);authorization.withdraw(item);void observe(item.info.source,false)}}},replaceDeferred(expected,item){const source=expected.info.source;if(closed||expected.registration!=="deferred"||item.registration==="deferred"||item.info.source!==source||sources.get(source)!==expected)return void 0;sources.set(source,item);sourceEpochs.set(source,(sourceEpochs.get(source)??0)+1);return()=>{if(sources.get(source)===item){sources.delete(source);sourceEpochs.set(source,(sourceEpochs.get(source)??0)+1);authorization.withdraw(item);void observe(source,false)}}},async status(options){if(closed)return businessError("unavailable","Connector hub is inactive.","plugin");if(options?.signal?.aborted)return businessError("aborted","Source status inspection was cancelled.","plugin");const states=Promise.all([...sources.values()].map(async item=>{const epoch=sourceEpochs.get(item.info.source),state=await probeStatus(item);return provider(item.info.source)===item&&sourceEpochs.get(item.info.source)===epoch?state:unavailableStatus(item,"Source was disabled before its status reply.")}));let removeAbort=()=>{};const cancelled=new Promise(resolve=>{if(options?.signal){const cancel=()=>resolve(businessError("aborted","Source status inspection was cancelled.","plugin"));options.signal.addEventListener("abort",cancel,{once:true});removeAbort=()=>options.signal.removeEventListener("abort",cancel)}});try{const result=await Promise.race([states.then(ok),cancelled]);return closed?businessError("unavailable","Connector hub is inactive.","plugin"):result}finally{removeAbort()}},async connect(source,options){options={...options,automatic:options?.automatic===true};const item=provider(source);if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(options.savedAccessOnly&&!item.supportsSavedReconnect)return businessError("failed_precondition","This source cannot reconnect using saved access.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;return withTransientConnectorAction(options?.retention==="transient",()=>admitted("connect",source,providerNeeds(source,{worker:1,[`refresh:${source}`]:1}),()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);await trace.step("source_selected","completed");await trace.step("authorization_started","started");const started=performance.now();let result;try{result=await item.connect(options)}catch(error){await authorization.immediate(item,businessError(options?.signal?.aborted?"aborted":"unavailable","Connection failed.","plugin"),started);throw error}if(provider(source)!==item){result=businessError("unavailable","Source was disabled.","plugin");await authorization.immediate(item,result,started,"source_disabled");return result}if("ok"in result&&result.ok.source!==source)result=businessError("data_loss","Mismatched connection source.","plugin");if("ok"in result){jobs.set(result.ok.id,item);await authorization.track(item,result,started)}else await authorization.immediate(item,result,started);return result},authorization.currentFlow(item)),options?.signal))},job(id){const item=jobs.get(id);if(!item)return businessError("not_found","Unknown connector connection job.","plugin");if(provider(item.info.source)!==item)return businessError("unavailable","Source was disabled.","plugin");const result=item.job(id);authorization.observe(item,id,result);return result},cancelJob(id,source){const tracked=jobs.get(id),item=tracked??(source?provider(source):void 0);if(!item)return businessError("not_found","Unknown connector connection job.","plugin");if(source&&item.info.source!==source)return businessError("not_found","Unknown connector connection job.","plugin");if(provider(item.info.source)!==item)return businessError("unavailable","Source was disabled.","plugin");return item.cancelJob?.(id)},async settleObservations(options){if(options?.closing)await authorization.close();else await authorization.settle();await Promise.allSettled([...observations])},async check(source,options){const item=provider(source);if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Source readiness was cancelled.","plugin");try{const result=item.check?await withTransientConnectorAction(options?.retention==="transient",()=>admitted("check",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.check(options),options?.signal)):await service.read(source,{limit:1},options).then(result2=>"ok"in result2?ok({source,basis:"read",operation:{state:"succeeded",returned:result2.ok.returned,...result2.ok.evidence?{evidence:result2.ok.evidence}:{}}}):"empty"in result2?ok({source,basis:"read",operation:{state:"succeeded",returned:0}}):result2);if(provider(source)!==item)return businessError("unavailable","Source was disabled before readiness delivery.","plugin");if(options?.signal?.aborted)return businessError("aborted","Source readiness was cancelled.","plugin");if("err"in result)return result;if(!("ok"in result))return businessError("data_loss","Source did not provide readiness metadata.","plugin");return readiness(source,result.ok)}catch{return businessError(options?.signal?.aborted?"aborted":"unavailable","Source readiness did not complete.","plugin")}},async read(source,request={},options){const item=provider(source);const run=()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);if(dependencies.metrics)await trace.step("read_started","started");const started=performance.now();let disabled=false;const execute=async()=>{if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(provider(source)!==item){disabled=true;return businessError("unavailable","Source was disabled before the query.","plugin")}const retention=retentionFailure(item,options);if(retention)return retention;const invalid=validateRead(request,item.info.readById?["fileId"]:[]);if(invalid)return invalid;try{const result2=await item.read(request,options);if(provider(source)!==item){disabled=true;return businessError("unavailable","Source was disabled during the query.","plugin")}if("ok"in result2&&(result2.ok.source!==source||result2.ok.returned!==result2.ok.records.length||result2.ok.returned>(request.limit??1)))return businessError("data_loss","Source returned invalid or unbounded records.","plugin");return result2}catch{return businessError(options?.signal?.aborted?"aborted":"unavailable","Connector query did not complete.","plugin")}};const result=await execute();try{const metrics=dependencies.metrics?.();if(metrics){const summary=usageResultSummary(result),errorCategory=usageErrorCategory(result);await metrics.record({operation:"connector.read",outcome:disabled?"cancelled":usageOutcome(result),durationMs:performance.now()-started,internal:options?.internalTelemetry??false,...item?{source:item.info.source}:{},..."err"in result?{code:result.err.code}:{},...summary?{result:summary}:{},...errorCategory?{errorCategory}:{}})}}catch{}await trace.step("read_verified","err"in result?result.err.code==="aborted"?"cancelled":"failed":"ok"in result||"empty"in result?"completed":"unknown","ok"in result?{count:result.ok.returned}:"empty"in result?{count:0}:{});if(item)await observeResult(source,result,provider(source)===item);return item&&provider(source)!==item?businessError("unavailable","Source was disabled before query delivery.","plugin"):result});const feedback=dependencies.feedback?.();return withTransientConnectorAction(options?.retention==="transient",()=>admitted("read",source,providerNeeds(source,{worker:1}),()=>feedback?feedback.run(source,run):run(),options?.signal))},close(){if(!closing){closed=true;statusStop.abort();for(const source of sources.keys())void observe(source,false);sources.clear();jobs.clear();informationSnapshots.clear();fileSnapshots.clear();closing=(async()=>{await authorization.close();await Promise.allSettled([...observations])})()}return closing},async catalog(source,input,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source);if(!item)return fail("Source is not installed or enabled: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(!item.actions){const action=sharedReadDiscovery(item.info);return ok({source,actions:[{name:action.name,effect:action.effect,operation:action.operation}],total:1,discovery:"Request method=connector.read for the shared action schema; execute it with operation=action, not connector.invoke."})}const result=await admitted("catalog",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.catalog(input),options?.signal);return provider(source)===item?result:businessError("unavailable","Source was disabled before its catalog reply.","plugin")})},async method(source,name2,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source);if(!item)return fail("Source is not installed or enabled: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(!item.actions)return name2==="connector.read"?ok(sharedReadDiscovery(item.info)):fail("This source has no installed action schema: "+name2);const result=await admitted("method",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.method(name2),options?.signal);return provider(source)===item?result:businessError("unavailable","Source was disabled before its schema reply.","plugin")})},async review(source,name2,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source),epoch=sourceEpochs.get(source)??0;if(!item?.actions)return fail("This source has no installed action schema: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;const result=await admitted("review",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.method(name2),options?.signal);if(provider(source)!==item)return businessError("unavailable","Source was disabled before its schema reply.","plugin");if(!("ok"in result))return result;return actionReview(source,name2,epoch,result.ok)})},async invokeReviewed(review,input,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{if(!review||typeof review!=="object"||typeof review.source!=="string"||typeof review.name!=="string"||typeof review.revision!=="string")return fail("A reviewed action handle is required.");const item=provider(review.source),epoch=sourceEpochs.get(review.source)??0;if(!item?.actions)return fail("This source has no installed action port: "+review.source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;const current=await admitted("invoke-review",review.source,providerNeeds(review.source,{probe:1,discovery:1}),()=>item.actions.method(review.name),options?.signal);if(provider(review.source)!==item)return businessError("unavailable","Source was disabled before action review.","plugin");if(!("ok"in current))return current;if(!sameActionReview(review,epoch,current.ok))return businessError("failed_precondition","Provider action schema changed after review; inspect the new schema before dispatch.","plugin");const valid=validateReviewedInput(review,input);if(!("ok"in valid))return valid;return service.invoke(review.source,review.name,input,options)})},async invoke(source,name2,input,options){const item=provider(source);if(!item?.actions)return fail("This source has no installed action port: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const run=()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);await trace.step("invoke_started","started");if(provider(source)!==item){await trace.step("invoke_finished","failed",{reason:"source_disabled"});return businessError("unavailable","Source was disabled before action dispatch.","plugin")}const retention=retentionFailure(item,options);if(retention){await trace.step("invoke_finished","failed",{reason:"provider_error"});return retention}const started=performance.now();let result;try{const reply=await admitted("invoke",source,providerNeeds(source,{worker:1}),()=>{if(provider(source)!==item)return businessError("unavailable","Source was disabled before action dispatch.","plugin");if(!item.actions.reportsActionAccess){try{options?.onActionAccess?.("legacy")}catch{}const legacyOptions=options?{...options}:void 0;if(legacyOptions)delete legacyOptions.onActionAccess;return item.actions.invoke(name2,input,legacyOptions)}return item.actions.invoke(name2,input,options)},options?.signal);result=provider(source)===item?reply:businessError("unavailable","Source was disabled before its reply.","plugin")}catch{result=businessError(options?.signal?.aborted?"aborted":"unavailable","Source action did not finish.","plugin")}let outcome="unknown";try{outcome=usageOutcome(result);const metrics=dependencies.metrics?.();if(metrics){const summary=usageResultSummary(result),errorCategory=usageErrorCategory(result);await metrics.record({operation:"connector.invoke",source,outcome,durationMs:performance.now()-started,internal:true,..."err"in result?{code:result.err.code}:{},...summary?{result:summary}:{},...errorCategory?{errorCategory}:{}})}}catch{}await trace.step("invoke_finished",outcome==="ok"||outcome==="empty"?"completed":outcome==="cancelled"?"cancelled":outcome==="auth-blocked"?"waiting":outcome==="fault"||outcome==="invalid"?"failed":"unknown");await observeResult(source,result,provider(source)===item);return provider(source)===item?result:businessError("unavailable","Source was disabled before action delivery.","plugin")});const feedback=dependencies.feedback?.();return withTransientConnectorAction(options?.retention==="transient",()=>feedback?feedback.run(source,run):run())},async captureInformation(review,input,options){purgeSnapshots();if(!review||typeof review!=="object"||!review.schema||!shareReadSchema(review.schema))return businessError("permission_denied","Share snapshots require an explicitly read-only Connector Action.","plugin");const item=provider(review.source),epoch=sourceEpochs.get(review.source)??0;if(!item)return fail("Source is not enabled: "+review.source);const result=await service.invokeReviewed(review,input,options);if(!("ok"in result))return result;if(provider(review.source)!==item||sourceEpochs.get(review.source)!==epoch)return businessError("unavailable","Source changed before its information snapshot was retained.","plugin");const fingerprint=informationFingerprint(result.ok);if(!("ok"in fingerprint))return fingerprint;const handle=randomUUID(),capturedAt=new Date().toISOString(),expiresAt=new Date(Date.now()+SNAPSHOT_TTL_MS).toISOString();const snapshot={kind:"information",source:review.source,name:review.name,handle,capturedAt,expiresAt,...fingerprint.ok};let savedReview,savedInput;try{savedReview=structuredClone(review);savedInput=structuredClone(input)}catch{return businessError("invalid_argument","Connector snapshot input is not cloneable.","plugin")}informationSnapshots.set(handle,{public:snapshot,review:savedReview,input:savedInput,provider:item,epoch});return ok(snapshot)},async verifyInformation(snapshot,options){purgeSnapshots();if(!validInformationHandle(snapshot))return businessError("invalid_argument","Pass one Connector information snapshot handle.","plugin");const stored=informationSnapshots.get(snapshot.handle);if(!stored||!samePublic(stored.public,snapshot))return fail("Connector information snapshot is missing, expired or changed.");if(provider(stored.public.source)!==stored.provider||sourceEpochs.get(stored.public.source)!==stored.epoch)return fail("Connector source changed after preview; review the Share again.");const result=await service.invokeReviewed(stored.review,stored.input,options);if(!("ok"in result))return result;const current=informationFingerprint(result.ok);if(!("ok"in current))return current;if(current.ok.sha256!==stored.public.sha256||current.ok.bytes!==stored.public.bytes)return businessError("aborted","Connector information changed after preview; review the Share again.","plugin");return ok(stored.public)},async inspectFile(source,input,options){purgeSnapshots();if(!input||typeof input.id!=="string"||!input.id||Buffer.byteLength(input.id)>1024)return businessError("invalid_argument","Connector file inspection requires one provider identity.","plugin");const item=provider(source),epoch=sourceEpochs.get(source)??0;if(!item?.fileSnapshots)return fail("This source does not provide file snapshots: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Connector file inspection was cancelled.","plugin");const result=await withTransientConnectorAction(options?.retention==="transient",()=>admitted("file-inspect",source,providerNeeds(source,{worker:1}),()=>item.fileSnapshots.inspect(input,options),options?.signal));if(provider(source)!==item||sourceEpochs.get(source)!==epoch)return businessError("unavailable","Source changed before its file snapshot was retained.","plugin");if(!("ok"in result))return result;const checked=validProviderFile(result.ok,source);if(!("ok"in checked))return checked;let retained;try{retained=structuredClone(checked.ok)}catch{return businessError("data_loss","Connector file snapshot metadata is not retainable.","plugin")}const handle=randomUUID(),expiresAt=new Date(Date.now()+SNAPSHOT_TTL_MS).toISOString(),snapshot=publicFileSnapshot(handle,retained,expiresAt);fileSnapshots.set(handle,{public:snapshot,file:retained,provider:item,epoch});return ok(snapshot)},async materializeFile(snapshot,options){purgeSnapshots();if(!validFileHandle(snapshot))return businessError("invalid_argument","Pass one Connector file snapshot handle.","plugin");const stored=fileSnapshots.get(snapshot.handle);if(!stored||!samePublic(stored.public,snapshot))return fail("Connector file snapshot is missing, expired or changed.");const item=provider(stored.public.source);if(item!==stored.provider||sourceEpochs.get(stored.public.source)!==stored.epoch||!item.fileSnapshots)return fail("Connector source changed after preview; review the Share again.");const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Connector file materialization was cancelled.","plugin");const result=await withTransientConnectorAction(options?.retention==="transient",()=>admitted("file-materialize",stored.public.source,providerNeeds(stored.public.source,{worker:1}),()=>item.fileSnapshots.materialize(stored.file,options),options?.signal));if(provider(stored.public.source)!==item||sourceEpochs.get(stored.public.source)!==stored.epoch)return businessError("unavailable","Source changed while its file snapshot was materialized.","plugin");if(!("ok"in result))return result;const checked=validProviderFile(result.ok.file,stored.public.source);if(!("ok"in checked))return checked;if(!sameProviderFile(stored.file,checked.ok)||!(result.ok.content instanceof Uint8Array)||result.ok.mimeType!==stored.public.mimeType||result.ok.size!==result.ok.content.byteLength||result.ok.size<0)return businessError("data_loss","Connector file bytes did not match the inspected snapshot.","plugin");return ok({file:stored.public,content:result.ok.content,mimeType:result.ok.mimeType,size:result.ok.size})}};return instrumentConnectorHub(service,dependencies.metrics,id=>jobs.get(id)?.info.source)}export async function apply(ctx){const feedback=createConnectionFeedback({store:()=>ctx.get("zortexSqliteVault")?.createPrivateStore("connection-feedback"),connection:async source=>{const local=ctx.get("zortexLocalSourceRegistry")?.get(source);if(local)return ok(local);const level1=ctx.get("zortexLevel1Connectors");const namespace=source==="figma"&&level1?.provider("figma")?.spec.auth.kind==="fields"?"figma--pat":source;const result=await ctx.zortexVaultStore.connection(namespace);return namespace!==source&&"ok"in result&&result.ok?ok({...result.ok,source}):result}});ctx.provide("zortexConnectionFeedback",feedback);const admission=createResourceAdmission(),http=await createConnectorHttp({admission}),hub=createConnectorHub({metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>feedback,availabilityMetrics:true,admission}),enrollment=createEnrollment({vault:ctx.zortexVaultStore,transport:http.fetch,metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>feedback});ctx.provide("zortexResourceAdmission",admission);ctx.provide("zortexConnectorHttp",http.fetch);ctx.provide("zortexConnectorHub",hub);ctx.provide("zortexConnectorEnrollment",enrollment);ctx.effect(()=>()=>hub.close());ctx.effect(()=>async()=>{await enrollment.close();await http.close();admission.close()})}
|
|
1
|
+
import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{usageOutcome,usageResultSummary,usageErrorCategory,withFeedbackFlow,createTraceRecorder}from"@zortexhq/plugin-telemetry/api";import{instrumentConnectorHub}from"./operational-hub.js";import{validateRead}from"./api/index.js";import{sharedReadDiscovery}from"./shared-read-discovery.js";import{createEnrollment}from"./enrollment.js";import{createConnectorHttp}from"./transport.js";import{createAuthorizationMetrics}from"./authorization-metrics.js";import{createConnectionFeedback}from"./connection-feedback.js";import{actionReview,sameActionReview,validateReviewedInput}from"./action-review.js";import{createResourceAdmission}from"./resource-admission.js";import{bindConnectorActionRetention,isTransientConnectorAction,withTransientConnectorAction}from"./transient-action-context.js";import{informationFingerprint,publicFileSnapshot,sameProviderFile,validFileHandle,validInformationHandle,validProviderFile}from"./share-snapshot.js";export const name="zortex-connector-hub";export const inject=["zortexVaultStore"];function readiness(source,value){const invalid=()=>businessError("data_loss","Source returned invalid readiness metadata.","plugin");if(!value||value.source!==source||value.basis!=="actions"&&value.basis!=="read"||!value.operation)return invalid();if(value.basis==="actions"&&(!Number.isSafeInteger(value.actions)||value.actions<0))return invalid();const operation=value.operation;if(operation.state!=="not-run"&&operation.state!=="succeeded")return invalid();if(value.basis==="read"&&(operation.state!=="succeeded"||!Number.isSafeInteger(operation.returned)||operation.returned<0))return invalid();if(operation.state==="not-run")return ok({source,basis:value.basis,...value.basis==="actions"?{actions:value.actions}:{},operation:{state:"not-run"}});if(operation.returned!==void 0&&(!Number.isSafeInteger(operation.returned)||operation.returned<0))return invalid();let evidence;if(operation.evidence!==void 0){const{origin,observedAt,stage,ownRecords}=operation.evidence;if(!["live","connection-first-read","vault-cache"].includes(origin)||!["read-page","read-own-posts"].includes(stage)||typeof observedAt!=="string"||observedAt.length>27||!Number.isFinite(Date.parse(observedAt))||new Date(observedAt).toISOString()!==observedAt||ownRecords!==void 0&&(!Number.isSafeInteger(ownRecords)||ownRecords<0))return invalid();evidence={origin,observedAt,stage,...ownRecords!==void 0?{ownRecords}:{}}}return ok({source,basis:value.basis,...value.basis==="actions"?{actions:value.actions}:{},operation:{state:"succeeded",...operation.returned!==void 0?{returned:operation.returned}:{},...evidence?{evidence}:{}}})}function shareReadSchema(schema){const effect=schema.effect,http=schema.httpMethod;const effectClass=effect==="read"?"read":effect&&typeof effect==="object"&&!Array.isArray(effect)&&effect.class==="read"?"read":effect===void 0?void 0:"other";const httpClass=http===void 0?void 0:http==="GET"?"read":"other";return(effectClass==="read"||httpClass==="read")&&effectClass!=="other"&&httpClass!=="other"}export function createConnectorHub(dependencies={}){const statusTimeoutMs=dependencies.statusTimeoutMs??15e3;if(!Number.isSafeInteger(statusTimeoutMs)||statusTimeoutMs<1||statusTimeoutMs>3e4)throw Error("Invalid source metadata deadline.");const authorization=createAuthorizationMetrics(dependencies.metrics,dependencies.authorizationPollMs,dependencies.authorizationObserveMs);const sources=new Map,sourceEpochs=new Map,jobs=new Map,usability=new Map,observations=new Set;let closed=false,closing,admissionSequence=0;const SNAPSHOT_TTL_MS=30*60*1e3;const informationSnapshots=new Map;const fileSnapshots=new Map;const statusStop=new AbortController,statusProbes=new Map;const fail=message=>businessError("failed_precondition",message,"plugin");const provider=source=>closed?void 0:sources.get(source);const purgeSnapshots=()=>{const now=Date.now();for(const[handle,row]of informationSnapshots)if(Date.parse(row.public.expiresAt)<=now)informationSnapshots.delete(handle);for(const[handle,row]of fileSnapshots)if(Date.parse(row.public.expiresAt)<=now)fileSnapshots.delete(handle)};const samePublic=(left,right)=>{try{return JSON.stringify(left)===JSON.stringify(right)}catch{return false}};const admitted=(kind,source,needs,task,signal)=>{const retained=bindConnectorActionRetention(task);return dependencies.admission?.run(`${kind}/${source}/${++admissionSequence}`,needs,()=>Promise.resolve(retained()),{...signal?{signal}:{}})??retained()};const providerNeeds=(source,extra={})=>({http:1,[`provider:${source}`]:1,...extra});const unavailableStatus=(item,message)=>({...item.info,state:"unavailable",...item.actions?{actions:true}:{},message});function probeStatus(item){if(item.registration==="deferred")return Promise.resolve({...item.info,state:"unavailable",registration:"deferred",actions:false,message:"Setup required; no active provider is registered. Restart after setup."});const epoch=sourceEpochs.get(item.info.source)??0,existing=statusProbes.get(item);if(existing)return existing.epoch===epoch?existing.result:Promise.resolve(unavailableStatus(item,"A previous source registration is still settling."));const deadline=new AbortController,signal=AbortSignal.any([deadline.signal,statusStop.signal]);const timer=setTimeout(()=>deadline.abort(),statusTimeoutMs);let removeAbort=()=>{};const interrupted=new Promise(resolve=>{const cancel=()=>{clearTimeout(timer);resolve(unavailableStatus(item,closed?"Connector hub is inactive.":"Source status timed out."))};if(signal.aborted)cancel();else{signal.addEventListener("abort",cancel,{once:true});removeAbort=()=>signal.removeEventListener("abort",cancel)}});const operation=Promise.resolve().then(()=>admitted("probe",item.info.source,{[`provider:${item.info.source}`]:1},()=>signal.aborted?businessError("aborted","Source metadata inspection was cancelled.","plugin"):item.status({signal}),signal));const observed=operation.then(result2=>"ok"in result2?{...result2.ok,...item.actions?{actions:true}:{}}:unavailableStatus(item,"err"in result2?result2.err.message:"Source state was not confirmed."),()=>unavailableStatus(item,"Source status failed."));const result=Promise.race([observed,interrupted]);statusProbes.set(item,{epoch,result});const settled=()=>{clearTimeout(timer);removeAbort();if(statusProbes.get(item)?.result===result)statusProbes.delete(item)};void operation.then(settled,settled);return result}const retentionFailure=(item,options)=>options?.retention!==void 0&&options.retention!=="transient"?businessError("invalid_argument","Unsupported connector result retention policy.","plugin"):(options?.retention==="transient"||isTransientConnectorAction())&&item?.requiresPersistentPayloads?fail("This source requires persistent payload storage and has no qualified transient operation."):void 0;function observe(source,usable){if(!dependencies.availabilityMetrics||usability.get(source)===usable)return Promise.resolve();const task=(async()=>{try{const saved=await dependencies.metrics?.()?.record({operation:"connector.usable",source,outcome:usable?"ok":"cancelled",durationMs:0,internal:true});if(saved&&"ok"in saved&&saved.ok.recorded)usability.set(source,usable)}catch{}})();observations.add(task);void task.finally(()=>observations.delete(task));return task}async function observeResult(source,result,enabled){if(!enabled)return observe(source,false);const outcome=usageOutcome(result);if(outcome==="ok"||outcome==="empty")await observe(source,true);else if(outcome==="fault"||outcome==="auth-blocked")await observe(source,false)}const service={hasSource:source=>provider(source)!==void 0,describe:source=>{const info=provider(source)?.info;return info?structuredClone(info):void 0},...dependencies.metrics?{queryMetrics:"owned"}:{},register(item){if(closed)throw Error("Connector hub is inactive.");if(!/^[a-z][a-z0-9-]{0,63}$/.test(item.info.source))throw Error("Invalid source identity.");if(sources.has(item.info.source))throw Error("Duplicate connector source.");sources.set(item.info.source,item);sourceEpochs.set(item.info.source,(sourceEpochs.get(item.info.source)??0)+1);return()=>{if(sources.get(item.info.source)===item){sources.delete(item.info.source);sourceEpochs.set(item.info.source,(sourceEpochs.get(item.info.source)??0)+1);authorization.withdraw(item);void observe(item.info.source,false)}}},replaceDeferred(expected,item){const source=expected.info.source;if(closed||expected.registration!=="deferred"||item.registration==="deferred"||item.info.source!==source||sources.get(source)!==expected)return void 0;sources.set(source,item);sourceEpochs.set(source,(sourceEpochs.get(source)??0)+1);return()=>{if(sources.get(source)===item){sources.delete(source);sourceEpochs.set(source,(sourceEpochs.get(source)??0)+1);authorization.withdraw(item);void observe(source,false)}}},async status(options){if(closed)return businessError("unavailable","Connector hub is inactive.","plugin");if(options?.signal?.aborted)return businessError("aborted","Source status inspection was cancelled.","plugin");const states=Promise.all([...sources.values()].map(async item=>{const epoch=sourceEpochs.get(item.info.source),state=await probeStatus(item);return provider(item.info.source)===item&&sourceEpochs.get(item.info.source)===epoch?state:unavailableStatus(item,"Source was disabled before its status reply.")}));let removeAbort=()=>{};const cancelled=new Promise(resolve=>{if(options?.signal){const cancel=()=>resolve(businessError("aborted","Source status inspection was cancelled.","plugin"));options.signal.addEventListener("abort",cancel,{once:true});removeAbort=()=>options.signal.removeEventListener("abort",cancel)}});try{const result=await Promise.race([states.then(ok),cancelled]);return closed?businessError("unavailable","Connector hub is inactive.","plugin"):result}finally{removeAbort()}},async connect(source,options){options={...options,automatic:options?.automatic===true};const item=provider(source);if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(options.savedAccessOnly&&!item.supportsSavedReconnect)return businessError("failed_precondition","This source cannot reconnect using saved access.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;return withTransientConnectorAction(options?.retention==="transient",()=>admitted("connect",source,providerNeeds(source,{worker:1,[`refresh:${source}`]:1}),()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);await trace.step("source_selected","completed");await trace.step("authorization_started","started");const started=performance.now();let result;try{result=await item.connect(options)}catch(error){await authorization.immediate(item,businessError(options?.signal?.aborted?"aborted":"unavailable","Connection failed.","plugin"),started);throw error}if(provider(source)!==item){result=businessError("unavailable","Source was disabled.","plugin");await authorization.immediate(item,result,started,"source_disabled");return result}if("ok"in result&&result.ok.source!==source)result=businessError("data_loss","Mismatched connection source.","plugin");if("ok"in result){jobs.set(result.ok.id,item);await authorization.track(item,result,started)}else await authorization.immediate(item,result,started);return result},authorization.currentFlow(item)),options?.signal))},job(id){const item=jobs.get(id);if(!item)return businessError("not_found","Unknown connector connection job.","plugin");if(provider(item.info.source)!==item)return businessError("unavailable","Source was disabled.","plugin");const result=item.job(id);authorization.observe(item,id,result);return result},cancelJob(id,source){const tracked=jobs.get(id),item=tracked??(source?provider(source):void 0);if(!item)return businessError("not_found","Unknown connector connection job.","plugin");if(source&&item.info.source!==source)return businessError("not_found","Unknown connector connection job.","plugin");if(provider(item.info.source)!==item)return businessError("unavailable","Source was disabled.","plugin");return item.cancelJob?.(id)},async settleObservations(options){if(options?.closing)await authorization.close();else await authorization.settle();await Promise.allSettled([...observations])},async check(source,options){const item=provider(source);if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Source readiness was cancelled.","plugin");try{const result=item.check?await withTransientConnectorAction(options?.retention==="transient",()=>admitted("check",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.check(options),options?.signal)):await service.read(source,{limit:1},options).then(result2=>"ok"in result2?ok({source,basis:"read",operation:{state:"succeeded",returned:result2.ok.returned,...result2.ok.evidence?{evidence:result2.ok.evidence}:{}}}):"empty"in result2?ok({source,basis:"read",operation:{state:"succeeded",returned:0}}):result2);if(provider(source)!==item)return businessError("unavailable","Source was disabled before readiness delivery.","plugin");if(options?.signal?.aborted)return businessError("aborted","Source readiness was cancelled.","plugin");if("err"in result)return result;if(!("ok"in result))return businessError("data_loss","Source did not provide readiness metadata.","plugin");return readiness(source,result.ok)}catch{return businessError(options?.signal?.aborted?"aborted":"unavailable","Source readiness did not complete.","plugin")}},async read(source,request={},options){const item=provider(source);const run=()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);if(dependencies.metrics)await trace.step("read_started","started");const started=performance.now();let disabled=false;const execute=async()=>{if(!item)return fail("Source is not enabled: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(provider(source)!==item){disabled=true;return businessError("unavailable","Source was disabled before the query.","plugin")}const retention=retentionFailure(item,options);if(retention)return retention;const invalid=validateRead(request,item.info.readById?["fileId"]:[]);if(invalid)return invalid;try{const result2=await item.read(request,options);if(provider(source)!==item){disabled=true;return businessError("unavailable","Source was disabled during the query.","plugin")}if("ok"in result2&&(result2.ok.source!==source||result2.ok.returned!==result2.ok.records.length||result2.ok.returned>(request.limit??1)))return businessError("data_loss","Source returned invalid or unbounded records.","plugin");return result2}catch{return businessError(options?.signal?.aborted?"aborted":"unavailable","Connector query did not complete.","plugin")}};const result=await execute();try{const metrics=dependencies.metrics?.();if(metrics){const summary=usageResultSummary(result),errorCategory=usageErrorCategory(result);await metrics.record({operation:"connector.read",outcome:disabled?"cancelled":usageOutcome(result),durationMs:performance.now()-started,internal:options?.internalTelemetry??false,...item?{source:item.info.source}:{},..."err"in result?{code:result.err.code}:{},...summary?{result:summary}:{},...errorCategory?{errorCategory}:{}})}}catch{}await trace.step("read_verified","err"in result?result.err.code==="aborted"?"cancelled":"failed":"ok"in result||"empty"in result?"completed":"unknown","ok"in result?{count:result.ok.returned}:"empty"in result?{count:0}:{});if(item)await observeResult(source,result,provider(source)===item);return item&&provider(source)!==item?businessError("unavailable","Source was disabled before query delivery.","plugin"):result});const feedback=dependencies.feedback?.();return withTransientConnectorAction(options?.retention==="transient",()=>admitted("read",source,providerNeeds(source,{worker:1}),()=>feedback?feedback.run(source,run):run(),options?.signal))},close(){if(!closing){closed=true;statusStop.abort();for(const source of sources.keys())void observe(source,false);sources.clear();jobs.clear();informationSnapshots.clear();fileSnapshots.clear();closing=(async()=>{await authorization.close();await Promise.allSettled([...observations])})()}return closing},async catalog(source,input,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source);if(!item)return fail("Source is not installed or enabled: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(!item.actions){const action=sharedReadDiscovery(item.info);return ok({source,actions:[{name:action.name,effect:action.effect,operation:action.operation}],total:1,discovery:"Request method=connector.read for the shared action schema; execute it with operation=action, not connector.invoke."})}const result=await admitted("catalog",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.catalog(input),options?.signal);return provider(source)===item?result:businessError("unavailable","Source was disabled before its catalog reply.","plugin")})},async method(source,name2,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source);if(!item)return fail("Source is not installed or enabled: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");if(!item.actions)return name2==="connector.read"?ok(sharedReadDiscovery(item.info)):fail("This source has no installed action schema: "+name2);const result=await admitted("method",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.method(name2),options?.signal);return provider(source)===item?result:businessError("unavailable","Source was disabled before its schema reply.","plugin")})},async review(source,name2,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{const item=provider(source),epoch=sourceEpochs.get(source)??0;if(!item?.actions)return fail("This source has no installed action schema: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;const result=await admitted("review",source,providerNeeds(source,{probe:1,discovery:1}),()=>item.actions.method(name2),options?.signal);if(provider(source)!==item)return businessError("unavailable","Source was disabled before its schema reply.","plugin");if(!("ok"in result))return result;return actionReview(source,name2,epoch,result.ok)})},async invokeReviewed(review,input,options){return withTransientConnectorAction(options?.retention==="transient",async()=>{if(!review||typeof review!=="object"||typeof review.source!=="string"||typeof review.name!=="string"||typeof review.revision!=="string")return fail("A reviewed action handle is required.");const item=provider(review.source),epoch=sourceEpochs.get(review.source)??0;if(!item?.actions)return fail("This source has no installed action port: "+review.source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const retention=retentionFailure(item,options);if(retention)return retention;const current=await admitted("invoke-review",review.source,providerNeeds(review.source,{probe:1,discovery:1}),()=>item.actions.method(review.name),options?.signal);if(provider(review.source)!==item)return businessError("unavailable","Source was disabled before action review.","plugin");if(!("ok"in current))return current;if(!sameActionReview(review,epoch,current.ok))return businessError("failed_precondition","Provider action schema changed after review; inspect the new schema before dispatch.","plugin");const valid=validateReviewedInput(review,input);if(!("ok"in valid))return valid;return service.invoke(review.source,review.name,input,options)})},async invoke(source,name2,input,options){const item=provider(source);if(!item?.actions)return fail("This source has no installed action port: "+source);if(item.registration==="deferred")return businessError("failed_precondition","Source requires setup and restart.","plugin");const run=()=>withFeedbackFlow(source,async()=>{const trace=createTraceRecorder(dependencies.metrics,source);await trace.step("invoke_started","started");if(provider(source)!==item){await trace.step("invoke_finished","failed",{reason:"source_disabled"});return businessError("unavailable","Source was disabled before action dispatch.","plugin")}const retention=retentionFailure(item,options);if(retention){await trace.step("invoke_finished","failed",{reason:"provider_error"});return retention}const started=performance.now();let result;try{const reply=await admitted("invoke",source,providerNeeds(source,{worker:1}),()=>{if(provider(source)!==item)return businessError("unavailable","Source was disabled before action dispatch.","plugin");if(!item.actions.reportsActionAccess){try{options?.onActionAccess?.("legacy")}catch{}const legacyOptions=options?{...options}:void 0;if(legacyOptions)delete legacyOptions.onActionAccess;return item.actions.invoke(name2,input,legacyOptions)}return item.actions.invoke(name2,input,options)},options?.signal);result=provider(source)===item?reply:businessError("unavailable","Source was disabled before its reply.","plugin")}catch{result=businessError(options?.signal?.aborted?"aborted":"unavailable","Source action did not finish.","plugin")}let outcome="unknown";try{outcome=usageOutcome(result);const metrics=dependencies.metrics?.();if(metrics){const summary=usageResultSummary(result),errorCategory=usageErrorCategory(result);await metrics.record({operation:"connector.invoke",source,outcome,durationMs:performance.now()-started,internal:true,..."err"in result?{code:result.err.code}:{},...summary?{result:summary}:{},...errorCategory?{errorCategory}:{}})}}catch{}await trace.step("invoke_finished",outcome==="ok"||outcome==="empty"?"completed":outcome==="cancelled"?"cancelled":outcome==="auth-blocked"?"waiting":outcome==="fault"||outcome==="invalid"?"failed":"unknown");await observeResult(source,result,provider(source)===item);return provider(source)===item?result:businessError("unavailable","Source was disabled before action delivery.","plugin")});const feedback=dependencies.feedback?.();return withTransientConnectorAction(options?.retention==="transient",()=>feedback?feedback.run(source,run):run())},async captureInformation(review,input,options){purgeSnapshots();if(!review||typeof review!=="object"||!review.schema||!shareReadSchema(review.schema))return businessError("permission_denied","Share snapshots require an explicitly read-only Connector Action.","plugin");const item=provider(review.source),epoch=sourceEpochs.get(review.source)??0;if(!item)return fail("Source is not enabled: "+review.source);const result=await service.invokeReviewed(review,input,options);if(!("ok"in result))return result;if(provider(review.source)!==item||sourceEpochs.get(review.source)!==epoch)return businessError("unavailable","Source changed before its information snapshot was retained.","plugin");const fingerprint=informationFingerprint(result.ok);if(!("ok"in fingerprint))return fingerprint;const handle=randomUUID(),capturedAt=new Date().toISOString(),expiresAt=new Date(Date.now()+SNAPSHOT_TTL_MS).toISOString();const snapshot={kind:"information",source:review.source,name:review.name,handle,capturedAt,expiresAt,...fingerprint.ok};let savedReview,savedInput;try{savedReview=structuredClone(review);savedInput=structuredClone(input)}catch{return businessError("invalid_argument","Connector snapshot input is not cloneable.","plugin")}informationSnapshots.set(handle,{public:snapshot,review:savedReview,input:savedInput,provider:item,epoch});return ok(snapshot)},async verifyInformation(snapshot,options){purgeSnapshots();if(!validInformationHandle(snapshot))return businessError("invalid_argument","Pass one Connector information snapshot handle.","plugin");const stored=informationSnapshots.get(snapshot.handle);if(!stored||!samePublic(stored.public,snapshot))return fail("Connector information snapshot is missing, expired or changed.");if(provider(stored.public.source)!==stored.provider||sourceEpochs.get(stored.public.source)!==stored.epoch)return fail("Connector source changed after preview; review the Share again.");const result=await service.invokeReviewed(stored.review,stored.input,options);if(!("ok"in result))return result;const current=informationFingerprint(result.ok);if(!("ok"in current))return current;if(current.ok.sha256!==stored.public.sha256||current.ok.bytes!==stored.public.bytes)return businessError("aborted","Connector information changed after preview; review the Share again.","plugin");return ok(stored.public)},async inspectFile(source,input,options){purgeSnapshots();if(!input||typeof input.id!=="string"||!input.id||Buffer.byteLength(input.id)>1024)return businessError("invalid_argument","Connector file inspection requires one provider identity.","plugin");const item=provider(source),epoch=sourceEpochs.get(source)??0;if(!item?.fileSnapshots)return fail("This source does not provide file snapshots: "+source);const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Connector file inspection was cancelled.","plugin");const result=await withTransientConnectorAction(options?.retention==="transient",()=>admitted("file-inspect",source,providerNeeds(source,{worker:1}),()=>item.fileSnapshots.inspect(input,options),options?.signal));if(provider(source)!==item||sourceEpochs.get(source)!==epoch)return businessError("unavailable","Source changed before its file snapshot was retained.","plugin");if(!("ok"in result))return result;const checked=validProviderFile(result.ok,source);if(!("ok"in checked))return checked;let retained;try{retained=structuredClone(checked.ok)}catch{return businessError("data_loss","Connector file snapshot metadata is not retainable.","plugin")}const handle=randomUUID(),expiresAt=new Date(Date.now()+SNAPSHOT_TTL_MS).toISOString(),snapshot=publicFileSnapshot(handle,retained,expiresAt);fileSnapshots.set(handle,{public:snapshot,file:retained,provider:item,epoch});return ok(snapshot)},async materializeFile(snapshot,options){purgeSnapshots();if(!validFileHandle(snapshot))return businessError("invalid_argument","Pass one Connector file snapshot handle.","plugin");const stored=fileSnapshots.get(snapshot.handle);if(!stored||!samePublic(stored.public,snapshot))return fail("Connector file snapshot is missing, expired or changed.");const item=provider(stored.public.source);if(item!==stored.provider||sourceEpochs.get(stored.public.source)!==stored.epoch||!item.fileSnapshots)return fail("Connector source changed after preview; review the Share again.");const retention=retentionFailure(item,options);if(retention)return retention;if(options?.signal?.aborted)return businessError("aborted","Connector file materialization was cancelled.","plugin");const result=await withTransientConnectorAction(options?.retention==="transient",()=>admitted("file-materialize",stored.public.source,providerNeeds(stored.public.source,{worker:1}),()=>item.fileSnapshots.materialize(stored.file,options),options?.signal));if(provider(stored.public.source)!==item||sourceEpochs.get(stored.public.source)!==stored.epoch)return businessError("unavailable","Source changed while its file snapshot was materialized.","plugin");if(!("ok"in result))return result;const checked=validProviderFile(result.ok.file,stored.public.source);if(!("ok"in checked))return checked;if(!sameProviderFile(stored.file,checked.ok)||!(result.ok.content instanceof Uint8Array)||result.ok.mimeType!==stored.public.mimeType||result.ok.size!==result.ok.content.byteLength||result.ok.size<0)return businessError("data_loss","Connector file bytes did not match the inspected snapshot.","plugin");return ok({file:stored.public,content:result.ok.content,mimeType:result.ok.mimeType,size:result.ok.size})}};return instrumentConnectorHub(service,dependencies.metrics,id=>jobs.get(id)?.info.source)}export async function apply(ctx){const feedback=createConnectionFeedback({store:()=>ctx.get("zortexSqliteVault")?.createPrivateStore("connection-feedback"),connection:async source=>{const local=ctx.get("zortexLocalSourceRegistry")?.get(source);if(local)return ok(local);const level1=ctx.get("zortexLevel1Connectors");const namespace=source==="figma"&&level1?.provider("figma")?.spec.auth.kind==="fields"?"figma--pat":source;const result=await ctx.zortexVaultStore.connection(namespace);return namespace!==source&&"ok"in result&&result.ok?ok({...result.ok,source}):result}});ctx.provide("zortexConnectionFeedback",feedback);const admission=createResourceAdmission(),http=await createConnectorHttp({admission}),hub=createConnectorHub({metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>feedback,availabilityMetrics:true,admission}),enrollment=createEnrollment({vault:ctx.zortexVaultStore,transport:http.fetch,metrics:()=>ctx.get("zortexTelemetry"),feedback:()=>feedback});ctx.provide("zortexResourceAdmission",admission);ctx.provide("zortexConnectorHttp",http.fetch);ctx.provide("zortexConnectorHub",hub);ctx.provide("zortexConnectorEnrollment",enrollment);ctx.effect(()=>()=>hub.close());ctx.effect(()=>async()=>{await enrollment.close();await http.close();admission.close()})}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{execFile}from"node:child_process";import{promisify}from"node:util";import{win32}from"node:path";const TIMEOUT_MS=2e3,MAX_BYTES=32768;const script="$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();$folders=@();foreach($name in @('MyDocuments','DesktopDirectory')){$path=[Environment]::GetFolderPath($name);if($path){$folders+=$path}};try{$shell=New-Object -ComObject Shell.Application;$folder=$shell.NameSpace('shell:Downloads');if($folder){$folders+=$folder.Self.Path}}catch{};[PSCustomObject]@{sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value;folders=@($folders)}|ConvertTo-Json -Compress";const execute=async(command,options)=>(await promisify(execFile)("powershell.exe",["-NoProfile","-NonInteractive","-Command",command],{...options,windowsHide:true})).stdout;export async function readNativeUserFileRoots(native,options={}){if((options.platform??process.platform)!=="win32")return void 0;if(options.signal?.aborted)return[];try{const raw=await(options.execute??execute)(script,{timeout:TIMEOUT_MS,maxBuffer:MAX_BYTES,...options.signal?{signal:options.signal}:{}});if(options.signal?.aborted||Buffer.byteLength(raw,"utf8")>MAX_BYTES)return[];const result=JSON.parse(raw);if(result.sid!==native.subject||!Array.isArray(result.folders)||result.folders.length>3)return[];const home=win32.resolve(native.home).toLowerCase(),seen=new Set,roots=[];for(const path of result.folders){if(typeof path!=="string"||!path||path!==path.trim()||path.length>4096||/[\u0000-\u001f\u007f-\u009f]/u.test(path)||!win32.isAbsolute(path))continue;const canonical=win32.resolve(path),key=canonical.toLowerCase();if(key===home||canonical===win32.resolve(path,"..")||seen.has(key))continue;seen.add(key);roots.push(path)}return roots}catch{return[]}}
|
|
@@ -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()}}
|