@zortexhq/indra-v2.5 0.4.0 → 0.4.2
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 +5 -5
- package/bin/codex-postinstall.mjs +1 -1
- package/dist/action-effect.js +1 -0
- package/dist/action-read-progress.js +1 -1
- package/dist/actions-catalog.js +1 -0
- package/dist/auto-sync.js +1 -1
- package/dist/auto-update.js +1 -1
- package/dist/automatic-updates.js +1 -0
- package/dist/bundled-handbook.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/codex-install.js +1 -1
- package/dist/codex-setup.js +1 -1
- package/dist/computer-use-setup.js +1 -0
- package/dist/default-root.js +1 -1
- package/dist/documentation-action.js +1 -0
- package/dist/gateway.js +1 -1
- package/dist/imessage-sync.js +1 -1
- package/dist/local-cloud-policy.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mcp.js +1 -3
- package/dist/native-connect.js +1 -1
- package/dist/native-level1-setup.js +1 -1
- package/dist/native-ollama-discovery.js +1 -0
- package/dist/native-vault-discovery.js +1 -1
- package/dist/onboard-cli.js +1 -1
- package/dist/onboard.js +1 -1
- package/dist/onboarding.js +1 -1
- package/dist/profile.js +1 -1
- package/dist/public-tool.js +4 -1
- package/dist/read-route.js +1 -1
- package/dist/recovery-authorization-url.js +1 -1
- package/dist/recovery-progress.js +1 -1
- package/dist/recovery.js +1 -1
- package/dist/resident-autopilot.js +1 -0
- 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 +2 -2
- package/dist/resident-runtime-identity.js +1 -1
- package/dist/resident-startup-state.js +1 -0
- package/dist/resident-telemetry.js +1 -1
- package/dist/shared-action-schemas.js +1 -0
- package/dist/source-data.js +1 -1
- package/dist/storage-compatibility.js +1 -0
- package/dist/supervised-sync.js +1 -1
- package/dist/tools.js +1 -1
- package/dist/update-check.js +1 -1
- package/dist/update-cli.js +1 -1
- package/dist/update-command.js +1 -1
- package/dist/update-recovery.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/durable-dispatcher.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/job-contract.js +1 -1
- package/node_modules/@zortexhq/plugin-autopilot/dist/api.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/cua.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/feedback.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/index.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/python-runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/service.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/worker.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/package.json +23 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/LICENSE +21 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/PROVENANCE.json +38 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/__init__.py +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/agent.py +178 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/browser.py +13 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/indra.patch +57 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/model.py +180 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/questions.py +26 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/transport.py +70 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/strategies.py +154 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/worker.py +260 -0
- package/node_modules/@zortexhq/plugin-connector-activitywatch/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/action-outcome.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/connectors.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/authorization-metrics.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/native-principal.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/connector.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/compounds.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/action-content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-server.js +6 -6
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-native-process.mjs +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/macos-contacts-server.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-apple-native.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/public-data/specs.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-netease/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/mail-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/auth-state.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/content.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/full-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/api/action-schemas.js +1 -0
- package/node_modules/@zortexhq/plugin-context-share/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/share.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
- 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-google-auth/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/api/execution-scope.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/api/stdio-transport.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/windows-job.js +1 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/index.js +4 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/session-store.js +10 -0
- package/node_modules/@zortexhq/plugin-product-account/dist/storage.js +1 -0
- package/node_modules/@zortexhq/plugin-product-account/package.json +5 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/public-result-visibility.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/credentials.js +3 -3
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/keychain.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/public-visibility.js +7 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/recovery-guard.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +2 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-worker.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +2 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql.js +1 -1
- package/package.json +13 -7
- package/profiles/core.yml +2 -0
- package/release-provenance.json +48 -41
- package/update-manifest.json +573 -296
- package/dist/content-find.js +0 -2
- package/dist/find-snapshots.js +0 -1
- package/dist/match-excerpt.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";const id={type:"string",minLength:1,maxLength:2048},top={type:"integer",minimum:1,maximum:100},object={type:"object",minProperties:1,maxProperties:64};const methods=[{name:"teams.identity",description:"Read the authorized Microsoft identity.",httpMethod:"GET",effect:"read",scopes:["User.Read"],inputSchema:{type:"object",properties:{},additionalProperties:false}},{name:"teams.teams.list",description:"List joined teams.",httpMethod:"GET",effect:"read",scopes:["Team.ReadBasic.All"],inputSchema:{type:"object",properties:{top},additionalProperties:false}},{name:"teams.channels.list",description:"List channels in one team.",httpMethod:"GET",effect:"read",scopes:["Channel.ReadBasic.All"],inputSchema:{type:"object",properties:{teamId:id,top},required:["teamId"],additionalProperties:false}},{name:"teams.members.list",description:"List members of one team.",httpMethod:"GET",effect:"read",scopes:["TeamMember.Read.All"],inputSchema:{type:"object",properties:{teamId:id,top},required:["teamId"],additionalProperties:false}},{name:"teams.chats.list",description:"List chats.",httpMethod:"GET",effect:"read",scopes:["Chat.ReadBasic"],inputSchema:{type:"object",properties:{top},additionalProperties:false}},{name:"teams.chat.messages.list",description:"List messages in one chat.",httpMethod:"GET",effect:"read",scopes:["Chat.Read"],inputSchema:{type:"object",properties:{chatId:id,top},required:["chatId"],additionalProperties:false}},{name:"teams.chat.messages.get",description:"Read one chat message.",httpMethod:"GET",effect:"read",scopes:["Chat.Read"],inputSchema:{type:"object",properties:{chatId:id,messageId:id},required:["chatId","messageId"],additionalProperties:false}},{name:"teams.chat.messages.create",description:"Create a chat message.",httpMethod:"POST",effect:"write",scopes:["ChatMessage.Send"],inputSchema:{type:"object",properties:{chatId:id,message:object},required:["chatId","message"],additionalProperties:false}},{name:"teams.chat.messages.update",description:"Update one chat message authored by the account.",httpMethod:"PATCH",effect:"write",scopes:["Chat.ReadWrite"],inputSchema:{type:"object",properties:{chatId:id,messageId:id,message:object},required:["chatId","messageId","message"],additionalProperties:false}},{name:"teams.channel.messages.list",description:"List root messages in one channel.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,top},required:["teamId","channelId"],additionalProperties:false}},{name:"teams.channel.messages.get",description:"Read one channel message.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,messageId:id},required:["teamId","channelId","messageId"],additionalProperties:false}},{name:"teams.channel.replies.list",description:"List replies to one channel message.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,messageId:id,top},required:["teamId","channelId","messageId"],additionalProperties:false}},{name:"teams.channel.messages.create",description:"Create a root channel message.",httpMethod:"POST",effect:"write",scopes:["ChannelMessage.Send"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,message:object},required:["teamId","channelId","message"],additionalProperties:false}},{name:"teams.channel.files.folder",description:"Read the SharePoint folder backing one channel.",httpMethod:"GET",effect:"read",scopes:["Files.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id},required:["teamId","channelId"],additionalProperties:false}},{name:"teams.meeting.recordings.list",description:"List recordings for one online meeting.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingRecording.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,top},required:["userId","meetingId"],additionalProperties:false}},{name:"teams.meeting.transcripts.list",description:"List transcripts for one online meeting.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingTranscript.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,top},required:["userId","meetingId"],additionalProperties:false}},{name:"teams.meeting.transcripts.content",description:"Read one meeting transcript as text.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingTranscript.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,transcriptId:id},required:["userId","meetingId","transcriptId"],additionalProperties:false}}];const fail=(code,message)=>businessError(code,message,"plugin");const params=input=>input&&typeof input==="object"&&!Array.isArray(input)&&input.params&&typeof input.params==="object"&&!Array.isArray(input.params)?input.params:{};const segment=value=>{if(typeof value!=="string"||!value||value.length>2048)throw Error("invalid_identifier");return encodeURIComponent(value)};const bounded=value=>{const json=JSON.stringify(value);if(json.length>1e6)throw Error("response_too_large");return value};function hasScope(granted,required){const accepted=required==="Chat.ReadBasic"?["Chat.ReadBasic","Chat.Read","Chat.ReadWrite"]:required==="Chat.Read"?["Chat.Read","Chat.ReadWrite"]:[required];return accepted.some(value=>granted.includes(value)||granted.includes("https://graph.microsoft.com/"+value))}export function createTeamsActions(resolveGrant,clientFactory){return{catalog(){return ok({source:"teams",total:methods.length,methods:methods.map(({inputSchema:_,scopes:__,...row})=>({...row,level:1}))})},method(name){const row=methods.find(method=>method.name===name);return row?ok({...structuredClone(row),level:1}):fail("not_found",`Teams has no action ${String(name).slice(0,100)}.`)},async invoke(name,input,options){try{const row=methods.find(method2=>method2.name===name);if(!row)return fail("not_found",`Teams has no action ${String(name).slice(0,100)}.`);let signal=options?.signal??new AbortController().signal;const grant=await resolveGrant(signal);if(!("ok"in grant))return grant;if(row.scopes.some(scope=>!hasScope(grant.ok.scopes,scope)))return fail("permission_denied","Reconnect Teams with the scopes required by this Action.");const p=params(input);let path="/me",method="get",body;if(name==="teams.teams.list")path="/me/joinedTeams";else if(name==="teams.channels.list")path=`/teams/${segment(p.teamId)}/channels`;else if(name==="teams.members.list")path=`/teams/${segment(p.teamId)}/members`;else if(name==="teams.chats.list")path="/me/chats";else if(name==="teams.chat.messages.list")path=`/chats/${segment(p.chatId)}/messages`;else if(name==="teams.chat.messages.get")path=`/chats/${segment(p.chatId)}/messages/${segment(p.messageId)}`;else if(name==="teams.chat.messages.create"){path=`/chats/${segment(p.chatId)}/messages`;method="post";body=p.message}else if(name==="teams.chat.messages.update"){path=`/chats/${segment(p.chatId)}/messages/${segment(p.messageId)}`;method="patch";body=p.message}else if(name==="teams.channel.messages.list")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages`;else if(name==="teams.channel.messages.get")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages/${segment(p.messageId)}`;else if(name==="teams.channel.replies.list")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages/${segment(p.messageId)}/replies`;else if(name==="teams.channel.messages.create"){path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages`;method="post";body=p.message}else if(name==="teams.channel.files.folder")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/filesFolder`;else if(name==="teams.meeting.recordings.list")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/recordings`;else if(name==="teams.meeting.transcripts.list")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/transcripts`;else if(name==="teams.meeting.transcripts.content")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/transcripts/${segment(p.transcriptId)}/content`;signal=grant.ok.signal??signal;const checked=await grant.ok.check?.(signal);if(checked&&!("ok"in checked))return checked;let request=clientFactory(grant.ok.accessToken,signal).api(path);if(p.top!==void 0)request=request.top(Math.min(100,Math.max(1,Number(p.top))));const
|
|
1
|
+
import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{actionNotApplied,actionOutcome}from"@zortexhq/plugin-connector-core/api";const id={type:"string",minLength:1,maxLength:2048},top={type:"integer",minimum:1,maximum:100},object={type:"object",minProperties:1,maxProperties:64};const methods=[{name:"teams.identity",description:"Read the authorized Microsoft identity.",httpMethod:"GET",effect:"read",scopes:["User.Read"],inputSchema:{type:"object",properties:{},additionalProperties:false}},{name:"teams.teams.list",description:"List joined teams.",httpMethod:"GET",effect:"read",scopes:["Team.ReadBasic.All"],inputSchema:{type:"object",properties:{top},additionalProperties:false}},{name:"teams.channels.list",description:"List channels in one team.",httpMethod:"GET",effect:"read",scopes:["Channel.ReadBasic.All"],inputSchema:{type:"object",properties:{teamId:id,top},required:["teamId"],additionalProperties:false}},{name:"teams.members.list",description:"List members of one team.",httpMethod:"GET",effect:"read",scopes:["TeamMember.Read.All"],inputSchema:{type:"object",properties:{teamId:id,top},required:["teamId"],additionalProperties:false}},{name:"teams.chats.list",description:"List chats.",httpMethod:"GET",effect:"read",scopes:["Chat.ReadBasic"],inputSchema:{type:"object",properties:{top},additionalProperties:false}},{name:"teams.chat.messages.list",description:"List messages in one chat.",httpMethod:"GET",effect:"read",scopes:["Chat.Read"],inputSchema:{type:"object",properties:{chatId:id,top},required:["chatId"],additionalProperties:false}},{name:"teams.chat.messages.get",description:"Read one chat message.",httpMethod:"GET",effect:"read",scopes:["Chat.Read"],inputSchema:{type:"object",properties:{chatId:id,messageId:id},required:["chatId","messageId"],additionalProperties:false}},{name:"teams.chat.messages.create",description:"Create a chat message.",httpMethod:"POST",effect:"write",scopes:["ChatMessage.Send"],inputSchema:{type:"object",properties:{chatId:id,message:object},required:["chatId","message"],additionalProperties:false}},{name:"teams.chat.messages.update",description:"Update one chat message authored by the account.",httpMethod:"PATCH",effect:"write",scopes:["Chat.ReadWrite"],inputSchema:{type:"object",properties:{chatId:id,messageId:id,message:object},required:["chatId","messageId","message"],additionalProperties:false}},{name:"teams.channel.messages.list",description:"List root messages in one channel.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,top},required:["teamId","channelId"],additionalProperties:false}},{name:"teams.channel.messages.get",description:"Read one channel message.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,messageId:id},required:["teamId","channelId","messageId"],additionalProperties:false}},{name:"teams.channel.replies.list",description:"List replies to one channel message.",httpMethod:"GET",effect:"read",scopes:["ChannelMessage.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,messageId:id,top},required:["teamId","channelId","messageId"],additionalProperties:false}},{name:"teams.channel.messages.create",description:"Create a root channel message.",httpMethod:"POST",effect:"write",scopes:["ChannelMessage.Send"],inputSchema:{type:"object",properties:{teamId:id,channelId:id,message:object},required:["teamId","channelId","message"],additionalProperties:false}},{name:"teams.channel.files.folder",description:"Read the SharePoint folder backing one channel.",httpMethod:"GET",effect:"read",scopes:["Files.Read.All"],inputSchema:{type:"object",properties:{teamId:id,channelId:id},required:["teamId","channelId"],additionalProperties:false}},{name:"teams.meeting.recordings.list",description:"List recordings for one online meeting.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingRecording.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,top},required:["userId","meetingId"],additionalProperties:false}},{name:"teams.meeting.transcripts.list",description:"List transcripts for one online meeting.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingTranscript.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,top},required:["userId","meetingId"],additionalProperties:false}},{name:"teams.meeting.transcripts.content",description:"Read one meeting transcript as text.",httpMethod:"GET",effect:"read",scopes:["OnlineMeetingTranscript.Read.All"],inputSchema:{type:"object",properties:{userId:id,meetingId:id,transcriptId:id},required:["userId","meetingId","transcriptId"],additionalProperties:false}}];const fail=(code,message)=>businessError(code,message,"plugin");const params=input=>input&&typeof input==="object"&&!Array.isArray(input)&&input.params&&typeof input.params==="object"&&!Array.isArray(input.params)?input.params:{};const segment=value=>{if(typeof value!=="string"||!value||value.length>2048)throw Error("invalid_identifier");return encodeURIComponent(value)};const bounded=value=>{const json=JSON.stringify(value);if(json.length>1e6)throw Error("response_too_large");return value};function hasScope(granted,required){const accepted=required==="Chat.ReadBasic"?["Chat.ReadBasic","Chat.Read","Chat.ReadWrite"]:required==="Chat.Read"?["Chat.Read","Chat.ReadWrite"]:[required];return accepted.some(value=>granted.includes(value)||granted.includes("https://graph.microsoft.com/"+value))}export function createTeamsActions(resolveGrant,clientFactory){return{catalogSnapshot(){return{revision:"installed-v1",complete:true,actions:methods.map(row=>({...row,level:1}))}},catalog(){return ok({source:"teams",total:methods.length,methods:methods.map(({inputSchema:_,scopes:__,...row})=>({...row,level:1}))})},method(name){const row=methods.find(method=>method.name===name);return row?ok({...structuredClone(row),level:1}):fail("not_found",`Teams has no action ${String(name).slice(0,100)}.`)},async invoke(name,input,options){let dispatched=false;const execute=async()=>{try{const row=methods.find(method2=>method2.name===name);if(!row)return fail("not_found",`Teams has no action ${String(name).slice(0,100)}.`);let signal=options?.signal??new AbortController().signal;const grant=await resolveGrant(signal);if(!("ok"in grant))return grant;if(row.scopes.some(scope=>!hasScope(grant.ok.scopes,scope)))return fail("permission_denied","Reconnect Teams with the scopes required by this Action.");const p=params(input);let path="/me",method="get",body;if(name==="teams.teams.list")path="/me/joinedTeams";else if(name==="teams.channels.list")path=`/teams/${segment(p.teamId)}/channels`;else if(name==="teams.members.list")path=`/teams/${segment(p.teamId)}/members`;else if(name==="teams.chats.list")path="/me/chats";else if(name==="teams.chat.messages.list")path=`/chats/${segment(p.chatId)}/messages`;else if(name==="teams.chat.messages.get")path=`/chats/${segment(p.chatId)}/messages/${segment(p.messageId)}`;else if(name==="teams.chat.messages.create"){path=`/chats/${segment(p.chatId)}/messages`;method="post";body=p.message}else if(name==="teams.chat.messages.update"){path=`/chats/${segment(p.chatId)}/messages/${segment(p.messageId)}`;method="patch";body=p.message}else if(name==="teams.channel.messages.list")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages`;else if(name==="teams.channel.messages.get")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages/${segment(p.messageId)}`;else if(name==="teams.channel.replies.list")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages/${segment(p.messageId)}/replies`;else if(name==="teams.channel.messages.create"){path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/messages`;method="post";body=p.message}else if(name==="teams.channel.files.folder")path=`/teams/${segment(p.teamId)}/channels/${segment(p.channelId)}/filesFolder`;else if(name==="teams.meeting.recordings.list")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/recordings`;else if(name==="teams.meeting.transcripts.list")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/transcripts`;else if(name==="teams.meeting.transcripts.content")path=`/users/${segment(p.userId)}/onlineMeetings/${segment(p.meetingId)}/transcripts/${segment(p.transcriptId)}/content`;signal=grant.ok.signal??signal;const checked=await grant.ok.check?.(signal);if(checked&&!("ok"in checked))return checked;let request=clientFactory(grant.ok.accessToken,signal).api(path);if(p.top!==void 0)request=request.top(Math.min(100,Math.max(1,Number(p.top))));if(method!=="get")dispatched=true;const result2=method==="get"?await request.get():method==="post"?await request.post(body):await request.patch(body);const final=await grant.ok.check?.(signal);return final&&!("ok"in final)?final:ok(bounded(result2))}catch(error){const invalid=error instanceof Error&&error.message==="invalid_identifier";return fail(options?.signal?.aborted?"aborted":invalid?"invalid_argument":"unavailable",invalid?"Teams Action requires valid resource identifiers.":"Microsoft Graph Teams Action did not complete.")}};const result=await execute();return dispatched?actionOutcome(result,"unknown"):actionNotApplied(result)}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Client,RetryHandlerOptions}from"@microsoft/microsoft-graph-client";import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{captureSelectedAccount,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{createTeamsActions}from"./actions.js";import{MICROSOFT_AUTHORITY,TEAMS_SCOPE,TEAMS_SCOPES,credentialExpiring,requestMicrosoftToken,teamsClientId}from"./token.js";const defaultClientFactory=(accessToken,signal)=>{const client=Client.init({authProvider:done=>done(null,accessToken),fetchOptions:{signal}});const retry=new RetryHandlerOptions(void 0,void 0,(_delay,_attempt,request,options)=>(typeof request==="string"?options?.method:request.method)==="GET");return{api:path=>client.api(path).middlewareOptions([retry])}};function scopePresent(scopes,required){return scopes.includes(required)||scopes.includes("https://graph.microsoft.com/"+required)}const validToken=value=>typeof value==="string"&&value.length>0&&value.length<=16384&&!/[\s\u0000-\u001f\u007f-\u009f]/u.test(value);const validScopes=value=>Array.isArray(value)&&value.length>0&&value.length<=64&&value.every(scope=>typeof scope==="string"&&/^[\x21-\x7e]{1,512}$/u.test(scope));const sameScopes=(left,right)=>JSON.stringify([...new Set(left)].sort())===JSON.stringify([...new Set(right)].sort());function wait(task,signal){return new Promise((resolve,reject)=>{const cancelled=()=>{signal.removeEventListener("abort",cancelled);reject(signal.reason??Error("Teams operation cancelled."))};signal.addEventListener("abort",cancelled,{once:true});task.then(value=>{signal.removeEventListener("abort",cancelled);resolve(value)},error=>{signal.removeEventListener("abort",cancelled);reject(error)});if(signal.aborted)cancelled()})}export function createTeamsProvider({vault,enrollment,transport=fetch,clientFactory=defaultClientFactory}){const info={source:"teams",label:"Microsoft Teams",group:"Connector / Microsoft",auth:"oauth-browser"},stop=new AbortController;let closed=false,closing;const clientId=teamsClientId();const pending=new Set,connectedJobs=new Map;const fail=(code,message)=>businessError(code,message,"plugin");function track(task){pending.add(task);void task.then(()=>pending.delete(task),()=>pending.delete(task));return task}function authorized(snapshot,accountId){const{binding,grant:grant2,resource,material}=snapshot;if(binding.identity.source!=="teams"||binding.identity.issuer!=="microsoft"||binding.provider!=="microsoft"||binding.identity.subject!==accountId||binding.state!=="connected"||grant2.bindingId!==binding.id||grant2.purpose!=="L1"||grant2.audience!=="microsoft"||grant2.state!=="active"||resource.id!==oauthCredentialResourceId(binding.id)||resource.bindingId!==binding.id||resource.kind!=="oauth"||resource.owner.kind!=="resident"||material.kind!=="oauth")return fail("failed_precondition","Teams requires one verified native resident OAuth binding and L1 grant.");const credential=material.credential;if(!validScopes(grant2.scopes)||!validScopes(credential.scopes)||!sameScopes(grant2.scopes,credential.scopes))return fail("permission_denied","Teams credential scopes do not match the selected grant.");if(!validToken(credential.accessToken)||typeof credential.clientId!=="string"||!/^[\x21-\x7e]{1,512}$/u.test(credential.clientId)||!Number.isFinite(credential.expiresAt)||credential.expiresAt<=0||credential.expiresAt>864e13||credential.refreshToken!==void 0&&!validToken(credential.refreshToken))return fail("failed_precondition","Teams credential material is invalid; reconnect this source.");return ok(credential)}async function resolveGrant(signal){const selected=await captureSelectedAccount(vault,"teams",signal);if(!("ok"in selected))return selected;const authority=selected.ok;if(!vault.bindingCustody)return fail("failed_precondition","Teams operations require verified account custody.");const custody=vault.bindingCustody,resolution=await custody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in resolution))return resolution;if(resolution.ok.kind!=="resolved")return fail("failed_precondition","Select one verified Teams account binding.");const found=await custody.credentialSnapshot(oauthCredentialResourceId(resolution.ok.binding.id),{purpose:"L1",audience:"microsoft"});if(!("ok"in found))return found;let snapshot=found.ok,allowed=authorized(snapshot,authority.accountId);if(!("ok"in allowed))return allowed;async function fence(expected,active,requireFresh=true){const checked=await authority.check(active);if(!("ok"in checked))return checked;const current=await custody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in current))return current;if(current.ok.kind!=="resolved"||current.ok.binding.id!==expected.binding.id||current.ok.binding.revision!==expected.binding.revision)return fail("failed_precondition","Teams account selection changed during the operation.");const resource=await custody.resource(expected.resource.id);if(!("ok"in resource))return resource;if(resource.ok?.revision!==expected.resource.revision||resource.ok.owner.kind!=="resident")return fail("failed_precondition","Teams credential authority changed during the operation.");const credential=authorized(expected,authority.accountId);if(!("ok"in credential))return credential;if(requireFresh&&credential.ok.expiresAt<=Date.now())return fail("failed_precondition","Teams authorization expired during the operation.");return authority.check(active)}try{if(credentialExpiring(allowed.ok)){if(!allowed.ok.refreshToken)return fail("failed_precondition","Teams authorization expired; reconnect this source.");const before2=await fence(snapshot,signal,false);if(!("ok"in before2))return before2;const ownerSignal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);const renewed=await track(custody.refreshResource(snapshot,{kind:"resident"},async current=>{const material=authorized(current,authority.accountId);if(!("ok"in material))return material;const checked=await fence(current,ownerSignal,false);if(!("ok"in checked))return checked;if(!material.ok.refreshToken)return fail("failed_precondition","Teams authorization expired; reconnect this source.");try{ownerSignal.throwIfAborted();const requestedAt=Date.now();const response=await wait(track(requestMicrosoftToken(transport,material.ok.clientId,{grant_type:"refresh_token",refresh_token:material.ok.refreshToken,scope:material.ok.scopes.join(" ")},ownerSignal)),ownerSignal),reply=response.body;const scopes=reply.scope===void 0?material.ok.scopes:typeof reply.scope==="string"&&reply.scope.length<=8192?reply.scope.trim().split(/\s+/u):[],expiresAt=requestedAt+Number(reply.expires_in)*1e3;if(response.status<200||response.status>=300||!validToken(reply.access_token)||typeof reply.token_type!=="string"||reply.token_type.toLowerCase()!=="bearer"||typeof reply.expires_in!=="number"||!Number.isFinite(reply.expires_in)||reply.expires_in<=0||!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt<=Date.now()||!validScopes(scopes)||!sameScopes(scopes,current.grant.scopes)||reply.refresh_token!==void 0&&!validToken(reply.refresh_token))return fail("failed_precondition","Teams refresh did not preserve token type, scope and expiry; reconnect this source.");const identity2=await wait(track(clientFactory(reply.access_token,ownerSignal).api("/me").select("id").get()),ownerSignal);if(identity2.id!==authority.accountId)return fail("permission_denied","Teams refreshed token does not match the selected native account.");const unchanged=await fence(current,ownerSignal,false);if(!("ok"in unchanged))return unchanged;if(expiresAt<=Date.now())return fail("failed_precondition","Teams refreshed access expired before custody completed.");return ok({kind:"oauth",credential:{...material.ok,accessToken:reply.access_token,...reply.refresh_token!==void 0?{refreshToken:reply.refresh_token}:{},expiresAt,scopes:[...material.ok.scopes]}})}catch{return fail("failed_precondition","Teams refresh did not complete; its rotating outcome must not be replayed.")}}));if(!("ok"in renewed))return renewed;snapshot=renewed.ok;allowed=authorized(snapshot,authority.accountId);if(!("ok"in allowed))return allowed}const before=await fence(snapshot,signal);if(!("ok"in before))return before;const identity=await clientFactory(allowed.ok.accessToken,signal).api("/me").select("id").get();if(identity.id!==authority.accountId)return businessError("permission_denied","Teams native account does not match the selected connection.","auth");const after=await fence(snapshot,signal);return"ok"in after?ok({accessToken:allowed.ok.accessToken,scopes:allowed.ok.scopes,check:(active=signal)=>fence(snapshot,active),signal,bindingId:snapshot.binding.id,account:snapshot.binding.account}):after}catch{return businessError(signal.aborted?"aborted":"unavailable","Teams authorization could not be verified.","auth")}}async function grant(caller){if(closed)return fail("unavailable","Teams source is inactive.");const signal=AbortSignal.any([caller,stop.signal,AbortSignal.timeout(45e3)]);try{return await wait(track(resolveGrant(signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams account authority could not be confirmed.")}}async function connect(options,signal){const expected=options.expectedBinding?{...options.expectedBinding}:void 0;if(expected?.kind==="legacy-source"&&expected.source!=="teams")return fail("invalid_argument","Teams account selection names another source.");if(options.automatic!==false){const existing=await vault.connection("teams");if(!("ok"in existing))return existing;if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(expected?.kind==="binding"){if(!vault.bindingCustody)return fail("failed_precondition","Teams requires verified account custody.");const selected=await vault.bindingCustody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved"||selected.ok.binding.id!==expected.bindingId)return fail("failed_precondition","Teams account selection does not match the existing grant.")}if(existing.ok){const resolved=await grant(signal);if(!("ok"in resolved))return resolved;if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(expected?.kind==="binding"&&resolved.ok.bindingId!==expected.bindingId)return fail("failed_precondition","Teams account selection changed during authorization reuse.");const job={id:randomUUID(),source:"teams",state:"connected",startedAt:new Date().toISOString(),account:resolved.ok.account};connectedJobs.set(job.id,job);if(connectedJobs.size>32)connectedJobs.delete(connectedJobs.keys().next().value);return ok({...job})}}if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(!enrollment)return fail("unavailable","Connector enrollment is not installed.");return enrollment.pkce(info,{clientId,authorizeUrl:MICROSOFT_AUTHORITY+"authorize?prompt=select_account",tokenUrl:MICROSOFT_AUTHORITY+"token",scope:TEAMS_SCOPE,redirectPath:"/",provider:"microsoft",driver:"microsoft"},async(result,signal2)=>{if(!result.access_token||!Number.isFinite(result.expires_in))throw Error("Microsoft authorization failed.");const scopes=String(result.scope??"").split(" ").filter(Boolean);for(const required of TEAMS_SCOPES.filter(scope=>scope!=="offline_access"))if(!scopePresent(scopes,required))throw Error("Required Teams Action scope missing: "+required);const identity=await clientFactory(result.access_token,signal2).api("/me").select("id,displayName,mail,userPrincipalName").get();if(!identity.id||!(identity.mail||identity.userPrincipalName))throw Error("Microsoft account unconfirmed.");return{account:identity.mail||identity.userPrincipalName,accountId:identity.id,credential:{accessToken:result.access_token,...result.refresh_token?{refreshToken:result.refresh_token}:{},clientId,expiresAt:Date.now()+Number(result.expires_in)*1e3,scopes}}},{...options,signal,...expected?{expectedBinding:expected}:{}})}async function readSelected(request,signal){const resolved=await grant(signal);if(!("ok"in resolved))return resolved;if(!scopePresent(resolved.ok.scopes,"Chat.Read")&&!scopePresent(resolved.ok.scopes,"Chat.ReadWrite"))return fail("permission_denied","The selected Teams grant does not include chat message read access.");const nativeId=value=>typeof value==="string"&&value.length>0&&value.length<=2048&&value===value.trim()&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);try{const client=clientFactory(resolved.ok.accessToken,signal),chats=await client.api("/me/chats").top(25).get();if(!Array.isArray(chats?.value)||chats.value.length>25||chats.value.some(chat=>!chat||!nativeId(chat.id)))return fail("data_loss","Teams returned a malformed chat page.");const records=[],limit=request.limit??1,query=request.query?.toLowerCase(),since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity;for(const chat of chats.value){if(records.length>=limit)break;const checked2=await resolved.ok.check?.(signal);if(checked2&&!("ok"in checked2))return checked2;const count=Math.min(50,limit),page=await client.api(`/chats/${encodeURIComponent(chat.id)}/messages`).top(count).get();if(!Array.isArray(page?.value)||page.value.length>count||page.value.some(row=>!row||!nativeId(row.id)||typeof row.body?.content!=="string"||typeof(row.createdDateTime??row.lastModifiedDateTime)!=="string"||!Number.isFinite(Date.parse(row.createdDateTime??row.lastModifiedDateTime))))return fail("data_loss","Teams returned malformed messages.");for(const row of page.value){const content=row.body.content,ts=row.createdDateTime??row.lastModifiedDateTime,time=Date.parse(ts);if(time<since||time>until||query&&!content.toLowerCase().includes(query))continue;records.push({source:"teams",sourceId:row.id,kind:"teams-message",ts,body:content,fields:{...row,chatId:chat.id}});if(records.length>=limit)break}}const checked=await resolved.ok.check?.(signal);return checked&&!("ok"in checked)?checked:readResult("teams",records)}catch{return businessError(signal.aborted?"aborted":"unavailable","Microsoft Graph Teams query failed; no empty result was assumed.","plugin")}}const actions=createTeamsActions(grant,clientFactory);const operationSignal=caller=>AbortSignal.any([stop.signal,AbortSignal.timeout(45e3),...caller?[caller]:[]]);const service={info,actions:{...actions,async invoke(name,input,options={}){if(closed)return fail("unavailable","Teams source is inactive.");const signal=operationSignal(options.signal);try{return await wait(track(actions.invoke(name,input,{...options,signal})),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams Action did not complete.")}}},status:()=>connectionState(vault,info),job:id=>connectedJobs.has(id)?ok({...connectedJobs.get(id)}):enrollment?enrollment.job(id):fail("not_found","Teams authorization job not found."),cancelJob:id=>connectedJobs.has(id)?ok({id,cleanup:"confirmed"}):enrollment?.cancelJob(id)??fail("not_found","Teams authorization job not found."),async connect(options={}){if(closed)return fail("unavailable","Teams source is inactive.");const signal=operationSignal(options.signal);try{return await wait(track(connect(options,signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams connection did not complete.")}},async read(request,options={}){if(closed)return fail("unavailable","Teams source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;const signal=operationSignal(options.signal);try{return await wait(track(readSelected({...request},signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams selected read did not complete.")}},close(){if(closing)return closing;closed=true;stop.abort();enrollment?.cancelSource?.("teams");closing=(async()=>{while(pending.size)await Promise.allSettled([...pending])})();return closing}};return service}
|
|
1
|
+
import{actionNotApplied,withActionExecution}from"@zortexhq/plugin-connector-core/api";import{acquiredReadCapability,unreviewedActionContent}from"@zortexhq/plugin-connector-core/api";import{Client,RetryHandlerOptions}from"@microsoft/microsoft-graph-client";import{randomUUID}from"node:crypto";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{captureSelectedAccount,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{createTeamsActions}from"./actions.js";import{MICROSOFT_AUTHORITY,TEAMS_SCOPE,TEAMS_SCOPES,credentialExpiring,requestMicrosoftToken,teamsClientId}from"./token.js";const defaultClientFactory=(accessToken,signal)=>{const client=Client.init({authProvider:done=>done(null,accessToken),fetchOptions:{signal}});const retry=new RetryHandlerOptions(void 0,void 0,(_delay,_attempt,request,options)=>(typeof request==="string"?options?.method:request.method)==="GET");return{api:path=>client.api(path).middlewareOptions([retry])}};function scopePresent(scopes,required){return scopes.includes(required)||scopes.includes("https://graph.microsoft.com/"+required)}const validToken=value=>typeof value==="string"&&value.length>0&&value.length<=16384&&!/[\s\u0000-\u001f\u007f-\u009f]/u.test(value);const validScopes=value=>Array.isArray(value)&&value.length>0&&value.length<=64&&value.every(scope=>typeof scope==="string"&&/^[\x21-\x7e]{1,512}$/u.test(scope));const sameScopes=(left,right)=>JSON.stringify([...new Set(left)].sort())===JSON.stringify([...new Set(right)].sort());function wait(task,signal){return new Promise((resolve,reject)=>{const cancelled=()=>{signal.removeEventListener("abort",cancelled);reject(signal.reason??Error("Teams operation cancelled."))};signal.addEventListener("abort",cancelled,{once:true});task.then(value=>{signal.removeEventListener("abort",cancelled);resolve(value)},error=>{signal.removeEventListener("abort",cancelled);reject(error)});if(signal.aborted)cancelled()})}export function createTeamsProvider({vault,enrollment,transport=fetch,clientFactory=defaultClientFactory}){const info={content:[acquiredReadCapability(["plugins/connector-teams/README.md"]),unreviewedActionContent(["plugins/connector-teams/README.md"])],source:"teams",label:"Microsoft Teams",group:"Connector / Microsoft",auth:"oauth-browser"},stop=new AbortController;let closed=false,closing;const clientId=teamsClientId();const pending=new Set,connectedJobs=new Map;const fail=(code,message)=>businessError(code,message,"plugin");function track(task){pending.add(task);void task.then(()=>pending.delete(task),()=>pending.delete(task));return task}function authorized(snapshot,accountId){const{binding,grant:grant2,resource,material}=snapshot;if(binding.identity.source!=="teams"||binding.identity.issuer!=="microsoft"||binding.provider!=="microsoft"||binding.identity.subject!==accountId||binding.state!=="connected"||grant2.bindingId!==binding.id||grant2.purpose!=="L1"||grant2.audience!=="microsoft"||grant2.state!=="active"||resource.id!==oauthCredentialResourceId(binding.id)||resource.bindingId!==binding.id||resource.kind!=="oauth"||resource.owner.kind!=="resident"||material.kind!=="oauth")return fail("failed_precondition","Teams requires one verified native resident OAuth binding and L1 grant.");const credential=material.credential;if(!validScopes(grant2.scopes)||!validScopes(credential.scopes)||!sameScopes(grant2.scopes,credential.scopes))return fail("permission_denied","Teams credential scopes do not match the selected grant.");if(!validToken(credential.accessToken)||typeof credential.clientId!=="string"||!/^[\x21-\x7e]{1,512}$/u.test(credential.clientId)||!Number.isFinite(credential.expiresAt)||credential.expiresAt<=0||credential.expiresAt>864e13||credential.refreshToken!==void 0&&!validToken(credential.refreshToken))return fail("failed_precondition","Teams credential material is invalid; reconnect this source.");return ok(credential)}async function resolveGrant(signal){const selected=await captureSelectedAccount(vault,"teams",signal);if(!("ok"in selected))return selected;const authority=selected.ok;if(!vault.bindingCustody)return fail("failed_precondition","Teams operations require verified account custody.");const custody=vault.bindingCustody,resolution=await custody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in resolution))return resolution;if(resolution.ok.kind!=="resolved")return fail("failed_precondition","Select one verified Teams account binding.");const found=await custody.credentialSnapshot(oauthCredentialResourceId(resolution.ok.binding.id),{purpose:"L1",audience:"microsoft"});if(!("ok"in found))return found;let snapshot=found.ok,allowed=authorized(snapshot,authority.accountId);if(!("ok"in allowed))return allowed;async function fence(expected,active,requireFresh=true){const checked=await authority.check(active);if(!("ok"in checked))return checked;const current=await custody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in current))return current;if(current.ok.kind!=="resolved"||current.ok.binding.id!==expected.binding.id||current.ok.binding.revision!==expected.binding.revision)return fail("failed_precondition","Teams account selection changed during the operation.");const resource=await custody.resource(expected.resource.id);if(!("ok"in resource))return resource;if(resource.ok?.revision!==expected.resource.revision||resource.ok.owner.kind!=="resident")return fail("failed_precondition","Teams credential authority changed during the operation.");const credential=authorized(expected,authority.accountId);if(!("ok"in credential))return credential;if(requireFresh&&credential.ok.expiresAt<=Date.now())return fail("failed_precondition","Teams authorization expired during the operation.");return authority.check(active)}try{if(credentialExpiring(allowed.ok)){if(!allowed.ok.refreshToken)return fail("failed_precondition","Teams authorization expired; reconnect this source.");const before2=await fence(snapshot,signal,false);if(!("ok"in before2))return before2;const ownerSignal=AbortSignal.any([stop.signal,AbortSignal.timeout(45e3)]);const renewed=await track(custody.refreshResource(snapshot,{kind:"resident"},async current=>{const material=authorized(current,authority.accountId);if(!("ok"in material))return material;const checked=await fence(current,ownerSignal,false);if(!("ok"in checked))return checked;if(!material.ok.refreshToken)return fail("failed_precondition","Teams authorization expired; reconnect this source.");try{ownerSignal.throwIfAborted();const requestedAt=Date.now();const response=await wait(track(requestMicrosoftToken(transport,material.ok.clientId,{grant_type:"refresh_token",refresh_token:material.ok.refreshToken,scope:material.ok.scopes.join(" ")},ownerSignal)),ownerSignal),reply=response.body;const scopes=reply.scope===void 0?material.ok.scopes:typeof reply.scope==="string"&&reply.scope.length<=8192?reply.scope.trim().split(/\s+/u):[],expiresAt=requestedAt+Number(reply.expires_in)*1e3;if(response.status<200||response.status>=300||!validToken(reply.access_token)||typeof reply.token_type!=="string"||reply.token_type.toLowerCase()!=="bearer"||typeof reply.expires_in!=="number"||!Number.isFinite(reply.expires_in)||reply.expires_in<=0||!Number.isFinite(expiresAt)||expiresAt>864e13||expiresAt<=Date.now()||!validScopes(scopes)||!sameScopes(scopes,current.grant.scopes)||reply.refresh_token!==void 0&&!validToken(reply.refresh_token))return fail("failed_precondition","Teams refresh did not preserve token type, scope and expiry; reconnect this source.");const identity2=await wait(track(clientFactory(reply.access_token,ownerSignal).api("/me").select("id").get()),ownerSignal);if(identity2.id!==authority.accountId)return fail("permission_denied","Teams refreshed token does not match the selected native account.");const unchanged=await fence(current,ownerSignal,false);if(!("ok"in unchanged))return unchanged;if(expiresAt<=Date.now())return fail("failed_precondition","Teams refreshed access expired before custody completed.");return ok({kind:"oauth",credential:{...material.ok,accessToken:reply.access_token,...reply.refresh_token!==void 0?{refreshToken:reply.refresh_token}:{},expiresAt,scopes:[...material.ok.scopes]}})}catch{return fail("failed_precondition","Teams refresh did not complete; its rotating outcome must not be replayed.")}}));if(!("ok"in renewed))return renewed;snapshot=renewed.ok;allowed=authorized(snapshot,authority.accountId);if(!("ok"in allowed))return allowed}const before=await fence(snapshot,signal);if(!("ok"in before))return before;const identity=await clientFactory(allowed.ok.accessToken,signal).api("/me").select("id").get();if(identity.id!==authority.accountId)return businessError("permission_denied","Teams native account does not match the selected connection.","auth");const after=await fence(snapshot,signal);return"ok"in after?ok({accessToken:allowed.ok.accessToken,scopes:allowed.ok.scopes,check:(active=signal)=>fence(snapshot,active),signal,bindingId:snapshot.binding.id,account:snapshot.binding.account}):after}catch{return businessError(signal.aborted?"aborted":"unavailable","Teams authorization could not be verified.","auth")}}async function grant(caller){if(closed)return actionNotApplied(fail("unavailable","Teams source is inactive."));const signal=AbortSignal.any([caller,stop.signal,AbortSignal.timeout(45e3)]);try{return await wait(track(resolveGrant(signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams account authority could not be confirmed.")}}async function connect(options,signal){const expected=options.expectedBinding?{...options.expectedBinding}:void 0;if(expected?.kind==="legacy-source"&&expected.source!=="teams")return fail("invalid_argument","Teams account selection names another source.");if(options.automatic!==false){const existing=await vault.connection("teams");if(!("ok"in existing))return existing;if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(expected?.kind==="binding"){if(!vault.bindingCustody)return fail("failed_precondition","Teams requires verified account custody.");const selected=await vault.bindingCustody.resolve({kind:"legacy-source",source:"teams"});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved"||selected.ok.binding.id!==expected.bindingId)return fail("failed_precondition","Teams account selection does not match the existing grant.")}if(existing.ok){const resolved=await grant(signal);if(!("ok"in resolved))return resolved;if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(expected?.kind==="binding"&&resolved.ok.bindingId!==expected.bindingId)return fail("failed_precondition","Teams account selection changed during authorization reuse.");const job={id:randomUUID(),source:"teams",state:"connected",startedAt:new Date().toISOString(),account:resolved.ok.account};connectedJobs.set(job.id,job);if(connectedJobs.size>32)connectedJobs.delete(connectedJobs.keys().next().value);return ok({...job})}}if(signal.aborted)return fail("aborted","Teams connection was stopped.");if(!enrollment)return fail("unavailable","Connector enrollment is not installed.");return enrollment.pkce(info,{clientId,authorizeUrl:MICROSOFT_AUTHORITY+"authorize?prompt=select_account",tokenUrl:MICROSOFT_AUTHORITY+"token",scope:TEAMS_SCOPE,redirectPath:"/",provider:"microsoft",driver:"microsoft"},async(result,signal2)=>{if(!result.access_token||!Number.isFinite(result.expires_in))throw Error("Microsoft authorization failed.");const scopes=String(result.scope??"").split(" ").filter(Boolean);for(const required of TEAMS_SCOPES.filter(scope=>scope!=="offline_access"))if(!scopePresent(scopes,required))throw Error("Required Teams Action scope missing: "+required);const identity=await clientFactory(result.access_token,signal2).api("/me").select("id,displayName,mail,userPrincipalName").get();if(!identity.id||!(identity.mail||identity.userPrincipalName))throw Error("Microsoft account unconfirmed.");return{account:identity.mail||identity.userPrincipalName,accountId:identity.id,credential:{accessToken:result.access_token,...result.refresh_token?{refreshToken:result.refresh_token}:{},clientId,expiresAt:Date.now()+Number(result.expires_in)*1e3,scopes}}},{...options,signal,...expected?{expectedBinding:expected}:{}})}async function readSelected(request,signal){const resolved=await grant(signal);if(!("ok"in resolved))return resolved;if(!scopePresent(resolved.ok.scopes,"Chat.Read")&&!scopePresent(resolved.ok.scopes,"Chat.ReadWrite"))return fail("permission_denied","The selected Teams grant does not include chat message read access.");const nativeId=value=>typeof value==="string"&&value.length>0&&value.length<=2048&&value===value.trim()&&!/[\u0000-\u001f\u007f-\u009f]/u.test(value);try{const client=clientFactory(resolved.ok.accessToken,signal),chats=await client.api("/me/chats").top(25).get();if(!Array.isArray(chats?.value)||chats.value.length>25||chats.value.some(chat=>!chat||!nativeId(chat.id)))return fail("data_loss","Teams returned a malformed chat page.");const records=[],limit=request.limit??1,query=request.query?.toLowerCase(),since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity;for(const chat of chats.value){if(records.length>=limit)break;const checked2=await resolved.ok.check?.(signal);if(checked2&&!("ok"in checked2))return checked2;const count=Math.min(50,limit),page=await client.api(`/chats/${encodeURIComponent(chat.id)}/messages`).top(count).get();if(!Array.isArray(page?.value)||page.value.length>count||page.value.some(row=>!row||!nativeId(row.id)||typeof row.body?.content!=="string"||typeof(row.createdDateTime??row.lastModifiedDateTime)!=="string"||!Number.isFinite(Date.parse(row.createdDateTime??row.lastModifiedDateTime))))return fail("data_loss","Teams returned malformed messages.");for(const row of page.value){const content=row.body.content,ts=row.createdDateTime??row.lastModifiedDateTime,time=Date.parse(ts);if(time<since||time>until||query&&!content.toLowerCase().includes(query))continue;records.push({source:"teams",sourceId:chat.id+":"+row.id,kind:"teams-message",ts,body:content,fields:{...row,chatId:chat.id}});if(records.length>=limit)break}}const checked=await resolved.ok.check?.(signal);return checked&&!("ok"in checked)?checked:readResult("teams",records)}catch{return businessError(signal.aborted?"aborted":"unavailable","Microsoft Graph Teams query failed; no empty result was assumed.","plugin")}}const actions=createTeamsActions(grant,clientFactory);const operationSignal=caller=>AbortSignal.any([stop.signal,AbortSignal.timeout(45e3),...caller?[caller]:[]]);const service={info,actions:{...actions,async invoke(name,input,options={}){if(closed)return fail("unavailable","Teams source is inactive.");const signal=operationSignal(options.signal);const task=track(actions.invoke(name,input,{...options,signal}));try{return withActionExecution(await wait(task,signal),task)}catch{return withActionExecution(fail(signal.aborted?"aborted":"unavailable","Teams Action did not complete."),task)}}},status:()=>connectionState(vault,info),job:id=>connectedJobs.has(id)?ok({...connectedJobs.get(id)}):enrollment?enrollment.job(id):fail("not_found","Teams authorization job not found."),cancelJob:id=>connectedJobs.has(id)?ok({id,cleanup:"confirmed"}):enrollment?.cancelJob(id)??fail("not_found","Teams authorization job not found."),async connect(options={}){if(closed)return fail("unavailable","Teams source is inactive.");const signal=operationSignal(options.signal);try{return await wait(track(connect(options,signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams connection did not complete.")}},async read(request,options={}){if(closed)return fail("unavailable","Teams source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;const signal=operationSignal(options.signal);try{return await wait(track(readSelected({...request},signal)),signal)}catch{return fail(signal.aborted?"aborted":"unavailable","Teams selected read did not complete.")}},close(){if(closing)return closing;closed=true;stop.abort();enrollment?.cancelSource?.("teams");closing=(async()=>{while(pending.size)await Promise.allSettled([...pending])})();return closing}};return service}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BufferJSON,initAuthCreds,proto}from"baileys";export function sessionStore(serialized,changed){let creds=initAuthCreds();let keys={};if(serialized){const parsed=JSON.parse(serialized,BufferJSON.reviver);if(!parsed?.creds||typeof parsed.keys!=="object")throw new Error("invalid_session");creds=parsed.creds;keys=parsed.keys}const state={creds,keys:{async get(type,ids){const data={};for(const id of ids){let value=keys[type]?.[id];if(value===void 0)continue;if(type==="app-state-sync-key")value=proto.Message.AppStateSyncKeyData.fromObject(value);data[id]=value}return data},async set(data){for(const[type,entries]of Object.entries(data)){const bucket=keys[type]??={};for(const[id,value]of Object.entries(entries??{})){if(value===null||value===void 0)delete bucket[id];else bucket[id]=value}}changed()}}};return{state,serialize:()=>JSON.stringify({creds:state.creds,keys},BufferJSON.replacer)}}
|
|
1
|
+
import{BufferJSON,initAuthCreds,proto}from"baileys";export function sessionStore(serialized,changed){let creds=initAuthCreds();let keys={};if(serialized){const parsed=JSON.parse(serialized,BufferJSON.reviver);if(!parsed?.creds||typeof parsed.keys!=="object")throw new Error("invalid_session");creds=parsed.creds;keys=parsed.keys}const state={creds,keys:{async get(type,ids){const data={};for(const id of ids){let value=keys[type]?.[id];if(value===void 0)continue;if(type==="app-state-sync-key")value=proto.Message.AppStateSyncKeyData.fromObject(value);data[id]=value}return data},async set(data){for(const[type,entries]of Object.entries(data)){const bucket=keys[type]??={};for(const[id,value]of Object.entries(entries??{})){if(value===null||value===void 0)delete bucket[id];else bucket[id]=value}}await changed()}}};return{state,serialize:()=>JSON.stringify({creds:state.creds,keys},BufferJSON.replacer)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID}from"node:crypto";import makeWASocket,{Browsers,DisconnectReason,fetchLatestBaileysVersion,jidDecode}from"baileys";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{sessionStore}from"./auth-state.js";import{toRecords}from"./messages.js";import{openPairingPage}from"./pairing-page.js";import{TransientMessageBuffer,TRANSIENT_MESSAGE_LIMIT}from"./transient-buffer.js";export const SOURCE="whatsapp-web";const silent={level:"silent",child:()=>silent,trace(){},debug(){},info(){},warn(){},error(){},fatal(){}};async function defaultSocket(auth,fullHistory){const version=await Promise.race([fetchLatestBaileysVersion().then(r=>r.version).catch(()=>void 0),new Promise(resolve=>setTimeout(resolve,5e3))]);return makeWASocket({auth,logger:silent,browser:Browsers.macOS("Chrome"),syncFullHistory:fullHistory,markOnlineOnConnect:false,...version?{version}:{}})}const statusCode=update=>update.lastDisconnect?.error?.output?.statusCode;function nativeAccount(socket){const identity=jidDecode(socket?.user?.id);return identity?.server==="s.whatsapp.net"&&/^[1-9][0-9]{4,19}$/u.test(identity.user)?identity.user:void 0}export function createWhatsappProvider({vault,socket,pairingPage=openPairingPage,openUrl=openConnectionUrl,payloadRetention="cache",pairingTimeoutMs=18e4,resumeTimeoutMs=2e4,historyTimeoutMs=3e4}){if(!["cache","transient"].includes(payloadRetention)||[pairingTimeoutMs,resumeTimeoutMs,historyTimeoutMs].some(ms=>!Number.isInteger(ms)||ms<1||ms>6e5))throw Error("Invalid WhatsApp retention or timeout configuration.");const transient=payloadRetention==="transient",makeSocket=socket??(auth=>defaultSocket(auth,!transient));const info={source:SOURCE,label:"WhatsApp",group:"Connector / Chat",auth:"native-browser"};const jobs=new Map,names=new Map,buffer=new TransientMessageBuffer,pairings=new Set;const initializing=new Set;let live,resuming,closed=false,closing;let writes=Promise.resolve(),persistTimer;const fail=(code,message)=>businessError(code,message,"plugin");const enqueue=task=>{writes=writes.then(task,task).catch(()=>void 0);return writes};const track=task=>{initializing.add(task);void task.then(()=>initializing.delete(task),()=>initializing.delete(task));return task};const notify=entry=>{for(const wake of entry.waiters)wake()};const owned=(entry,sock=entry.socket)=>!closed&&!entry.stopped&&live===entry&&entry.socket===sock;function remember(jid,name){if(!jid||jid.length>512||!name)return;names.delete(jid);names.set(jid,name.slice(0,256));if(names.size>2e3)names.delete(names.keys().next().value)}function stopLive(entry){entry.stopped=true;entry.online=false;entry.resolveOpen(false);notify(entry);entry.socket?.end();if(live===entry){live=void 0;buffer.clear();names.clear()}}function waitUntil(entry,predicate,timeout,signal){if(predicate())return Promise.resolve(true);if(signal?.aborted||closed||entry.stopped)return Promise.resolve(false);return new Promise(resolve=>{const finish=value=>{clearTimeout(timer);entry.waiters.delete(wake);signal?.removeEventListener("abort",abort);resolve(value)};const wake=()=>{if(predicate())finish(true);else if(closed||entry.stopped)finish(false)};const abort=()=>finish(false),timer=setTimeout(()=>finish(false),timeout);entry.waiters.add(wake);signal?.addEventListener("abort",abort,{once:true});wake()})}async function captureAuthority(accountId){const custody=vault.bindingCustody;if(!custody)return transient?fail("failed_precondition","Transient WhatsApp requires durable native account custody."):ok(void 0);const selected=await custody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return fail("failed_precondition","WhatsApp needs one explicit native account binding.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(selected.ok.binding.id),{purpose:"L1",audience:SOURCE});if(!("ok"in current))return current;const value=current.ok;if(value.binding.identity.source!==SOURCE||value.binding.identity.issuer!==SOURCE||value.binding.identity.subject!==accountId||value.binding.identity.tenant!==null||value.material.kind!=="oauth"||value.resource.kind!=="oauth"||value.resource.owner.kind!=="resident"||value.material.credential.clientId!=="whatsapp-linked-device"||!value.grant.scopes.includes("messages.read"))return fail("permission_denied","WhatsApp session custody does not match the selected native account.");return ok({binding:value.binding,grant:value.grant,resource:value.resource})}async function checkAuthority(entry){if(!entry.accountId||nativeAccount(entry.socket)!==entry.accountId)return fail("failed_precondition","WhatsApp signed-in account changed. Reconnect the selected account.");const current=await captureAuthority(entry.accountId);if(!("ok"in current))return current;const expected=entry.authority,latest=current.ok;if(expected&&(!latest||latest.binding.id!==expected.binding.id||latest.binding.revision!==expected.binding.revision||latest.grant.id!==expected.grant.id||latest.grant.revision!==expected.grant.revision||latest.grant.scopeEpoch!==expected.grant.scopeEpoch||latest.resource.id!==expected.resource.id))return fail("permission_denied","WhatsApp account permission changed while the operation was pending.");return ok(latest)}async function persistNow(entry){if(!entry.accountId||!entry.online||entry.stopped)return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}if(entry.stopped||!entry.online)return;const credential={accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]};const saved=allowed.ok&&vault.bindingCustody?await vault.bindingCustody.compareAndSwapResource({...allowed.ok.resource,updatedAt:new Date().toISOString()},{kind:"oauth",credential},allowed.ok.resource.revision):await vault.updateCredential(SOURCE,credential);if(!("ok"in saved))stopLive(entry)}function persist(entry){if(!owned(entry)||!entry.accountId)return;clearTimeout(persistTimer);persistTimer=setTimeout(()=>{void enqueue(()=>persistNow(entry))},1e3);persistTimer.unref?.()}function store(entry,sock,messages,history=false){if(!owned(entry,sock)||!entry.accountId||nativeAccount(sock)!==entry.accountId||transient&&!entry.online)return;if(transient){for(const message of messages)for(const record of toRecords(entry.accountId,[message],jid=>names.get(jid)))buffer.add(record);if(history||messages.length>0)entry.historyArrived=true;notify(entry);return}const records=toRecords(entry.accountId,messages,jid=>names.get(jid));for(let i=0;i<records.length;i+=100){const batch=records.slice(i,i+100);void enqueue(async()=>{if(!await entry.open||!owned(entry,sock))return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}await cache(vault,SOURCE,batch);entry.historyArrived=true;notify(entry)})}}async function markLoggedOut(entry){if(!entry.accountId)return;if(vault.bindingCustody&&entry.authority){const current=await vault.bindingCustody.binding(entry.authority.binding.id);if("ok"in current&¤t.ok?.revision===entry.authority.binding.revision)await vault.bindingCustody.compareAndSwapBinding({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},current.ok.revision)}else{const current=await vault.connection(SOURCE);if("ok"in current&¤t.ok?.accountId===entry.accountId)await vault.saveConnection({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},{accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]})}}async function start(stateStore,accountId,authority,onView,onOpen,onFailure){if(closed)throw Error("inactive");let resolveOpen;const open=new Promise(resolve=>{resolveOpen=resolve});const current={store:stateStore,open,resolveOpen,...accountId?{accountId}:{},...authority?{authority}:{},online:false,stopped:false,historyArrived:false,needsPairing:false,waiters:new Set};live=current;buffer.clear();names.clear();let restarts=0,generation=0;const failed=code=>{current.failure=code;stopLive(current);onFailure?.(code)};const connect=async()=>{if(!owned(current))return;const attempt=++generation,previous=current.socket;delete current.socket;previous?.end();const sock=await track(makeSocket(current.store.state));if(!owned(current)||attempt!==generation){sock.end();return}current.socket=sock;sock.ev.on("creds.update",()=>{if(owned(current,sock))persist(current)});sock.ev.on("connection.update",update=>{if(!owned(current,sock))return;if(update.qr){current.needsPairing=true;onView?.({state:"qr",qr:update.qr});notify(current)}if(update.connection==="open"){const linked=nativeAccount(sock);if(!linked||current.accountId&¤t.accountId!==linked){failed("account_changed");return}current.accountId=linked;void(async()=>{const completed=await onOpen?.(current);if(!owned(current,sock))return;const captured=current.authority?await checkAuthority(current):await captureAuthority(linked);if(!("ok"in captured)){failed("account_permission_changed");return}if(!owned(current,sock))return;if(!current.authority)current.authority=captured.ok;current.online=true;current.needsPairing=false;restarts=0;resolveOpen(true);notify(current);completed?.()})().catch(()=>failed("pairing_unavailable"))}if(update.connection==="close"){current.online=false;notify(current);const code=statusCode(update);if(code===DisconnectReason.loggedOut){current.needsPairing=true;void enqueue(()=>markLoggedOut(current));failed("qr_scan_required");return}if(code!==DisconnectReason.connectionReplaced&&restarts++<5){void connect().catch(()=>failed("connection_unavailable"));return}failed("connection_unavailable")}});sock.ev.on("messaging-history.set",({chats,contacts,messages})=>{if(!owned(current,sock))return;for(const chat of chats)remember(chat.id,chat.name);for(const contact of contacts)remember(contact.id,contact.name??contact.notify);store(current,sock,messages,true)});sock.ev.on("chats.upsert",chats=>{if(owned(current,sock))for(const chat of chats)remember(chat.id,chat.name)});sock.ev.on("contacts.upsert",contacts=>{if(owned(current,sock))for(const contact of contacts)remember(contact.id,contact.name??contact.notify)});sock.ev.on("messages.upsert",({messages})=>{if(!owned(current,sock))return;for(const message of messages)if(!message.key.fromMe)remember(message.key.remoteJid,message.key.remoteJid?.endsWith("@g.us")?void 0:message.pushName);store(current,sock,messages)})};try{await connect()}catch(error){failed("connection_unavailable");throw error}return current}async function resume(){if(live&&!live.stopped)return live;if(resuming)return resuming;resuming=(async()=>{const connection=await vault.connection(SOURCE);if(!("ok"in connection))throw Error("account_permission_changed");if(connection.ok?.state!=="connected"||!connection.ok.accountId)return void 0;const grant=await vault.credential(SOURCE);if(!("ok"in grant))throw Error("account_permission_changed");const authority=await captureAuthority(connection.ok.accountId);if(!("ok"in authority))throw Error("account_permission_changed");const restored=sessionStore(grant.ok.accessToken,()=>{if(live)persist(live)});return start(restored,connection.ok.accountId,authority.ok)})();try{return await resuming}finally{resuming=void 0}}function cleanPairing(pair2){clearTimeout(pair2.timer);pair2.removeAbort?.();pair2.page?.close();pairings.delete(pair2)}function failPairing(pair2,code,message){if(pair2.job.state==="waiting-user"){pair2.job.state="failed";pair2.job.error={code,message};delete pair2.job.authorizationUrl;delete pair2.job.instructions;pair2.stop.abort();pair2.page?.update({state:"failed",message});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live)}cleanPairing(pair2)}function cancelPairing(pair2){if(pair2.job.state==="waiting-user")pair2.job.state="cancelled";delete pair2.job.authorizationUrl;delete pair2.job.instructions;delete pair2.job.error;pair2.stop.abort();pair2.page?.update({state:"failed",message:"WhatsApp connection was cancelled."});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live);cleanPairing(pair2)}async function pair(job,options,expectedAccountId){if(closed)throw Error("inactive");const owner={job,stop:new AbortController};pairings.add(owner);const abort=()=>failPairing(owner,"aborted","WhatsApp connection was cancelled.");options.signal?.addEventListener("abort",abort,{once:true});owner.removeAbort=()=>options.signal?.removeEventListener("abort",abort);try{owner.page=await pairingPage();if(closed||options.signal?.aborted||owner.stop.signal.aborted){abort();return}job.authorizationUrl=owner.page.url;job.instructions="Open the QR code page, then use WhatsApp on your phone: Settings \u2192 Linked devices \u2192 Link a device. The connection continues automatically after scanning.";job.error={code:"qr_scan_required",message:"Scan the WhatsApp QR code with your phone."};owner.timer=setTimeout(()=>failPairing(owner,"pairing_timeout","WhatsApp QR was not scanned before it expired."),pairingTimeoutMs);owner.timer.unref?.();const fresh=sessionStore(void 0,()=>{if(owner.entry)persist(owner.entry)});if(live)stopLive(live);owner.entry=await start(fresh,expectedAccountId,void 0,view=>{if(job.state==="waiting-user")owner.page?.update(view)},async current=>{if(job.state==="connected"&&!closed)return;if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)throw Error("aborted");const saved=await vault.saveConnection({source:SOURCE,provider:SOURCE,account:current.socket?.user?.name?.slice(0,256)||"WhatsApp",accountId:current.accountId,scopes:["messages.read"],state:"connected",updatedAt:new Date().toISOString()},{accessToken:current.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]},{signal:owner.stop.signal});if(!("ok"in saved))throw Error("custody_failed");return()=>{if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)return;clearTimeout(owner.timer);owner.removeAbort?.();job.state="connected";job.account=saved.ok.account;delete job.instructions;delete job.authorizationUrl;delete job.error;owner.page?.update({state:"connected"});owner.timer=setTimeout(()=>cleanPairing(owner),1e4);owner.timer.unref?.()}},code=>failPairing(owner,code,code==="account_changed"?"The scanned WhatsApp account does not match the selected account.":"WhatsApp pairing did not complete."));if(owner.stop.signal.aborted)stopLive(owner.entry);if(!options.automatic&&options.manualPresentation!=="return-url"&&job.state==="waiting-user")await openUrl(owner.page.url)}catch{failPairing(owner,"pairing_unavailable","WhatsApp pairing page or connection could not start.")}}return{info,...transient?{}:{requiresPersistentPayloads:true},status:()=>connectionState(vault,info),job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","WhatsApp connection job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const pairing=[...pairings].find(owner=>owner.job===job);if(pairing)cancelPairing(pairing);else if(job.state==="waiting-user")job.state="cancelled";delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:[...pairings].some(owner=>owner.job===job)?"pending":"confirmed"})},async connect(options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");const running=[...jobs.values()].find(job2=>job2.state==="waiting-user");if(running)return ok({...running});for(const[id,job2]of jobs)if(jobs.size>=32&&job2.state!=="waiting-user")jobs.delete(id);const job={id:randomUUID(),source:SOURCE,state:"waiting-user",startedAt:new Date().toISOString()};jobs.set(job.id,job);try{const selected=await vault.connection(SOURCE);if(!("ok"in selected))return selected;if(selected.ok&&!selected.ok.accountId)return fail("failed_precondition","WhatsApp needs a verified native account binding.");if(options.expectedBinding?.kind==="legacy-source"&&options.expectedBinding.source!==SOURCE)return fail("invalid_argument","WhatsApp account selection names another source.");if(options.expectedBinding?.kind==="binding"){const binding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in binding)||binding.ok.kind!=="resolved"||binding.ok.binding.id!==options.expectedBinding.bindingId)return fail("failed_precondition","WhatsApp account selection does not match this linked device.")}if(closed)return fail("unavailable","WhatsApp source is inactive.");const resumed=await track(resume());if(resumed){await waitUntil(resumed,()=>resumed.online||resumed.needsPairing,resumeTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");if(resumed.online){const allowed=await checkAuthority(resumed);if(!("ok"in allowed))return allowed;job.state="connected";if(selected.ok)job.account=selected.ok.account;return ok({...job})}if(!resumed.needsPairing){job.state="failed";job.error={code:resumed.failure??"connection_unavailable",message:resumed.failure==="account_changed"?"WhatsApp signed in as a different account.":"The existing WhatsApp session did not reconnect."};return ok({...job})}}if(options.automatic&&!transient){job.state="failed";job.error={code:"qr_scan_required",message:"WhatsApp needs one QR scan from the phone; connect it explicitly."};return ok({...job})}if(options.automatic&&selected.ok?.accountId&&vault.bindingCustody){const selectedBinding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if("ok"in selectedBinding&&selectedBinding.ok.kind==="resolved"){const grant=await vault.bindingCustody.grantForBinding(selectedBinding.ok.binding.id,"L1",SOURCE);if(!("ok"in grant))return grant;if(grant.ok?.state==="revoked")return fail("permission_denied","WhatsApp access was revoked. Reconnect explicitly to grant it again.")}}await track(pair(job,options,selected.ok?.accountId))}catch{job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp session permission or connection could not be verified."}}finally{if(job.state==="waiting-user"&&![...pairings].some(owner=>owner.job===job)){job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp did not start an owned connection job."}}}return ok({...job})},async read(request,options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;if(request.fileId!==void 0)return fail("invalid_argument","WhatsApp message reads support limit, query and time filters; file download is not supported.");if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const connection=await vault.connection(SOURCE);if(!("ok"in connection))return connection;if(connection.ok?.state!=="connected"||!connection.ok.accountId)return fail("unauthenticated","Connect WhatsApp by scanning its QR code first.");const session=await track(resume()).catch(()=>void 0);const online=session?await waitUntil(session,()=>session.online,resumeTimeoutMs,options.signal):false;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const warnings=[];let records;if(transient){if(!online||!session)return fail("unavailable","WhatsApp is offline; transient reads need the selected live session.");const allowed=await checkAuthority(session);if(!("ok"in allowed)){stopLive(session);return allowed}await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");if(!owned(session)||!session.online)return fail("unavailable","WhatsApp session ended before the message read.");const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(!session.historyArrived)return fail("unavailable","No live WhatsApp message batch has arrived for this session yet. Retry after the phone finishes linking or a message arrives.");records=buffer.snapshot();warnings.push(`This live session retains at most ${TRANSIENT_MESSAGE_LIMIT} messages and 4 MiB in memory. Messages are not saved and are cleared on restart.`)}else{if(!online)warnings.push("WhatsApp is offline right now; showing messages already saved in the Vault.");if(online&&session&&!session.historyArrived){const stored2=await vault.records(SOURCE,1);if(!("ok"in stored2)||!stored2.ok.length)await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal)}await writes;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const stored=await vault.records(SOURCE,100);if(!("ok"in stored))return stored;records=stored.ok.map(row=>row.data);if(request.query||request.since||request.until)warnings.push("Filters apply to the 100 most recent saved messages; use SQL search over z_records for older history.")}const since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity,query=request.query?.toLowerCase();records=records.filter(record=>record.sourceId?.startsWith(connection.ok.accountId+":")).filter(record=>{const at=Date.parse(record.ts??"");return at>=since&&at<=until}).filter(record=>!query||`${record.body} ${record.fields?.chat??""}`.toLowerCase().includes(query)).slice(0,request.limit??1);if(transient&&session){const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(closed||!owned(session)||options.signal?.aborted)return fail("aborted","WhatsApp read was cancelled before delivery.")}return readResult(SOURCE,records,warnings)},close(){if(closing)return closing;closing=(async()=>{closed=true;clearTimeout(persistTimer);for(const owner of[...pairings]){if(owner.job.state==="waiting-user")failPairing(owner,"aborted","WhatsApp source was closed.");else cleanPairing(owner)}await Promise.allSettled([...initializing]);await writes;if(live){const current=live;await persistNow(current).catch(()=>void 0);stopLive(current)}buffer.clear();names.clear()})();return closing}}}
|
|
1
|
+
import{acquiredReadCapability,unreviewedActionContent}from"@zortexhq/plugin-connector-core/api";import{randomUUID}from"node:crypto";import makeWASocket,{Browsers,DisconnectReason,fetchLatestBaileysVersion,jidDecode}from"baileys";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{openConnectionUrl}from"@zortexhq/plugin-connector-core/browser";import{oauthCredentialResourceId}from"@zortexhq/plugin-vault-sqlite/api";import{sessionStore}from"./auth-state.js";import{toRecords}from"./messages.js";import{openPairingPage}from"./pairing-page.js";import{TransientMessageBuffer,TRANSIENT_MESSAGE_LIMIT}from"./transient-buffer.js";export const SOURCE="whatsapp-web";const silent={level:"silent",child:()=>silent,trace(){},debug(){},info(){},warn(){},error(){},fatal(){}};async function defaultSocket(auth,fullHistory){const version=await Promise.race([fetchLatestBaileysVersion().then(r=>r.version).catch(()=>void 0),new Promise(resolve=>setTimeout(resolve,5e3))]);return makeWASocket({auth,logger:silent,browser:Browsers.macOS("Chrome"),syncFullHistory:fullHistory,markOnlineOnConnect:false,...version?{version}:{}})}const statusCode=update=>update.lastDisconnect?.error?.output?.statusCode;function nativeAccount(socket){const identity=jidDecode(socket?.user?.id);return identity?.server==="s.whatsapp.net"&&/^[1-9][0-9]{4,19}$/u.test(identity.user)?identity.user:void 0}export function createWhatsappProvider({vault,socket,pairingPage=openPairingPage,openUrl=openConnectionUrl,payloadRetention="cache",pairingTimeoutMs=18e4,resumeTimeoutMs=2e4,historyTimeoutMs=3e4}){if(!["cache","transient"].includes(payloadRetention)||[pairingTimeoutMs,resumeTimeoutMs,historyTimeoutMs].some(ms=>!Number.isInteger(ms)||ms<1||ms>6e5))throw Error("Invalid WhatsApp retention or timeout configuration.");const transient=payloadRetention==="transient",makeSocket=socket??(auth=>defaultSocket(auth,!transient));const info={content:[acquiredReadCapability(["plugins/connector-whatsapp/README.md"]),unreviewedActionContent(["plugins/connector-whatsapp/README.md"])],source:SOURCE,label:"WhatsApp",group:"Connector / Chat",auth:"native-browser"};const jobs=new Map,names=new Map,buffer=new TransientMessageBuffer,pairings=new Set;const initializing=new Set;let live,resuming,closed=false,closing;let writes=Promise.resolve();const fail=(code,message)=>businessError(code,message,"plugin");const enqueue=task=>{writes=writes.then(task,task).catch(()=>void 0);return writes};const track=task=>{initializing.add(task);void task.then(()=>initializing.delete(task),()=>initializing.delete(task));return task};const notify=entry=>{for(const wake of entry.waiters)wake()};const owned=(entry,sock=entry.socket)=>!closed&&!entry.stopped&&live===entry&&entry.socket===sock;function remember(jid,name){if(!jid||jid.length>512||!name)return;names.delete(jid);names.set(jid,name.slice(0,256));if(names.size>2e3)names.delete(names.keys().next().value)}function stopLive(entry){entry.stopped=true;entry.online=false;entry.resolveOpen(false);notify(entry);entry.socket?.end();if(live===entry){live=void 0;buffer.clear();names.clear()}}function waitUntil(entry,predicate,timeout,signal){if(predicate())return Promise.resolve(true);if(signal?.aborted||closed||entry.stopped)return Promise.resolve(false);return new Promise(resolve=>{const finish=value=>{clearTimeout(timer);entry.waiters.delete(wake);signal?.removeEventListener("abort",abort);resolve(value)};const wake=()=>{if(predicate())finish(true);else if(closed||entry.stopped)finish(false)};const abort=()=>finish(false),timer=setTimeout(()=>finish(false),timeout);entry.waiters.add(wake);signal?.addEventListener("abort",abort,{once:true});wake()})}async function captureAuthority(accountId,expectedCredential){const custody=vault.bindingCustody;if(!custody)return transient?fail("failed_precondition","Transient WhatsApp requires durable native account custody."):ok(void 0);const selected=await custody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in selected))return selected;if(selected.ok.kind!=="resolved")return fail("failed_precondition","WhatsApp needs one explicit native account binding.");const current=await custody.credentialSnapshot(oauthCredentialResourceId(selected.ok.binding.id),{purpose:"L1",audience:SOURCE});if(!("ok"in current))return current;const value=current.ok;if(value.binding.identity.source!==SOURCE||value.binding.identity.issuer!==SOURCE||value.binding.identity.subject!==accountId||value.binding.identity.tenant!==null||value.material.kind!=="oauth"||value.resource.kind!=="oauth"||value.resource.owner.kind!=="resident"||value.material.credential.clientId!=="whatsapp-linked-device"||!value.grant.scopes.includes("messages.read"))return fail("permission_denied","WhatsApp session custody does not match the selected native account.");if(expectedCredential!==void 0&&value.material.credential.accessToken!==expectedCredential)return fail("failed_precondition","WhatsApp session changed while its stored credentials were being loaded.");return ok({binding:value.binding,grant:value.grant,resource:value.resource})}async function checkAuthority(entry,initializing2=false){if(!entry.accountId||nativeAccount(entry.socket)!==entry.accountId&&!(initializing2&&entry.durable&&entry.socket?.user?.id===void 0))return fail("failed_precondition","WhatsApp signed-in account changed. Reconnect the selected account.");const current=await captureAuthority(entry.accountId);if(!("ok"in current))return current;const expected=entry.authority,latest=current.ok;if(expected&&(!latest||latest.binding.id!==expected.binding.id||latest.binding.revision!==expected.binding.revision||latest.grant.id!==expected.grant.id||latest.grant.revision!==expected.grant.revision||latest.grant.scopeEpoch!==expected.grant.scopeEpoch||latest.resource.id!==expected.resource.id))return fail("permission_denied","WhatsApp account permission changed while the operation was pending.");return ok(latest)}async function persistNow(entry){if(!entry.accountId||!entry.durable||entry.stopped||live!==entry)throw Error("WhatsApp session no longer owns its stored credentials.");const allowed=await checkAuthority(entry,true);if(!("ok"in allowed))throw Error("WhatsApp session permission changed before persistence.");if(entry.stopped||live!==entry)throw Error("WhatsApp session ended before persistence.");if(entry.authority&&allowed.ok?.resource.revision!==entry.authority.resource.revision)throw Error("WhatsApp stored session was replaced by another owner.");const credential={accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]};const saved=allowed.ok&&vault.bindingCustody?await vault.bindingCustody.compareAndSwapResource({...allowed.ok.resource,updatedAt:new Date().toISOString()},{kind:"oauth",credential},allowed.ok.resource.revision):await vault.updateCredential(SOURCE,credential);if(!("ok"in saved))throw Error("WhatsApp session persistence failed.");if(entry.authority&&allowed.ok&&vault.bindingCustody)entry.authority={...entry.authority,resource:saved.ok};const current=await checkAuthority(entry,true);if(!("ok"in current)||entry.stopped||live!==entry||entry.authority&¤t.ok?.resource.revision!==entry.authority.resource.revision)throw Error("WhatsApp session permission changed during persistence.")}function persist(entry){if(!owned(entry))return Promise.reject(Error("WhatsApp session is no longer active."));if(!entry.durable)return Promise.resolve();const saved=entry.sessionWrites.then(()=>persistNow(entry));entry.sessionWrites=saved.catch(()=>{entry.failure="session_persistence_failed";stopLive(entry)});return track(saved)}function store(entry,sock,messages,history=false){if(!owned(entry,sock)||!entry.accountId||nativeAccount(sock)!==entry.accountId||transient&&!entry.online)return;if(transient){for(const message of messages)for(const record of toRecords(entry.accountId,[message],jid=>names.get(jid)))buffer.add(record);if(history||messages.length>0)entry.historyArrived=true;notify(entry);return}const records=toRecords(entry.accountId,messages,jid=>names.get(jid));for(let i=0;i<records.length;i+=100){const batch=records.slice(i,i+100);void enqueue(async()=>{if(!await entry.open||!owned(entry,sock))return;const allowed=await checkAuthority(entry);if(!("ok"in allowed)){stopLive(entry);return}await cache(vault,SOURCE,batch);entry.historyArrived=true;notify(entry)})}}async function markLoggedOut(entry){if(!entry.accountId)return;if(vault.bindingCustody&&entry.authority){const current=await vault.bindingCustody.binding(entry.authority.binding.id);if("ok"in current&¤t.ok?.revision===entry.authority.binding.revision)await vault.bindingCustody.compareAndSwapBinding({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},current.ok.revision)}else{const current=await vault.connection(SOURCE);if("ok"in current&¤t.ok?.accountId===entry.accountId)await vault.saveConnection({...current.ok,state:"disconnected",updatedAt:new Date().toISOString()},{accessToken:entry.store.serialize(),clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]})}}async function start(serialized,accountId,authority,onView,onOpen,onFailure){if(closed)throw Error("inactive");let resolveOpen;const open=new Promise(resolve=>{resolveOpen=resolve});const current={store:sessionStore(serialized,()=>persist(current)),open,resolveOpen,...accountId?{accountId}:{},...authority?{authority}:{},online:false,stopped:false,historyArrived:false,needsPairing:false,waiters:new Set,durable:serialized!==void 0,sessionWrites:Promise.resolve()};live=current;buffer.clear();names.clear();let restarts=0,generation=0;const failed=code=>{current.failure=code;stopLive(current);onFailure?.(code)};const connect=async()=>{if(!owned(current))return;const attempt=++generation,previous=current.socket;delete current.socket;previous?.end();const ownsAttempt=()=>owned(current)&&attempt===generation;const auth={creds:current.store.state.creds,keys:{get:async(type,ids)=>{if(!ownsAttempt())throw Error("WhatsApp socket was replaced.");return current.store.state.keys.get(type,ids)},set:async data=>{if(!ownsAttempt())throw Error("WhatsApp socket was replaced.");await current.store.state.keys.set(data)}}};const sock=await track(makeSocket(auth));if(!owned(current)||attempt!==generation){sock.end();return}current.socket=sock;sock.ev.on("creds.update",()=>{if(owned(current,sock))void persist(current).catch(()=>{})});sock.ev.on("connection.update",update=>{if(!owned(current,sock))return;if(update.qr){current.needsPairing=true;onView?.({state:"qr",qr:update.qr});notify(current)}if(update.connection==="open"){const linked=nativeAccount(sock);if(!linked||current.accountId&¤t.accountId!==linked){failed("account_changed");return}current.accountId=linked;void(async()=>{const completed=await onOpen?.(current);if(!owned(current,sock))return;const captured=current.authority?await checkAuthority(current):await captureAuthority(linked,completed?.credential);if(!("ok"in captured)){failed("account_permission_changed");return}if(!owned(current,sock))return;if(!current.authority)current.authority=captured.ok;current.durable=true;await persist(current);if(!owned(current,sock))return;current.online=true;current.needsPairing=false;restarts=0;resolveOpen(true);notify(current);completed?.complete()})().catch(()=>failed("pairing_unavailable"))}if(update.connection==="close"){current.online=false;notify(current);const code=statusCode(update);if(code===DisconnectReason.loggedOut){current.needsPairing=true;void enqueue(()=>markLoggedOut(current));failed("qr_scan_required");return}if(code!==DisconnectReason.connectionReplaced&&restarts++<5){void connect().catch(()=>failed("connection_unavailable"));return}failed("connection_unavailable")}});sock.ev.on("messaging-history.set",({chats,contacts,messages})=>{if(!owned(current,sock))return;for(const chat of chats)remember(chat.id,chat.name);for(const contact of contacts)remember(contact.id,contact.name??contact.notify);store(current,sock,messages,true)});sock.ev.on("chats.upsert",chats=>{if(owned(current,sock))for(const chat of chats)remember(chat.id,chat.name)});sock.ev.on("contacts.upsert",contacts=>{if(owned(current,sock))for(const contact of contacts)remember(contact.id,contact.name??contact.notify)});sock.ev.on("messages.upsert",({messages})=>{if(!owned(current,sock))return;for(const message of messages)if(!message.key.fromMe)remember(message.key.remoteJid,message.key.remoteJid?.endsWith("@g.us")?void 0:message.pushName);store(current,sock,messages)})};try{await connect()}catch(error){failed("connection_unavailable");throw error}return current}async function resume(){if(live&&!live.stopped)return live;if(resuming)return resuming;resuming=(async()=>{const connection=await vault.connection(SOURCE);if(!("ok"in connection))throw Error("account_permission_changed");if(connection.ok?.state!=="connected"||!connection.ok.accountId)return void 0;const grant=await vault.credential(SOURCE);if(!("ok"in grant))throw Error("account_permission_changed");const authority=await captureAuthority(connection.ok.accountId,grant.ok.accessToken);if(!("ok"in authority))throw Error("account_permission_changed");return start(grant.ok.accessToken,connection.ok.accountId,authority.ok)})();try{return await resuming}finally{resuming=void 0}}function cleanPairing(pair2){clearTimeout(pair2.timer);pair2.removeAbort?.();pair2.page?.close();pairings.delete(pair2)}function failPairing(pair2,code,message){if(pair2.job.state==="waiting-user"){pair2.job.state="failed";pair2.job.error={code,message};delete pair2.job.authorizationUrl;delete pair2.job.instructions;pair2.stop.abort();pair2.page?.update({state:"failed",message});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live)}cleanPairing(pair2)}function cancelPairing(pair2){if(pair2.job.state==="waiting-user")pair2.job.state="cancelled";delete pair2.job.authorizationUrl;delete pair2.job.instructions;delete pair2.job.error;pair2.stop.abort();pair2.page?.update({state:"failed",message:"WhatsApp connection was cancelled."});if(pair2.entry)stopLive(pair2.entry);else if(live&&!live.online)stopLive(live);cleanPairing(pair2)}async function pair(job,options,expectedAccountId){if(closed)throw Error("inactive");const owner={job,stop:new AbortController};pairings.add(owner);const abort=()=>failPairing(owner,"aborted","WhatsApp connection was cancelled.");options.signal?.addEventListener("abort",abort,{once:true});owner.removeAbort=()=>options.signal?.removeEventListener("abort",abort);try{owner.page=await pairingPage();if(closed||options.signal?.aborted||owner.stop.signal.aborted){abort();return}job.authorizationUrl=owner.page.url;job.instructions="Open the QR code page, then use WhatsApp on your phone: Settings \u2192 Linked devices \u2192 Link a device. The connection continues automatically after scanning.";job.error={code:"qr_scan_required",message:"Scan the WhatsApp QR code with your phone."};owner.timer=setTimeout(()=>failPairing(owner,"pairing_timeout","WhatsApp QR was not scanned before it expired."),pairingTimeoutMs);owner.timer.unref?.();if(live)stopLive(live);owner.entry=await start(void 0,expectedAccountId,void 0,view=>{if(job.state==="waiting-user")owner.page?.update(view)},async current=>{if(job.state==="connected"&&!closed)return;if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)throw Error("aborted");const credential=current.store.serialize();const saved=await vault.saveConnection({source:SOURCE,provider:SOURCE,account:current.socket?.user?.name?.slice(0,256)||"WhatsApp",accountId:current.accountId,scopes:["messages.read"],state:"connected",updatedAt:new Date().toISOString()},{accessToken:credential,clientId:"whatsapp-linked-device",expiresAt:0,scopes:["messages.read"]},{signal:owner.stop.signal});if(!("ok"in saved))throw Error("custody_failed");return{credential,complete:()=>{if(job.state!=="waiting-user"||closed||owner.stop.signal.aborted)return;clearTimeout(owner.timer);owner.removeAbort?.();job.state="connected";job.account=saved.ok.account;delete job.instructions;delete job.authorizationUrl;delete job.error;owner.page?.update({state:"connected"});owner.timer=setTimeout(()=>cleanPairing(owner),1e4);owner.timer.unref?.()}}},code=>failPairing(owner,code,code==="account_changed"?"The scanned WhatsApp account does not match the selected account.":"WhatsApp pairing did not complete."));if(owner.stop.signal.aborted)stopLive(owner.entry);if(!options.automatic&&options.manualPresentation!=="return-url"&&job.state==="waiting-user")await openUrl(owner.page.url)}catch{failPairing(owner,"pairing_unavailable","WhatsApp pairing page or connection could not start.")}}return{info,...transient?{}:{requiresPersistentPayloads:true},status:()=>connectionState(vault,info),job(id){const job=jobs.get(id);return job?ok({...job}):fail("not_found","WhatsApp connection job not found.")},cancelJob(id){const job=jobs.get(id);if(!job)return ok({id,cleanup:"confirmed"});const pairing=[...pairings].find(owner=>owner.job===job);if(pairing)cancelPairing(pairing);else if(job.state==="waiting-user")job.state="cancelled";delete job.authorizationUrl;delete job.instructions;return ok({id,cleanup:[...pairings].some(owner=>owner.job===job)?"pending":"confirmed"})},async connect(options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");const running=[...jobs.values()].find(job2=>job2.state==="waiting-user");if(running)return ok({...running});for(const[id,job2]of jobs)if(jobs.size>=32&&job2.state!=="waiting-user")jobs.delete(id);const job={id:randomUUID(),source:SOURCE,state:"waiting-user",startedAt:new Date().toISOString()};jobs.set(job.id,job);try{const selected=await vault.connection(SOURCE);if(!("ok"in selected))return selected;if(selected.ok&&!selected.ok.accountId)return fail("failed_precondition","WhatsApp needs a verified native account binding.");if(options.expectedBinding?.kind==="legacy-source"&&options.expectedBinding.source!==SOURCE)return fail("invalid_argument","WhatsApp account selection names another source.");if(options.expectedBinding?.kind==="binding"){const binding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if(!("ok"in binding)||binding.ok.kind!=="resolved"||binding.ok.binding.id!==options.expectedBinding.bindingId)return fail("failed_precondition","WhatsApp account selection does not match this linked device.")}if(closed)return fail("unavailable","WhatsApp source is inactive.");const resumed=await track(resume());if(resumed){await waitUntil(resumed,()=>resumed.online||resumed.needsPairing,resumeTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp connection cancelled.");if(resumed.online){const allowed=await checkAuthority(resumed);if(!("ok"in allowed))return allowed;job.state="connected";if(selected.ok)job.account=selected.ok.account;return ok({...job})}if(!resumed.needsPairing){job.state="failed";job.error={code:resumed.failure??"connection_unavailable",message:resumed.failure==="account_changed"?"WhatsApp signed in as a different account.":"The existing WhatsApp session did not reconnect."};return ok({...job})}}if(options.automatic&&!transient){job.state="failed";job.error={code:"qr_scan_required",message:"WhatsApp needs one QR scan from the phone; connect it explicitly."};return ok({...job})}if(options.automatic&&selected.ok?.accountId&&vault.bindingCustody){const selectedBinding=await vault.bindingCustody.resolve({kind:"legacy-source",source:SOURCE});if("ok"in selectedBinding&&selectedBinding.ok.kind==="resolved"){const grant=await vault.bindingCustody.grantForBinding(selectedBinding.ok.binding.id,"L1",SOURCE);if(!("ok"in grant))return grant;if(grant.ok?.state==="revoked")return fail("permission_denied","WhatsApp access was revoked. Reconnect explicitly to grant it again.")}}await track(pair(job,options,selected.ok?.accountId))}catch{job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp session permission or connection could not be verified."}}finally{if(job.state==="waiting-user"&&![...pairings].some(owner=>owner.job===job)){job.state="failed";job.error={code:"connection_unavailable",message:"WhatsApp did not start an owned connection job."}}}return ok({...job})},async read(request,options={}){if(closed)return fail("unavailable","WhatsApp source is inactive.");const invalid=validateRead(request);if(invalid)return invalid;if(request.fileId!==void 0)return fail("invalid_argument","WhatsApp message reads support limit, query and time filters; file download is not supported.");if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const connection=await vault.connection(SOURCE);if(!("ok"in connection))return connection;if(connection.ok?.state!=="connected"||!connection.ok.accountId)return fail("unauthenticated","Connect WhatsApp by scanning its QR code first.");const session=await track(resume()).catch(()=>void 0);const online=session?await waitUntil(session,()=>session.online,resumeTimeoutMs,options.signal):false;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const warnings=[];let records;if(transient){if(!online||!session)return fail("unavailable","WhatsApp is offline; transient reads need the selected live session.");const allowed=await checkAuthority(session);if(!("ok"in allowed)){stopLive(session);return allowed}await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal);if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");if(!owned(session)||!session.online)return fail("unavailable","WhatsApp session ended before the message read.");const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(!session.historyArrived)return fail("unavailable","No live WhatsApp message batch has arrived for this session yet. Retry after the phone finishes linking or a message arrives.");records=buffer.snapshot();warnings.push(`This live session retains at most ${TRANSIENT_MESSAGE_LIMIT} messages and 4 MiB in memory. Messages are not saved and are cleared on restart.`)}else{if(!online)warnings.push("WhatsApp is offline right now; showing messages already saved in the Vault.");if(online&&session&&!session.historyArrived){const stored2=await vault.records(SOURCE,1);if(!("ok"in stored2)||!stored2.ok.length)await waitUntil(session,()=>session.historyArrived,historyTimeoutMs,options.signal)}await writes;if(options.signal?.aborted)return fail("aborted","WhatsApp read cancelled.");const stored=await vault.records(SOURCE,100);if(!("ok"in stored))return stored;records=stored.ok.map(row=>row.data);if(request.query||request.since||request.until)warnings.push("Filters apply to the 100 most recent saved messages; use SQL search over z_records for older history.")}const since=request.since?Date.parse(request.since):-Infinity,until=request.until?Date.parse(request.until):Infinity,query=request.query?.toLowerCase();records=records.filter(record=>record.sourceId?.startsWith(connection.ok.accountId+":")).filter(record=>{const at=Date.parse(record.ts??"");return at>=since&&at<=until}).filter(record=>!query||`${record.body} ${record.fields?.chat??""}`.toLowerCase().includes(query)).slice(0,request.limit??1);if(transient&&session){const current=await checkAuthority(session);if(!("ok"in current)){stopLive(session);return current}if(closed||!owned(session)||options.signal?.aborted)return fail("aborted","WhatsApp read was cancelled before delivery.")}return readResult(SOURCE,records,warnings)},close(){if(closing)return closing;closing=(async()=>{closed=true;for(const owner of[...pairings]){if(owner.job.state==="waiting-user")failPairing(owner,"aborted","WhatsApp source was closed.");else cleanPairing(owner)}await Promise.allSettled([...initializing]);await writes;if(live){const current=live;await persistNow(current).catch(()=>void 0);stopLive(current)}buffer.clear();names.clear()})();return closing}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pinnedMethods}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";export const youtubeContent=[...["channels","subscriptions","playlists","playlistItems","videos","commentThreads"].map(resource=>({resource:`account/${resource}`,read:"implemented",acquisition:"collection",persistence:"durable",readFields:["selected-parts"],storedFields:["selected-parts"],updates:"rescan",evidence:["https://developers.google.com/youtube/v3/docs","src/full-sync.ts"],limitations:["Authorized account walk only; parts, quota and partialReasons bound coverage; inline comment replies are not complete reply history."]})),...[...pinnedMethods,...creatorMethods].filter(m=>m.httpMethod==="GET").map(m=>({resource:m.id,read:m.scopes?.length&&!m.id.endsWith(".stream")?"implemented":"unimplemented",acquisition:"lookup",persistence:"unimplemented",readFields:m.supportsMediaDownload?["content","mime"]:["data","items","nextPageToken"],storedFields:[],updates:"lookup",evidence:["src/discovery-data.ts","src/creator-data.ts","src/source.ts"],limitations:["Selected parameters, scopes and provider admission apply. No automatic durable path for this selected-method response."]})),...["personal-search-history","watch-history","watch-later","complete-authored-comment-history"].map(resource=>({resource,read:"unsupported",acquisition:"none",persistence:"not-applicable",readFields:[],storedFields:[],updates:"none",evidence:["src/full-sync.ts"],limitations:["Unavailable through the reviewed Data API path; explicit user exports are a separate acquisition path."]}))];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{Original}from"@zortexhq/plugin-connector-framework/api";import{manifest as sourceManifest}from"./discovery-data.js";import{object}from"./schema.js";const READONLY="https://www.googleapis.com/auth/youtube.readonly";export const YOUTUBE_READ_SCOPES=Object.freeze([READONLY,"https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]);const API="https://www.googleapis.com/youtube/v3/";const HOUR=36e5,DAY=24*HOUR;const UNKNOWN_TS="1970-01-01T00:00:00.000Z";const MAX_WALK_PAGES=2e5,HEAD_IDS=3,COMMENT_SLACK_MS=DAY,QUOTA_SLACK_MS=6e4;export const YOUTUBE_INCREMENTAL_EVERY_MS=6*HOUR,YOUTUBE_FULL_EVERY_MS=7*DAY;const READ_STREAMS=["channels","subscriptions","playlists","playlistItems","videos","commentThreads"];const LISTED_ONLY=["comments","search","captions","members"];const STATIC_REASONS={channels:["brand-channels-need-own-grant"],playlistItems:["watch-history-not-in-api","watch-later-not-in-api"],comments:["authored-comments-not-in-api"],search:["search-history-not-in-api"],captions:["captions-need-force-ssl-scope"],members:["memberships-need-creator-scope"]};export const youtubeSyncManifest=(()=>{const wanted=new Set([...READ_STREAMS,...LISTED_ONLY]),copy=structuredClone(sourceManifest);delete copy.actionScopes;return{...copy,streams:copy.streams.filter(stream=>wanted.has(stream.stream)),actions:[]}})();const PHASES=["channels","subscriptions","playlists","playlistItems","uploads","likes","dislikes","comments","done"];const text=value=>typeof value==="string"?value.trim():"";const json=value=>JSON.parse(JSON.stringify(value));const instant=(...values)=>{for(const value of values)if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return UNKNOWN_TS};const reasonCode=(reason,fallback)=>(reason??"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||fallback;const shortHash=value=>createHash("sha256").update(value).digest("hex").slice(0,10);export function nextPacificMidnight(nowMs){const at=Math.floor(nowMs/1e3)*1e3;try{const parts=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}).formatToParts(new Date(at)).map(part=>[part.type,part.value]));const[y,m,d]=[Number(parts.year),Number(parts.month),Number(parts.day)];const offset=Date.UTC(y,m-1,d,Number(parts.hour),Number(parts.minute),Number(parts.second))-at;const next=Date.UTC(y,m-1,d+1)-offset;if(Number.isFinite(next)&&next>at)return next}catch{}return Math.floor((at-8*HOUR)/DAY+1)*DAY+8*HOUR}function stringRecord(value){return object(value)&&Object.values(value).every(item=>typeof item==="string")}function parseMarks(value){if(!object(value))return null;const marks={};if(value.since!==void 0){if(typeof value.since!=="string"||!Number.isFinite(Date.parse(value.since)))return null;marks.since=value.since}if(value.heads!==void 0){if(!object(value.heads)||!Object.values(value.heads).every(ids=>Array.isArray(ids)&&ids.every(id=>typeof id==="string")))return null;marks.heads=value.heads}if(value.tags!==void 0){if(!stringRecord(value.tags))return null;marks.tags=value.tags}return marks}function parseWalk(wire){if(!object(wire))return null;const w=wire;const strings=value=>Array.isArray(value)&&value.every(item=>typeof item==="string");const optionalInstant=value=>value===void 0||typeof value==="string"&&Number.isFinite(Date.parse(value));if(typeof w.account!=="string"||!w.account||w.mode!=="full"&&w.mode!=="incremental"||typeof w.startedAt!=="string"||!Number.isFinite(Date.parse(w.startedAt)))return null;if(!PHASES.includes(w.phase)||w.token!==null&&typeof w.token!=="string"||!Number.isSafeInteger(w.pages)||Number(w.pages)<0)return null;if(!strings(w.channels)||!strings(w.uploads)||w.channels.length!==w.uploads.length||!Number.isSafeInteger(w.at)||Number(w.at)<0)return null;if(!Array.isArray(w.queue)||!w.queue.every(entry=>Array.isArray(entry)&&entry.length===2&&entry.every(part=>typeof part==="string"))||w.more!==null&&typeof w.more!=="string")return null;const prior=parseMarks(w.prior),next=parseMarks(w.next);if(!prior||!next||!object(w.gaps)||!Object.values(w.gaps).every(n=>Number.isSafeInteger(n)&&Number(n)>=0))return null;if(!optionalInstant(w.completedAt)||!optionalInstant(w.fullAt)||!optionalInstant(w.quotaUntil)||w.phase==="done"&&w.completedAt===void 0)return null;return{account:w.account,mode:w.mode,startedAt:w.startedAt,phase:w.phase,token:w.token,pages:Number(w.pages),channels:[...w.channels],uploads:[...w.uploads],at:Number(w.at),queue:w.queue.map(([id,tag])=>[id,tag]),more:w.more,prior,next,gaps:{...w.gaps},...w.completedAt===void 0?{}:{completedAt:w.completedAt},...w.fullAt===void 0?{}:{fullAt:w.fullAt},...w.quotaUntil===void 0?{}:{quotaUntil:w.quotaUntil}}}function stable(value,stream,depth=0){if(Array.isArray(value))return value.map(item=>stable(item,stream,depth+1));if(!object(value))return value;const out={};for(const[key,item]of Object.entries(value)){if(key==="etag"||depth===0&&key==="statistics")continue;if(stream==="commentThreads"&&(key==="likeCount"||key==="viewerRating"||key==="canRate"))continue;out[key]=stable(item,stream,depth+1)}return out}function snippet(item){return object(item.snippet)?item.snippet:{}}function commentLine(comment){const s=object(comment)&&object(comment.snippet)?comment.snippet:{};const said=text(s.textOriginal)||text(s.textDisplay);return said?[text(s.authorDisplayName),said].filter(Boolean).join(": "):""}function describe(stream,raw){const item=raw.item,s=snippet(item),title=text(s.title);const lines=(...parts)=>parts.filter(Boolean).join("\n");switch(stream){case"channels":return{title,ts:instant(s.publishedAt),body:lines("YouTube channel: "+title,text(s.customUrl),text(s.description))};case"subscriptions":return{title,ts:instant(s.publishedAt),body:lines("Subscribed to: "+title,text(s.description))};case"playlists":return{title,ts:instant(s.publishedAt),body:lines("Playlist: "+title,text(s.description))};case"playlistItems":{const details=object(item.contentDetails)?item.contentDetails:{};const owner=text(s.videoOwnerChannelTitle);return{title,ts:instant(s.publishedAt,details.videoPublishedAt),body:lines((raw.via==="uploads"?"Uploaded: ":"In playlist: ")+title,owner?"by "+owner:"",text(s.description))}}case"videos":{const tags=Array.isArray(s.tags)?s.tags.filter(tag=>typeof tag==="string"):[];const channel=text(s.channelTitle);return{title,ts:instant(s.publishedAt),body:lines((raw.via==="dislike"?"Disliked video: ":"Liked video: ")+title,channel?"by "+channel:"",text(s.description),tags.join(", "))}}case"commentThreads":{const top=s.topLevelComment,first=commentLine(top),replies=object(item.replies)&&Array.isArray(item.replies.comments)?item.replies.comments.map(commentLine).filter(Boolean):[];const topSnippet=object(top)&&object(top.snippet)?top.snippet:{};return{title:first.slice(0,120),ts:instant(topSnippet.updatedAt,topSnippet.publishedAt),body:lines(first,...replies)}}default:throw Error("YouTube full sync does not normalize stream "+stream+".")}}export function createYouTubeProvider({parts,auth,vault,now=()=>new Date().toISOString(),incrementalEveryMs=YOUTUBE_INCREMENTAL_EVERY_MS,fullEveryMs=YOUTUBE_FULL_EVERY_MS}){if(!Number.isFinite(incrementalEveryMs)||incrementalEveryMs<0||!Number.isFinite(fullEveryMs)||fullEveryMs<0)throw Error("YouTube sync pacing must be non-negative milliseconds.");const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser"};const stop=new AbortController,pending=new Set;let closed=false;let latest=null;const codec=parts.cursorCodecV1({source:"youtube",version:2,versionKey:"v",validate:parseWalk});const fail=(code,message,retryability="non-retryable",cause)=>parts.connectorError(code,message,retryability,cause);const inactive=()=>fail("aborted","YouTube source is inactive.");const owned=task=>{const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled};const declared=new Map(youtubeSyncManifest.streams.map(stream=>[stream.stream,stream]));async function resolveGrant(){if(closed)return inactive();const connection=await vault.connection("youtube");if(!("ok"in connection))return"err"in connection?connection:fail("data_loss","YouTube connection metadata was unconfirmed.");const row=connection.ok;if(!row||row.state!=="connected")return fail("unauthenticated","Connect YouTube before syncing it.");if(typeof row.accountId!=="string"||!row.accountId.trim())return fail("failed_precondition","YouTube sync needs the verified Google subject; an email or grant id is never the account identity.");const scope=YOUTUBE_READ_SCOPES.find(candidate=>row.scopes.includes(candidate));if(!scope)return fail("permission_denied","The YouTube connection has no read scope; reconnect YouTube.");if(closed)return inactive();return Original.ok({id:"0"+createHash("sha256").update(row.accountId).digest("hex").slice(0,25).toUpperCase(),source:"youtube",account:row.accountId,scopes:[scope],expiresAt:new Date(Date.parse(now())+HOUR).toISOString()})}function checkGrant(grant){if(grant.source!=="youtube"||!grant.account?.trim())return fail("permission_denied","YouTube grant is not bound to a verified account.");if(!grant.scopes.some(scope=>YOUTUBE_READ_SCOPES.includes(scope)))return fail("permission_denied","YouTube grant has no read scope.");return void 0}async function fence(grant){if(closed||stop.signal.aborted)return inactive();const current=await vault.connection("youtube");if(!("ok"in current))return"err"in current?current:fail("data_loss","YouTube account fence was unconfirmed.");if(closed||stop.signal.aborted)return inactive();const row=current.ok;if(!row||row.state!=="connected")return fail("unauthenticated","YouTube was disconnected during the sync.");if(row.accountId!==grant.account)return fail("permission_denied","The YouTube account changed during the sync; nothing from the old grant is attributed to the new account.");if(!grant.scopes.every(scope=>row.scopes.includes(scope)))return fail("permission_denied","YouTube read consent was withdrawn.");return Original.ok(void 0)}async function call(grant,listing2,token){const url=new URL(listing2.resource,API);for(const[key,value]of Object.entries(listing2.params))url.searchParams.set(key,value);if(token)url.searchParams.set("pageToken",token);const before=await fence(grant);if(!Original.isOk(before))return before;const reply=await auth.requestRaw("youtube",url.href,{signal:stop.signal});if(closed||stop.signal.aborted)return inactive();if(!("ok"in reply)){const err="err"in reply?reply.err:void 0;if(!err||err.code==="unavailable"||err.code==="aborted")return fail("unavailable","A YouTube list request did not complete (network or request timeout); the page is retried from the same cursor.","transient",err);return reply}const after=await fence(grant);if(!Original.isOk(after))return after;return reply}function soleChannel(walk){return walk.channels.length===1?walk.channels[0]:null}function listing(walk){const page2=(resource,params)=>({resource,params:{...params,maxResults:"50"}});switch(walk.phase){case"channels":return{...page2("channels",{part:"snippet,contentDetails,brandingSettings,status,topicDetails,localizations",mine:"true"}),stream:"channels",via:"mine",owner:null};case"subscriptions":return{...page2("subscriptions",{part:"snippet",mine:"true"}),stream:"subscriptions",via:"subscription",owner:soleChannel(walk)};case"playlists":return{...page2("playlists",{part:"snippet,contentDetails,status,localizations",mine:"true"}),stream:"playlists",via:"playlist",owner:soleChannel(walk)};case"playlistItems":{const id=walk.queue[0][0];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"playlist",owner:soleChannel(walk),playlistId:id}}case"uploads":{const id=walk.uploads[walk.at];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"uploads",owner:walk.channels[walk.at],playlistId:id,head:"uploads:"+id}}case"likes":case"dislikes":{const rating=walk.phase==="likes"?"like":"dislike";return{...page2("videos",{part:"snippet,contentDetails,status,topicDetails",myRating:rating}),stream:"videos",via:rating,owner:soleChannel(walk),head:rating}}case"comments":return{resource:"commentThreads",params:{part:"snippet,replies",allThreadsRelatedToChannelId:walk.channels[walk.at],maxResults:"100",order:"time",textFormat:"plainText"},stream:"commentThreads",via:"channel-comments",owner:walk.channels[walk.at],byTime:true};case"done":throw Error("A completed YouTube walk has no listing.")}}function settle(walk){for(;;){if(walk.phase==="playlistItems"&&!walk.queue.length){if(walk.more!==null){walk.phase="playlists";walk.token=walk.more;walk.more=null}else{walk.phase="uploads";walk.at=0;walk.token=null}continue}if(walk.phase==="uploads"){while(walk.at<walk.channels.length&&!walk.uploads[walk.at])walk.at++;if(walk.at>=walk.channels.length){walk.phase="likes";walk.at=0;walk.token=null;continue}}if(walk.phase==="comments"&&walk.at>=walk.channels.length){walk.phase="done";walk.token=null;continue}return}}function finish(walk,read){switch(walk.phase){case"channels":walk.phase="subscriptions";break;case"subscriptions":walk.phase="playlists";walk.more=null;break;case"playlists":walk.phase="playlistItems";walk.queue=[];walk.more=null;break;case"playlistItems":{const[id,tag]=walk.queue.shift();if(read)walk.next.tags={...walk.next.tags,[id]:tag};break}case"uploads":walk.at++;break;case"likes":walk.phase="dislikes";break;case"dislikes":walk.phase="comments";walk.at=0;break;case"comments":walk.at++;break;case"done":break}walk.token=null}function gap(walk,stream,reason,count=1){const key=stream+":"+reason;walk.gaps[key]=(walk.gaps[key]??0)+count}function begin(account,mode,prior,fullAt,at){return{account,mode,startedAt:at,phase:"channels",token:null,pages:0,channels:[],uploads:[],at:0,queue:[],more:null,prior:mode==="full"?{}:prior,next:{},gaps:{},...fullAt===void 0?{}:{fullAt}}}function complete(walk,at){return{...walk,phase:"done",token:null,at:0,queue:[],more:null,prior:{...walk.next,since:walk.startedAt},next:{},completedAt:at,...walk.mode==="full"?{fullAt:at}:{}}}function encode(walk,notes){let attempt=codec.encode(walk);if("ok"in attempt)return attempt;if(walk.prior.tags||walk.next.tags){const{tags:_p,...prior}=walk.prior,{tags:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: playlist-marks-dropped \u2014 remembered playlist versions were dropped to keep the cursor within "+Original.SYNC_CURSOR_MAX_CHARS+" chars; those playlists are read in full");attempt=codec.encode(walk);if("ok"in attempt)return attempt}if(walk.prior.heads||walk.next.heads){const{heads:_p,...prior}=walk.prior,{heads:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: head-marks-dropped \u2014 remembered list heads were dropped to keep the cursor bounded; those lists are read in full");attempt=codec.encode(walk)}return attempt}function page(items,walk,exhausted,notes){latest=walk;const next=encode(walk,notes);if(!("ok"in next))return next;return Original.ok({items,next:next.ok,exhausted,...notes.length?{notes}:{}})}function respond(items,walk,at,notes){return walk.phase==="done"?page(items,complete(walk,at),true,notes):page(items,walk,false,notes)}function quotaWait(until){return fail("resource_exhausted","YouTube daily quota is exhausted (youtube-daily-quota-exhausted): the project's YouTube Data API units for today are used up. Quota backoff not due until "+until+", when Google resets the quota at midnight Pacific Time; the walk then resumes from its saved cursor and nothing is skipped.","retry-at-higher-level")}const RATE_LIMIT=new Set(["rateLimitExceeded","userRateLimitExceeded","RATE_LIMIT_EXCEEDED"]),DAILY=new Set(["quotaExceeded","dailyLimitExceeded"]),GRANT=new Set(["insufficientPermissions","authError","unauthorized","PERMISSION_DENIED","UNAUTHENTICATED"]);function classify(walk,reply){const what=walk.phase==="uploads"||walk.phase==="playlistItems"?"playlistItems.list":walk.phase==="likes"||walk.phase==="dislikes"?"videos.list":walk.phase==="comments"?"commentThreads.list":walk.phase+".list";if(reply.status===200){let data;try{data=JSON.parse(reply.body)}catch{return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a body that is not JSON; the page is asked again.","transient").err}}if(!object(data)||data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item)))||data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a malformed list; the page is asked again.","transient").err};return{kind:"ok",data}}const reason=parts.googleErrorReasonV1(reply.body);if((reply.status===403||reply.status===429)&&reason!==void 0&&DAILY.has(reason))return{kind:"quota"};const status=()=>parts.webStatusErrorV1(reply.status,{provider:"YouTube",what,headers:reply.headers,...reason?{detail:reason}:{},bodyOverride:code=>code===403&&reason!==void 0&&RATE_LIMIT.has(reason)?{code:"resource_exhausted",retryability:"throttling",meaning:"the provider throttled the call ("+reason+")"}:void 0})??fail("internal","YouTube "+what+" returned HTTP "+reply.status+".").err;if(reply.status===429||reply.status===403&&reason!==void 0&&RATE_LIMIT.has(reason))return{kind:"err",err:status()};if(reason==="youtubeSignupRequired"&&(reply.status===401||reply.status===403))return{kind:"gap",reason:"youtube-signup-required"};if(reply.status===401)return{kind:"err",err:status()};if(reply.status===403){if(walk.phase==="channels"||reason===void 0||GRANT.has(reason))return{kind:"err",err:status()};return{kind:"gap",reason:reasonCode(reason,"forbidden")}}if(reply.status===404)return{kind:"gap",reason:reasonCode(reason,"not-found")};if(reply.status===400&&reason==="invalidPageToken"&&walk.token!==null)return{kind:"restart"};return{kind:"err",err:status()}}async function pullInner(grant,cursor){const invalid=checkGrant(grant);if(invalid)return invalid;if(closed)return inactive();const notes=[],nowMs=Date.parse(now()),nowIso=new Date(nowMs).toISOString();let walk=cursor===null?null:codec.decode(cursor);if(cursor!==null&&walk===null)notes.push("youtube: cursor-unreadable \u2014 the walk starts again from the first list");if(walk&&walk.account!==grant.account){notes.push("youtube: account-changed \u2014 the walk starts again for the connected account");walk=null}if(walk?.quotaUntil!==void 0){if(nowMs<Date.parse(walk.quotaUntil)){latest=walk;return quotaWait(walk.quotaUntil)}const{quotaUntil:_q,...resumed}=walk;walk=resumed;notes.push("youtube: quota-reset \u2014 the walk resumes where the daily quota stopped it")}if(!walk){walk=begin(grant.account,"full",{},void 0,nowIso);notes.push("youtube: full-pass \u2014 every list is read")}else if(walk.phase==="done"){const due=Date.parse(walk.completedAt)+incrementalEveryMs;if(nowMs<due&&cursor!==null){latest=walk;return Original.ok({items:[],next:cursor,exhausted:true,notes:[...notes,"youtube: pass-not-due \u2014 the next pass starts after "+new Date(due).toISOString()+" (quota pacing)"]})}const full=walk.fullAt===void 0||nowMs-Date.parse(walk.fullAt)>=fullEveryMs;walk=begin(grant.account,full?"full":"incremental",walk.prior,walk.fullAt,nowIso);notes.push(full?"youtube: full-pass \u2014 every list is read again (periodic re-walk)":"youtube: incremental-pass \u2014 cheap lists re-listed, unchanged playlists skipped, newest-first lists stop at the remembered head")}settle(walk);if(walk.phase==="done")return page([],complete(walk,nowIso),true,notes);if(walk.pages>=MAX_WALK_PAGES)return fail("resource_exhausted","YouTube walk exceeded "+MAX_WALK_PAGES+" provider pages; the cursor is kept.");const current=listing(walk),reply=await call(grant,current,walk.token);if(!("ok"in reply))return"err"in reply?reply:fail("data_loss","YouTube request result was unconfirmed.");walk.pages++;const outcome=classify(walk,reply.ok),stream=current.stream,items=[];if(outcome.kind==="err")return{err:outcome.err};if(outcome.kind==="quota"){walk.quotaUntil=new Date(nextPacificMidnight(nowMs)+QUOTA_SLACK_MS).toISOString();notes.push("youtube: youtube-daily-quota-exhausted \u2014 no request until "+walk.quotaUntil+"; the walk resumes at this list");return page([],walk,false,notes)}if(outcome.kind==="restart"){walk.token=null;notes.push("youtube: page-token-expired \u2014 this list is read again from its first page");return page([],walk,false,notes)}if(outcome.kind==="gap"){const reason=walk.phase==="channels"&&outcome.reason==="youtube-signup-required"?"no-youtube-channel":outcome.reason;gap(walk,stream,reason);notes.push("youtube: "+stream+" not read \u2014 "+reason+" (HTTP "+reply.ok.status+")");finish(walk,false);settle(walk);return respond(items,walk,nowIso,notes)}const data=outcome.data,rows=Array.isArray(data.items)?data.items:[],nextToken=typeof data.nextPageToken==="string"?data.nextPageToken:null;const ids=[];let missing=0,unavailable=0;for(const item of rows){const id=typeof item.id==="string"&&item.id?item.id:"";if(!id){missing++;continue}ids.push(id);const s=snippet(item);const owner=walk.phase==="channels"?id:current.via==="subscription"||current.via==="playlist"?text(s.channelId)||current.owner:current.owner;const raw={account:walk.account,channelId:owner,via:current.via,...current.playlistId?{playlistId:current.playlistId}:{},item};items.push({streamRef:stream,raw:json(raw)});if(stream==="playlistItems"&&(s.title==="Private video"||s.title==="Deleted video"))unavailable++}if(missing){gap(walk,stream,"item-without-id",missing);notes.push("youtube: "+stream+" item-without-id \u2014 "+missing+" item(s) without a provider id were not stored")}if(unavailable){gap(walk,"playlistItems","video-unavailable",unavailable);notes.push("youtube: video-unavailable \u2014 "+unavailable+" playlist item(s) point to a private or deleted video; only the placeholder is stored")}if(walk.phase==="channels"){for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)&&object(item.contentDetails.relatedPlaylists)?item.contentDetails.relatedPlaylists:{};walk.channels.push(item.id);walk.uploads.push(text(details.uploads))}if(!nextToken&&!walk.channels.length){gap(walk,"channels","no-youtube-channel");notes.push("youtube: channels not read \u2014 no-youtube-channel (this identity has no channel; a Brand Account channel needs its own grant)")}}if(walk.phase==="playlists"){const queue=[];for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)?item.contentDetails:{};const tag=shortHash(typeof item.etag==="string"?item.etag:Original.jcsCanonicalize(json(item)));if(details.itemCount===0||walk.mode==="incremental"&&walk.prior.tags?.[item.id]===tag){walk.next.tags={...walk.next.tags,[item.id]:tag};continue}queue.push([item.id,tag])}finish(walk,true);walk.queue=queue;walk.more=nextToken}else{if(current.head&&walk.token===null)walk.next.heads={...walk.next.heads,[current.head]:ids.slice(0,HEAD_IDS)};const known=current.head?walk.prior.heads?.[current.head]:void 0;const reachedHead=walk.mode==="incremental"&&!!known?.length&&ids.some(id=>known.includes(id));const since=walk.prior.since===void 0?NaN:Date.parse(walk.prior.since)-COMMENT_SLACK_MS;const reachedOld=walk.mode==="incremental"&¤t.byTime===true&&Number.isFinite(since)&&rows.some(item=>{const top=snippet(item).topLevelComment,published=object(top)&&object(top.snippet)?Date.parse(String(top.snippet.publishedAt)):NaN;return Number.isFinite(published)&&published<since});if(nextToken&&nextToken===walk.token){gap(walk,stream,"repeated-page-token");notes.push("youtube: "+stream+" repeated-page-token \u2014 the provider repeated a page token; the rest of this list is not read");finish(walk,false)}else if(nextToken&&!reachedHead&&!reachedOld)walk.token=nextToken;else finish(walk,true)}settle(walk);return respond(items,walk,nowIso,notes)}const connector={manifest:youtubeSyncManifest,discover:()=>parts.gateRefusal("YouTube synchronous census","The production YouTube provider is async; use discoverAsync"),pull:()=>parts.gateRefusal("YouTube synchronous pull","The production YouTube provider is async; use pullAsync"),discoverAsync:grant=>owned((async()=>{const invalid=checkGrant(grant);if(invalid)return invalid;const fenced=await fence(grant);if(!Original.isOk(fenced))return fenced;const gaps=latest&&latest.account===grant.account?latest.gaps:{};const streams={};for(const stream of[...READ_STREAMS,...LISTED_ONLY]){const reasons=[...(STATIC_REASONS[stream]??[]).map(reason=>({reason})),...Object.entries(gaps).filter(([key])=>key.startsWith(stream+":")).map(([key,count])=>({reason:key.slice(stream.length+1),count}))];streams[stream]={method:"pagination-exhaustion",...reasons.length?{partialReasons:reasons}:{}}}return Original.ok({asOf:new Date(Date.parse(now())).toISOString(),streams})})()),pullAsync:(grant,cursor)=>owned(pullInner(grant,cursor)),normalize(item){const decl=declared.get(item.streamRef);if(!decl||!READ_STREAMS.includes(item.streamRef))throw Error("YouTube full sync does not emit stream "+item.streamRef+".");if(!object(item.raw)||!object(item.raw.item)||typeof item.raw.account!=="string"||typeof item.raw.via!=="string")throw Error("YouTube normalization requires the wrapped provider resource.");const raw=item.raw,id=typeof raw.item.id==="string"?raw.item.id:"";if(!id)throw Error("YouTube resource has no provider id.");const{title,body,ts}=describe(item.streamRef,raw);const payload={title,account:raw.account,channelId:typeof raw.channelId==="string"?raw.channelId:null,via:raw.via,...typeof raw.playlistId==="string"?{playlistId:raw.playlistId}:{},item:stable(raw.item,item.streamRef)};return{nk:{source:"youtube",stream:item.streamRef,sourceId:item.streamRef==="videos"?raw.via+":"+id:id},ts,kind:decl.kinds[0],tier:"api",schemaVersion:1,mentions:[],body,payload:json(payload)}}};return{info,connector,resolveGrant:()=>owned(resolveGrant()),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}}}
|
|
1
|
+
import{createHash}from"node:crypto";import{Original}from"@zortexhq/plugin-connector-framework/api";import{manifest as sourceManifest}from"./discovery-data.js";import{object}from"./schema.js";const READONLY="https://www.googleapis.com/auth/youtube.readonly";export const YOUTUBE_READ_SCOPES=Object.freeze([READONLY,"https://www.googleapis.com/auth/youtube","https://www.googleapis.com/auth/youtube.force-ssl"]);const API="https://www.googleapis.com/youtube/v3/";const HOUR=36e5,DAY=24*HOUR;const UNKNOWN_TS="1970-01-01T00:00:00.000Z";const MAX_WALK_PAGES=2e5,HEAD_IDS=3,COMMENT_SLACK_MS=DAY,QUOTA_SLACK_MS=6e4;export const YOUTUBE_INCREMENTAL_EVERY_MS=6*HOUR,YOUTUBE_FULL_EVERY_MS=7*DAY;const READ_STREAMS=["channels","subscriptions","playlists","playlistItems","videos","commentThreads"];const LISTED_ONLY=["comments","search","captions","members"];const STATIC_REASONS={channels:["brand-channels-need-own-grant"],playlistItems:["watch-history-not-in-api","watch-later-not-in-api"],comments:["authored-comments-not-in-api"],search:["search-history-not-in-api"],captions:["captions-sync-not-implemented"],members:["members-sync-not-implemented"]};export const youtubeSyncManifest=(()=>{const wanted=new Set([...READ_STREAMS,...LISTED_ONLY]),copy=structuredClone(sourceManifest);delete copy.actionScopes;return{...copy,streams:copy.streams.filter(stream=>wanted.has(stream.stream)),actions:[]}})();const PHASES=["channels","subscriptions","playlists","playlistItems","uploads","likes","dislikes","comments","done"];const text=value=>typeof value==="string"?value.trim():"";const json=value=>JSON.parse(JSON.stringify(value));const instant=(...values)=>{for(const value of values)if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return UNKNOWN_TS};const reasonCode=(reason,fallback)=>(reason??"").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||fallback;const shortHash=value=>createHash("sha256").update(value).digest("hex").slice(0,10);export function nextPacificMidnight(nowMs){const at=Math.floor(nowMs/1e3)*1e3;try{const parts=Object.fromEntries(new Intl.DateTimeFormat("en-US",{timeZone:"America/Los_Angeles",hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}).formatToParts(new Date(at)).map(part=>[part.type,part.value]));const[y,m,d]=[Number(parts.year),Number(parts.month),Number(parts.day)];const offset=Date.UTC(y,m-1,d,Number(parts.hour),Number(parts.minute),Number(parts.second))-at;const next=Date.UTC(y,m-1,d+1)-offset;if(Number.isFinite(next)&&next>at)return next}catch{}return Math.floor((at-8*HOUR)/DAY+1)*DAY+8*HOUR}function stringRecord(value){return object(value)&&Object.values(value).every(item=>typeof item==="string")}function parseMarks(value){if(!object(value))return null;const marks={};if(value.since!==void 0){if(typeof value.since!=="string"||!Number.isFinite(Date.parse(value.since)))return null;marks.since=value.since}if(value.heads!==void 0){if(!object(value.heads)||!Object.values(value.heads).every(ids=>Array.isArray(ids)&&ids.every(id=>typeof id==="string")))return null;marks.heads=value.heads}if(value.tags!==void 0){if(!stringRecord(value.tags))return null;marks.tags=value.tags}return marks}function parseWalk(wire){if(!object(wire))return null;const w=wire;const strings=value=>Array.isArray(value)&&value.every(item=>typeof item==="string");const optionalInstant=value=>value===void 0||typeof value==="string"&&Number.isFinite(Date.parse(value));if(typeof w.account!=="string"||!w.account||w.mode!=="full"&&w.mode!=="incremental"||typeof w.startedAt!=="string"||!Number.isFinite(Date.parse(w.startedAt)))return null;if(!PHASES.includes(w.phase)||w.token!==null&&typeof w.token!=="string"||!Number.isSafeInteger(w.pages)||Number(w.pages)<0)return null;if(!strings(w.channels)||!strings(w.uploads)||w.channels.length!==w.uploads.length||!Number.isSafeInteger(w.at)||Number(w.at)<0)return null;if(!Array.isArray(w.queue)||!w.queue.every(entry=>Array.isArray(entry)&&entry.length===2&&entry.every(part=>typeof part==="string"))||w.more!==null&&typeof w.more!=="string")return null;const prior=parseMarks(w.prior),next=parseMarks(w.next);if(!prior||!next||!object(w.gaps)||!Object.values(w.gaps).every(n=>Number.isSafeInteger(n)&&Number(n)>=0))return null;if(!optionalInstant(w.completedAt)||!optionalInstant(w.fullAt)||!optionalInstant(w.quotaUntil)||w.phase==="done"&&w.completedAt===void 0)return null;return{account:w.account,mode:w.mode,startedAt:w.startedAt,phase:w.phase,token:w.token,pages:Number(w.pages),channels:[...w.channels],uploads:[...w.uploads],at:Number(w.at),queue:w.queue.map(([id,tag])=>[id,tag]),more:w.more,prior,next,gaps:{...w.gaps},...w.completedAt===void 0?{}:{completedAt:w.completedAt},...w.fullAt===void 0?{}:{fullAt:w.fullAt},...w.quotaUntil===void 0?{}:{quotaUntil:w.quotaUntil}}}function stable(value,stream,depth=0){if(Array.isArray(value))return value.map(item=>stable(item,stream,depth+1));if(!object(value))return value;const out={};for(const[key,item]of Object.entries(value)){if(key==="etag"||depth===0&&key==="statistics")continue;if(stream==="commentThreads"&&(key==="likeCount"||key==="viewerRating"||key==="canRate"))continue;out[key]=stable(item,stream,depth+1)}return out}function snippet(item){return object(item.snippet)?item.snippet:{}}function commentLine(comment){const s=object(comment)&&object(comment.snippet)?comment.snippet:{};const said=text(s.textOriginal)||text(s.textDisplay);return said?[text(s.authorDisplayName),said].filter(Boolean).join(": "):""}function describe(stream,raw){const item=raw.item,s=snippet(item),title=text(s.title);const lines=(...parts)=>parts.filter(Boolean).join("\n");switch(stream){case"channels":return{title,ts:instant(s.publishedAt),body:lines("YouTube channel: "+title,text(s.customUrl),text(s.description))};case"subscriptions":return{title,ts:instant(s.publishedAt),body:lines("Subscribed to: "+title,text(s.description))};case"playlists":return{title,ts:instant(s.publishedAt),body:lines("Playlist: "+title,text(s.description))};case"playlistItems":{const details=object(item.contentDetails)?item.contentDetails:{};const owner=text(s.videoOwnerChannelTitle);return{title,ts:instant(s.publishedAt,details.videoPublishedAt),body:lines((raw.via==="uploads"?"Uploaded: ":"In playlist: ")+title,owner?"by "+owner:"",text(s.description))}}case"videos":{const tags=Array.isArray(s.tags)?s.tags.filter(tag=>typeof tag==="string"):[];const channel=text(s.channelTitle);return{title,ts:instant(s.publishedAt),body:lines((raw.via==="dislike"?"Disliked video: ":"Liked video: ")+title,channel?"by "+channel:"",text(s.description),tags.join(", "))}}case"commentThreads":{const top=s.topLevelComment,first=commentLine(top),replies=object(item.replies)&&Array.isArray(item.replies.comments)?item.replies.comments.map(commentLine).filter(Boolean):[];const topSnippet=object(top)&&object(top.snippet)?top.snippet:{};return{title:first.slice(0,120),ts:instant(topSnippet.updatedAt,topSnippet.publishedAt),body:lines(first,...replies)}}default:throw Error("YouTube full sync does not normalize stream "+stream+".")}}export function createYouTubeProvider({parts,auth,vault,now=()=>new Date().toISOString(),incrementalEveryMs=YOUTUBE_INCREMENTAL_EVERY_MS,fullEveryMs=YOUTUBE_FULL_EVERY_MS}){if(!Number.isFinite(incrementalEveryMs)||incrementalEveryMs<0||!Number.isFinite(fullEveryMs)||fullEveryMs<0)throw Error("YouTube sync pacing must be non-negative milliseconds.");const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser"};const stop=new AbortController,pending=new Set;let closed=false;let latest=null;const codec=parts.cursorCodecV1({source:"youtube",version:2,versionKey:"v",validate:parseWalk});const fail=(code,message,retryability="non-retryable",cause)=>parts.connectorError(code,message,retryability,cause);const inactive=()=>fail("aborted","YouTube source is inactive.");const owned=task=>{const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled};const declared=new Map(youtubeSyncManifest.streams.map(stream=>[stream.stream,stream]));async function resolveGrant(){if(closed)return inactive();const connection=await vault.connection("youtube");if(!("ok"in connection))return"err"in connection?connection:fail("data_loss","YouTube connection metadata was unconfirmed.");const row=connection.ok;if(!row||row.state!=="connected")return fail("unauthenticated","Connect YouTube before syncing it.");if(typeof row.accountId!=="string"||!row.accountId.trim())return fail("failed_precondition","YouTube sync needs the verified Google subject; an email or grant id is never the account identity.");const scope=YOUTUBE_READ_SCOPES.find(candidate=>row.scopes.includes(candidate));if(!scope)return fail("permission_denied","The YouTube connection has no read scope; reconnect YouTube.");if(closed)return inactive();return Original.ok({id:"0"+createHash("sha256").update(row.accountId).digest("hex").slice(0,25).toUpperCase(),source:"youtube",account:row.accountId,scopes:[scope],expiresAt:new Date(Date.parse(now())+HOUR).toISOString()})}function checkGrant(grant){if(grant.source!=="youtube"||!grant.account?.trim())return fail("permission_denied","YouTube grant is not bound to a verified account.");if(!grant.scopes.some(scope=>YOUTUBE_READ_SCOPES.includes(scope)))return fail("permission_denied","YouTube grant has no read scope.");return void 0}async function fence(grant){if(closed||stop.signal.aborted)return inactive();const current=await vault.connection("youtube");if(!("ok"in current))return"err"in current?current:fail("data_loss","YouTube account fence was unconfirmed.");if(closed||stop.signal.aborted)return inactive();const row=current.ok;if(!row||row.state!=="connected")return fail("unauthenticated","YouTube was disconnected during the sync.");if(row.accountId!==grant.account)return fail("permission_denied","The YouTube account changed during the sync; nothing from the old grant is attributed to the new account.");if(!grant.scopes.every(scope=>row.scopes.includes(scope)))return fail("permission_denied","YouTube read consent was withdrawn.");return Original.ok(void 0)}async function call(grant,listing2,token){const url=new URL(listing2.resource,API);for(const[key,value]of Object.entries(listing2.params))url.searchParams.set(key,value);if(token)url.searchParams.set("pageToken",token);const before=await fence(grant);if(!Original.isOk(before))return before;const reply=await auth.requestRaw("youtube",url.href,{signal:stop.signal});if(closed||stop.signal.aborted)return inactive();if(!("ok"in reply)){const err="err"in reply?reply.err:void 0;if(!err||err.code==="unavailable"||err.code==="aborted")return fail("unavailable","A YouTube list request did not complete (network or request timeout); the page is retried from the same cursor.","transient",err);return reply}const after=await fence(grant);if(!Original.isOk(after))return after;return reply}function soleChannel(walk){return walk.channels.length===1?walk.channels[0]:null}function listing(walk){const page2=(resource,params)=>({resource,params:{...params,maxResults:"50"}});switch(walk.phase){case"channels":return{...page2("channels",{part:"snippet,contentDetails,brandingSettings,status,topicDetails,localizations",mine:"true"}),stream:"channels",via:"mine",owner:null};case"subscriptions":return{...page2("subscriptions",{part:"snippet",mine:"true"}),stream:"subscriptions",via:"subscription",owner:soleChannel(walk)};case"playlists":return{...page2("playlists",{part:"snippet,contentDetails,status,localizations",mine:"true"}),stream:"playlists",via:"playlist",owner:soleChannel(walk)};case"playlistItems":{const id=walk.queue[0][0];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"playlist",owner:soleChannel(walk),playlistId:id}}case"uploads":{const id=walk.uploads[walk.at];return{...page2("playlistItems",{part:"snippet,contentDetails,status",playlistId:id}),stream:"playlistItems",via:"uploads",owner:walk.channels[walk.at],playlistId:id,head:"uploads:"+id}}case"likes":case"dislikes":{const rating=walk.phase==="likes"?"like":"dislike";return{...page2("videos",{part:"snippet,contentDetails,status,topicDetails",myRating:rating}),stream:"videos",via:rating,owner:soleChannel(walk),head:rating}}case"comments":return{resource:"commentThreads",params:{part:"snippet,replies",allThreadsRelatedToChannelId:walk.channels[walk.at],maxResults:"100",order:"time",textFormat:"plainText"},stream:"commentThreads",via:"channel-comments",owner:walk.channels[walk.at],byTime:true};case"done":throw Error("A completed YouTube walk has no listing.")}}function settle(walk){for(;;){if(walk.phase==="playlistItems"&&!walk.queue.length){if(walk.more!==null){walk.phase="playlists";walk.token=walk.more;walk.more=null}else{walk.phase="uploads";walk.at=0;walk.token=null}continue}if(walk.phase==="uploads"){while(walk.at<walk.channels.length&&!walk.uploads[walk.at])walk.at++;if(walk.at>=walk.channels.length){walk.phase="likes";walk.at=0;walk.token=null;continue}}if(walk.phase==="comments"&&walk.at>=walk.channels.length){walk.phase="done";walk.token=null;continue}return}}function finish(walk,read){switch(walk.phase){case"channels":walk.phase="subscriptions";break;case"subscriptions":walk.phase="playlists";walk.more=null;break;case"playlists":walk.phase="playlistItems";walk.queue=[];walk.more=null;break;case"playlistItems":{const[id,tag]=walk.queue.shift();if(read)walk.next.tags={...walk.next.tags,[id]:tag};break}case"uploads":walk.at++;break;case"likes":walk.phase="dislikes";break;case"dislikes":walk.phase="comments";walk.at=0;break;case"comments":walk.at++;break;case"done":break}walk.token=null}function gap(walk,stream,reason,count=1){const key=stream+":"+reason;walk.gaps[key]=(walk.gaps[key]??0)+count}function begin(account,mode,prior,fullAt,at){return{account,mode,startedAt:at,phase:"channels",token:null,pages:0,channels:[],uploads:[],at:0,queue:[],more:null,prior:mode==="full"?{}:prior,next:{},gaps:{},...fullAt===void 0?{}:{fullAt}}}function complete(walk,at){return{...walk,phase:"done",token:null,at:0,queue:[],more:null,prior:{...walk.next,since:walk.startedAt},next:{},completedAt:at,...walk.mode==="full"?{fullAt:at}:{}}}function encode(walk,notes){let attempt=codec.encode(walk);if("ok"in attempt)return attempt;if(walk.prior.tags||walk.next.tags){const{tags:_p,...prior}=walk.prior,{tags:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: playlist-marks-dropped \u2014 remembered playlist versions were dropped to keep the cursor within "+Original.SYNC_CURSOR_MAX_CHARS+" chars; those playlists are read in full");attempt=codec.encode(walk);if("ok"in attempt)return attempt}if(walk.prior.heads||walk.next.heads){const{heads:_p,...prior}=walk.prior,{heads:_n,...next}=walk.next;walk.prior=prior;walk.next=next;notes.push("youtube: head-marks-dropped \u2014 remembered list heads were dropped to keep the cursor bounded; those lists are read in full");attempt=codec.encode(walk)}return attempt}function page(items,walk,exhausted,notes){latest=walk;const next=encode(walk,notes);if(!("ok"in next))return next;return Original.ok({items,next:next.ok,exhausted,...notes.length?{notes}:{}})}function respond(items,walk,at,notes){return walk.phase==="done"?page(items,complete(walk,at),true,notes):page(items,walk,false,notes)}function quotaWait(until){return fail("resource_exhausted","YouTube daily quota is exhausted (youtube-daily-quota-exhausted): the project's YouTube Data API units for today are used up. Quota backoff not due until "+until+", when Google resets the quota at midnight Pacific Time; the walk then resumes from its saved cursor and nothing is skipped.","retry-at-higher-level")}const RATE_LIMIT=new Set(["rateLimitExceeded","userRateLimitExceeded","RATE_LIMIT_EXCEEDED"]),DAILY=new Set(["quotaExceeded","dailyLimitExceeded"]),GRANT=new Set(["insufficientPermissions","authError","unauthorized","PERMISSION_DENIED","UNAUTHENTICATED"]);function classify(walk,reply){const what=walk.phase==="uploads"||walk.phase==="playlistItems"?"playlistItems.list":walk.phase==="likes"||walk.phase==="dislikes"?"videos.list":walk.phase==="comments"?"commentThreads.list":walk.phase+".list";if(reply.status===200){let data;try{data=JSON.parse(reply.body)}catch{return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a body that is not JSON; the page is asked again.","transient").err}}if(!object(data)||data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item)))||data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return{kind:"err",err:fail("data_loss","YouTube "+what+" returned a malformed list; the page is asked again.","transient").err};return{kind:"ok",data}}const reason=parts.googleErrorReasonV1(reply.body);if((reply.status===403||reply.status===429)&&reason!==void 0&&DAILY.has(reason))return{kind:"quota"};const status=()=>parts.webStatusErrorV1(reply.status,{provider:"YouTube",what,headers:reply.headers,...reason?{detail:reason}:{},bodyOverride:code=>code===403&&reason!==void 0&&RATE_LIMIT.has(reason)?{code:"resource_exhausted",retryability:"throttling",meaning:"the provider throttled the call ("+reason+")"}:void 0})??fail("internal","YouTube "+what+" returned HTTP "+reply.status+".").err;if(reply.status===429||reply.status===403&&reason!==void 0&&RATE_LIMIT.has(reason))return{kind:"err",err:status()};if(reason==="youtubeSignupRequired"&&(reply.status===401||reply.status===403))return{kind:"gap",reason:"youtube-signup-required"};if(reply.status===401)return{kind:"err",err:status()};if(reply.status===403){if(walk.phase==="channels"||reason===void 0||GRANT.has(reason))return{kind:"err",err:status()};return{kind:"gap",reason:reasonCode(reason,"forbidden")}}if(reply.status===404)return{kind:"gap",reason:reasonCode(reason,"not-found")};if(reply.status===400&&reason==="invalidPageToken"&&walk.token!==null)return{kind:"restart"};return{kind:"err",err:status()}}async function pullInner(grant,cursor){const invalid=checkGrant(grant);if(invalid)return invalid;if(closed)return inactive();const notes=[],nowMs=Date.parse(now()),nowIso=new Date(nowMs).toISOString();let walk=cursor===null?null:codec.decode(cursor);if(cursor!==null&&walk===null)notes.push("youtube: cursor-unreadable \u2014 the walk starts again from the first list");if(walk&&walk.account!==grant.account){notes.push("youtube: account-changed \u2014 the walk starts again for the connected account");walk=null}if(walk?.quotaUntil!==void 0){if(nowMs<Date.parse(walk.quotaUntil)){latest=walk;return quotaWait(walk.quotaUntil)}const{quotaUntil:_q,...resumed}=walk;walk=resumed;notes.push("youtube: quota-reset \u2014 the walk resumes where the daily quota stopped it")}if(!walk){walk=begin(grant.account,"full",{},void 0,nowIso);notes.push("youtube: full-pass \u2014 every list is read")}else if(walk.phase==="done"){const due=Date.parse(walk.completedAt)+incrementalEveryMs;if(nowMs<due&&cursor!==null){latest=walk;return Original.ok({items:[],next:cursor,exhausted:true,notes:[...notes,"youtube: pass-not-due \u2014 the next pass starts after "+new Date(due).toISOString()+" (quota pacing)"]})}const full=walk.fullAt===void 0||nowMs-Date.parse(walk.fullAt)>=fullEveryMs;walk=begin(grant.account,full?"full":"incremental",walk.prior,walk.fullAt,nowIso);notes.push(full?"youtube: full-pass \u2014 every list is read again (periodic re-walk)":"youtube: incremental-pass \u2014 cheap lists re-listed, unchanged playlists skipped, newest-first lists stop at the remembered head")}settle(walk);if(walk.phase==="done")return page([],complete(walk,nowIso),true,notes);if(walk.pages>=MAX_WALK_PAGES)return fail("resource_exhausted","YouTube walk exceeded "+MAX_WALK_PAGES+" provider pages; the cursor is kept.");const current=listing(walk),reply=await call(grant,current,walk.token);if(!("ok"in reply))return"err"in reply?reply:fail("data_loss","YouTube request result was unconfirmed.");walk.pages++;const outcome=classify(walk,reply.ok),stream=current.stream,items=[];if(outcome.kind==="err")return{err:outcome.err};if(outcome.kind==="quota"){walk.quotaUntil=new Date(nextPacificMidnight(nowMs)+QUOTA_SLACK_MS).toISOString();notes.push("youtube: youtube-daily-quota-exhausted \u2014 no request until "+walk.quotaUntil+"; the walk resumes at this list");return page([],walk,false,notes)}if(outcome.kind==="restart"){walk.token=null;notes.push("youtube: page-token-expired \u2014 this list is read again from its first page");return page([],walk,false,notes)}if(outcome.kind==="gap"){const reason=walk.phase==="channels"&&outcome.reason==="youtube-signup-required"?"no-youtube-channel":outcome.reason;gap(walk,stream,reason);notes.push("youtube: "+stream+" not read \u2014 "+reason+" (HTTP "+reply.ok.status+")");finish(walk,false);settle(walk);return respond(items,walk,nowIso,notes)}const data=outcome.data,rows=Array.isArray(data.items)?data.items:[],nextToken=typeof data.nextPageToken==="string"?data.nextPageToken:null;const ids=[];let missing=0,unavailable=0;for(const item of rows){const id=typeof item.id==="string"&&item.id?item.id:"";if(!id){missing++;continue}ids.push(id);const s=snippet(item);const owner=walk.phase==="channels"?id:current.via==="subscription"||current.via==="playlist"?text(s.channelId)||current.owner:current.owner;const raw={account:walk.account,channelId:owner,via:current.via,...current.playlistId?{playlistId:current.playlistId}:{},item};items.push({streamRef:stream,raw:json(raw)});if(stream==="playlistItems"&&(s.title==="Private video"||s.title==="Deleted video"))unavailable++}if(missing){gap(walk,stream,"item-without-id",missing);notes.push("youtube: "+stream+" item-without-id \u2014 "+missing+" item(s) without a provider id were not stored")}if(unavailable){gap(walk,"playlistItems","video-unavailable",unavailable);notes.push("youtube: video-unavailable \u2014 "+unavailable+" playlist item(s) point to a private or deleted video; only the placeholder is stored")}if(walk.phase==="channels"){for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)&&object(item.contentDetails.relatedPlaylists)?item.contentDetails.relatedPlaylists:{};walk.channels.push(item.id);walk.uploads.push(text(details.uploads))}if(!nextToken&&!walk.channels.length){gap(walk,"channels","no-youtube-channel");notes.push("youtube: channels not read \u2014 no-youtube-channel (this identity has no channel; a Brand Account channel needs its own grant)")}}if(walk.phase==="playlists"){const queue=[];for(const item of rows){if(typeof item.id!=="string"||!item.id)continue;const details=object(item.contentDetails)?item.contentDetails:{};const tag=shortHash(typeof item.etag==="string"?item.etag:Original.jcsCanonicalize(json(item)));if(details.itemCount===0||walk.mode==="incremental"&&walk.prior.tags?.[item.id]===tag){walk.next.tags={...walk.next.tags,[item.id]:tag};continue}queue.push([item.id,tag])}finish(walk,true);walk.queue=queue;walk.more=nextToken}else{if(current.head&&walk.token===null)walk.next.heads={...walk.next.heads,[current.head]:ids.slice(0,HEAD_IDS)};const known=current.head?walk.prior.heads?.[current.head]:void 0;const reachedHead=walk.mode==="incremental"&&!!known?.length&&ids.some(id=>known.includes(id));const since=walk.prior.since===void 0?NaN:Date.parse(walk.prior.since)-COMMENT_SLACK_MS;const reachedOld=walk.mode==="incremental"&¤t.byTime===true&&Number.isFinite(since)&&rows.some(item=>{const top=snippet(item).topLevelComment,published=object(top)&&object(top.snippet)?Date.parse(String(top.snippet.publishedAt)):NaN;return Number.isFinite(published)&&published<since});if(nextToken&&nextToken===walk.token){gap(walk,stream,"repeated-page-token");notes.push("youtube: "+stream+" repeated-page-token \u2014 the provider repeated a page token; the rest of this list is not read");finish(walk,false)}else if(nextToken&&!reachedHead&&!reachedOld)walk.token=nextToken;else finish(walk,true)}settle(walk);return respond(items,walk,nowIso,notes)}const connector={manifest:youtubeSyncManifest,discover:()=>parts.gateRefusal("YouTube synchronous census","The production YouTube provider is async; use discoverAsync"),pull:()=>parts.gateRefusal("YouTube synchronous pull","The production YouTube provider is async; use pullAsync"),discoverAsync:grant=>owned((async()=>{const invalid=checkGrant(grant);if(invalid)return invalid;const fenced=await fence(grant);if(!Original.isOk(fenced))return fenced;const gaps=latest&&latest.account===grant.account?latest.gaps:{};const streams={};for(const stream of[...READ_STREAMS,...LISTED_ONLY]){const reasons=[...(STATIC_REASONS[stream]??[]).map(reason=>({reason})),...Object.entries(gaps).filter(([key])=>key.startsWith(stream+":")).map(([key,count])=>({reason:key.slice(stream.length+1),count}))];streams[stream]={method:"pagination-exhaustion",...reasons.length?{partialReasons:reasons}:{}}}return Original.ok({asOf:new Date(Date.parse(now())).toISOString(),streams})})()),pullAsync:(grant,cursor)=>owned(pullInner(grant,cursor)),normalize(item){const decl=declared.get(item.streamRef);if(!decl||!READ_STREAMS.includes(item.streamRef))throw Error("YouTube full sync does not emit stream "+item.streamRef+".");if(!object(item.raw)||!object(item.raw.item)||typeof item.raw.account!=="string"||typeof item.raw.via!=="string")throw Error("YouTube normalization requires the wrapped provider resource.");const raw=item.raw,id=typeof raw.item.id==="string"?raw.item.id:"";if(!id)throw Error("YouTube resource has no provider id.");const{title,body,ts}=describe(item.streamRef,raw);const payload={title,account:raw.account,channelId:typeof raw.channelId==="string"?raw.channelId:null,via:raw.via,...typeof raw.playlistId==="string"?{playlistId:raw.playlistId}:{},item:stable(raw.item,item.streamRef)};return{nk:{source:"youtube",stream:item.streamRef,sourceId:item.streamRef==="videos"?raw.via+":"+id:id},ts,kind:decl.kinds[0],tier:"api",schemaVersion:1,mentions:[],body,payload:json(payload)}}};return{info,connector,resolveGrant:()=>owned(resolveGrant()),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{pinnedMethods,discoveryPin}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";import{object,invalidSchema}from"./schema.js";import{createYouTubeConnector}from"./connector.js";import{readTakeout}from"./takeout.js";const methodMap=new Map([...pinnedMethods,...creatorMethods].flatMap(method=>[[method.id,method],[method.contractName,method]]));const info={source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["authorized_collections"],limitations:["provider_history_limits"]},readById:true};export function createYouTubeSource({parts,auth,vault,transport,takeoutRoot}){const stop=new AbortController,pending=new Set;let closed=false;const track=work=>{pending.add(work);return work.finally(()=>pending.delete(work))};const unavailable=()=>businessError("unavailable","YouTube source is inactive.","connector");const aborted=()=>businessError("aborted","YouTube read was cancelled.","connector");function catalog(options={}){const{query="",resource,limit=20,cursor=0,profile="data"}=options;if(typeof query!=="string"||query.length>500||resource!==void 0&&typeof resource!=="string"||!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return businessError("invalid_argument","Catalog query/limit/cursor is invalid.","connector");if(!["data","analytics","reporting","all"].includes(profile))return businessError("invalid_argument","Unknown YouTube capability profile.","connector");const selected=[...pinnedMethods,...creatorMethods].filter(m=>(profile==="all"||(m.profile??"data")===profile)&&(!resource||m.resource===resource)&&(!query||[m.id,m.description??""].join(" ").toLowerCase().includes(query.toLowerCase())));return Original.ok({total:selected.length,methods:selected.slice(cursor,cursor+limit).map(m=>({id:m.id,contract:m.contractName,resource:m.resource,method:m.httpMethod,scopes:m.scopes??[],body:!!m.request?.$ref,media:!!m.supportsMediaUpload})),...cursor+limit<selected.length?{next:cursor+limit}:{},pin:discoveryPin,gaps:["watchHistory/watchLater require explicit read-only Takeout","creator Analytics/Reporting need separate admitted profile and scopes","audio/video bytes require provider permission","write effects require original action rail verification; HTTP success is not EFFECTED"]})}function method(id){const found=methodMap.get(id);return found?Original.ok(structuredClone(found)):businessError("not_found","Unknown pinned YouTube method.","connector")}async function invokeInner(id,input,options={},level1=false){if(closed)return unavailable();const m=methodMap.get(id);if(!m)return businessError("not_found","Unknown pinned YouTube method.","connector");const invalid=invalidSchema(m.params,input);if(invalid)return businessError("invalid_argument",invalid,"connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const conn=await vault.connection("youtube");if(!("ok"in conn))return conn;if(!conn.ok||conn.ok.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(closed||signal.aborted)return aborted();if(!m.scopes?.length)return businessError("failed_precondition","The pinned provider method "+m.id+" publishes no OAuth scope requirement. Scope/admission reconnaissance is required before a dispatch; no permission was guessed.","auth");if(!(m.scopes??[]).some(scope=>conn.ok.scopes.includes(scope)))return businessError("permission_denied","Method "+id+" requires one of the declared scopes: "+(m.scopes??[]).join(", ")+". Reauthorize this source; no API-key fallback.","auth");if(input.params.onBehalfOfContentOwner!==void 0&&!conn.ok.scopes.includes("https://www.googleapis.com/auth/youtubepartner"))return businessError("permission_denied","Content-owner operations require the partner scope and linked CMS admission.","auth");let pathname=m.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(input.params)){if(m.parameters?.[key]?.location==="path"){const text=String(value);if(text.split("/").some(segment=>segment==="."||segment==="..")||/[?#%\\]/.test(text))return businessError("invalid_argument","Path parameters cannot contain traversal or encoded routing material.","connector");const reserved=pathname.includes("{+"+key+"}");if(reserved&&!/^[A-Za-z0-9_./-]+$/.test(text))return businessError("invalid_argument","Reserved resource paths must be canonical provider resource names.","connector");pathname=pathname.replace(reserved?"{+"+key+"}":"{"+key+"}",reserved?text.split("/").map(encodeURIComponent).join("/"):encodeURIComponent(text))}else query.set(key,Array.isArray(value)?value.join(","):String(value))}if(pathname.includes("{"))return businessError("invalid_argument","Provider path parameter is missing.","connector");if(input.media)return businessError("failed_precondition","Media upload needs the separately admitted bounded streaming transport; no effect was dispatched.","connector");if(m.id==="youtube.youtube.v3.liveChat.messages.stream")return businessError("failed_precondition","The pinned server-streaming RPC requires an admitted cancelable stream transport; use liveChatMessages.list with pageToken until that profile is enabled.","connector");if(m.httpMethod!=="GET"&&!transport&&!level1)return businessError("failed_precondition","Write transport and original action admission are required for "+id+"; no effect was dispatched.","connector");const url=new URL(pathname,m.baseUrl??"https://www.googleapis.com/");url.search=query.toString();const raw=transport?await transport("youtube",url.href,{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"},signal}):await auth.requestRaw("youtube",url.href,{signal,...level1?{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"}}:{}});if(closed||signal.aborted)return aborted();if(!("ok"in raw))return raw;if(Buffer.byteLength(raw.ok.body,"utf8")>2*1024*1024)return businessError("resource_exhausted","YouTube response exceeds the bounded broker body budget. Use an admitted streaming path; no body was truncated.","connector");const reason=parts.googleErrorReasonV1(raw.ok.body),baseOverride=parts.googleStatusOverrideV1(raw.ok.body),status=parts.webStatusErrorV1(raw.ok.status,{provider:"YouTube",what:id,headers:raw.ok.headers,bodyOverride:status2=>status2===403&&reason==="quotaExceeded"?{code:"resource_exhausted",retryability:"throttling",meaning:"the YouTube project quota bucket is exhausted (quotaExceeded)"}:baseOverride(status2),...reason?{detail:reason}:{}});if(status)return{err:status};if(m.supportsMediaDownload){return Original.ok({method:id,resource:m.resource,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain",items:[{id:input.params.id??input.params.resourceName,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain"}],warnings:[],effect:"read",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}if(raw.ok.status===204||!raw.ok.body)return Original.ok({method:id,resource:m.resource,items:[],warnings:["Provider response carries no body; upstream effect remains unverified."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}});let data;try{data=JSON.parse(raw.ok.body)}catch{return businessError("data_loss","YouTube returned invalid JSON for "+id+".","connector")}if(!object(data))return businessError("data_loss","YouTube response must be an object.","connector");if(data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item))))return businessError("data_loss","YouTube response items are malformed.","connector");if(data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return businessError("data_loss","YouTube nextPageToken is malformed.","connector");const items=Array.isArray(data.items)?data.items:typeof data.id==="string"?[data]:[];return Original.ok({method:id,resource:m.resource,data,items,...typeof data.nextPageToken==="string"?{nextPageToken:data.nextPageToken}:{},warnings:m.httpMethod==="GET"?[]:["HTTP response accepted. Only original action read-after-write/event-confirm can mark EFFECTED."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}function invoke(id,input,options={},level1=false){return track(invokeInner(id,input,options,level1).catch(error=>{if(closed||options.signal?.aborted)return aborted();const cause=object(error)?Original.validateStructuredError(error.structuredError):void 0;return parts.connectorError("unavailable","Trusted YouTube transport failed before a confirmed provider response. Raw custody exception text is not a tool result.","transient",cause&&"ok"in cause?cause.ok:void 0)}))}async function*pages(id,params,options={}){const m=methodMap.get(id);if(!m||m.httpMethod!=="GET"){yield businessError("invalid_argument","Only pinned GET methods can be paginated.","connector");return}if(options.maxPages!==void 0&&(!Number.isInteger(options.maxPages)||options.maxPages<1)){yield businessError("invalid_argument","maxPages must be a positive integer.","connector");return}const seen=new Set;let token=typeof params.pageToken==="string"?params.pageToken:void 0,count=0;for(;;){if(token&&seen.has(token)){yield businessError("failed_precondition","YouTube repeated a page token; coverage is incomplete.","connector");return}if(token)seen.add(token);const result=await invoke(id,{params:{...params,...token?{pageToken:token}:{}}},options);yield result;if(!("ok"in result))return;count++;token=result.ok.nextPageToken;if(!token)return;if(options.maxPages!==void 0&&count>=options.maxPages){yield businessError("resource_exhausted","Selected page budget ended with a nonterminal token; coverage is incomplete.","connector");return}}}async function readInner(request,options={}){if(closed)return unavailable();const bad=validateRead(request,["fileId"]);if(bad)return bad;request=structuredClone(request);if(request.fileId!==void 0&&(!/^[A-Za-z0-9_-]{1,200}$/.test(request.fileId)||request.query!==void 0||request.since!==void 0||request.until!==void 0))return businessError("invalid_argument","An exact YouTube video read takes fileId without query or time bounds.","connector");const selected=request.fileId?"youtube.videos.list":request.query?"youtube.search.list":"youtube.activities.list";const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const connection=await vault.connection("youtube");if(!("ok"in connection))return connection;const captured=structuredClone(connection.ok);if(!captured||captured.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(typeof captured.accountId!=="string"||!captured.accountId.trim())return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");const firstScopes=methodMap.get(selected)?.scopes??[],detailScopes=request.query?methodMap.get("youtube.videos.list")?.scopes??[]:firstScopes,scopes=firstScopes.filter(scope=>detailScopes.includes(scope)),readonly="https://www.googleapis.com/auth/youtube.readonly";const requiredScope=scopes.includes(readonly)&&captured.scopes.includes(readonly)?readonly:scopes.find(scope=>captured.scopes.includes(scope));if(!requiredScope)return businessError("permission_denied","The selected YouTube query requires one of its pinned read scopes.","auth");const fence=async()=>{if(closed||signal.aborted)return aborted();const current=await vault.connection("youtube");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==captured.accountId||!current.ok.scopes.includes(requiredScope))return businessError("permission_denied","YouTube selected read connection or scope changed.","auth");return Original.ok(void 0)};const boundInvoke=async(id,input)=>{const before=await fence();if(!("ok"in before))return before;const answer2=await invoke(id,input,{signal});const after=await fence();return"ok"in after?answer2:after};const wanted=request.limit??1,params=request.fileId?{part:["snippet","contentDetails","status","statistics"],id:[request.fileId]}:request.query?{part:["snippet"],q:request.query,type:["video"],maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}}:{part:["snippet","contentDetails"],mine:true,maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}};let answer=await boundInvoke(selected,{params});if("err"in answer&&selected==="youtube.activities.list"&&answer.err.code==="permission_denied"){const channels=await boundInvoke("youtube.channels.list",{params:{part:["id"],mine:true,maxResults:1}});if("ok"in channels&&!channels.ok.items.length)return readResult("youtube",[],["This Google account has no YouTube channel, so it has no own activity to read; full sync records it as no-youtube-channel."])}if(!("ok"in answer))return answer;const items=[...answer.ok.items],seen=new Set;let steps=1;while(items.length<wanted&&answer.ok.nextPageToken){const token=answer.ok.nextPageToken;if(seen.has(token))return businessError("failed_precondition","Selected YouTube read repeated a token; no complete result was asserted.","connector");seen.add(token);if(++steps>100)return businessError("resource_exhausted","Selected YouTube read exceeded the page budget before satisfying its limit; no complete result was asserted.","connector");answer=await boundInvoke(selected,{params:{...params,pageToken:token}});if(!("ok"in answer))return answer;items.push(...answer.ok.items)}let retained=items.slice(0,wanted),resource=answer.ok.resource;if(request.query&&retained.length){const selectedItems=retained,details=[];for(let index=0;index<selectedItems.length;index+=50){const block=selectedItems.slice(index,index+50),ids=block.map(item=>object(item.id)?item.id.videoId:void 0).filter(id=>typeof id==="string");if(ids.length!==block.length)return businessError("data_loss","A selected YouTube video search result lacks its native video id.","connector");const hydrated=await boundInvoke("youtube.videos.list",{params:{part:["snippet","contentDetails","status","statistics","topicDetails","recordingDetails","localizations"],id:ids}});if(!("ok"in hydrated))return hydrated;for(const item of hydrated.ok.items)details.push({...item,_selection:block.find(selected2=>object(selected2.id)&&selected2.id.videoId===item.id)??null})}retained=details;resource="videos"}const records=retained.map(item=>({source:"youtube",sourceId:captured.accountId+":"+resource+":"+itemId(item),stream:resource,kind:"youtube."+resource.toLowerCase()+".changed",ts:itemTime(item),body:JSON.stringify(item),fields:{...item}}));const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;if(closed||signal.aborted)return aborted();return readResult("youtube",records,[...answer.ok.warnings,...answer.ok.nextPageToken||items.length>wanted?["More provider results exist beyond this selected batch."]:[],...retained.length<Math.min(items.length,wanted)?["Some selected videos are currently inaccessible/deleted; search metadata is retained only as an attributed missing detail, never a fabricated video body."]:[],"This selected API query does not establish complete YouTube account or archive coverage."])}function read(request,options={}){return track(readInner(request,options))}async function importTakeout(root=takeoutRoot??"",options={}){if(closed)return unavailable();if(!root)return businessError("failed_precondition","Supply an explicit extracted read-only Takeout copy; API success cannot substitute for history.","connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;const result=await readTakeout(root,signal);if(!("ok"in result))return result;if(closed||signal.aborted)return aborted();const saved=await cache(vault,"youtube",result.ok.records);if(!("ok"in saved))return saved;return result}const account=async()=>{const row=await vault.connection("youtube");if(!("ok"in row))return row;if(!row.ok||row.ok.state!=="connected")return businessError("unauthenticated","YouTube identity needs a connected account.","auth");if(!row.ok.accountId)return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");return Original.ok(row.ok.accountId)};function actionSchema(schema){const{id:_discoveryType,...result}=schema;if(result.properties)result.properties=Object.fromEntries(Object.entries(result.properties).map(([key,value])=>[key,actionSchema(value)]));if(result.items)result.items=actionSchema(result.items);if(object(result.additionalProperties))result.additionalProperties=actionSchema(result.additionalProperties);return result}const actions={catalog,method:id=>{const result=method(id);if(!("ok"in result))return result;const m=result.ok;return Original.ok({...m,params:actionSchema(m.params),...!m.supportsMediaUpload&&m.id!=="youtube.youtube.v3.liveChat.messages.stream"&&(!m.profile||m.httpMethod==="GET")?{level:1,effect:m.httpMethod==="GET"?"read":"write"}:{}})},invoke:(id,input,options={})=>invoke(id,input,options,true)};const source={info,actions,catalog,method,invoke,pages,read,status:()=>closed?Promise.resolve(Original.ok({...info,state:"unavailable",message:"YouTube source is inactive."})):connectionState(vault,info),connect:options=>closed?Promise.resolve(unavailable()):track(auth.connect("youtube",options)),job:id=>closed?unavailable():auth.job(id),cancelJob:id=>auth.cancelJob(id),importTakeout:(root,options)=>track(importTakeout(root,options)),createConnector:(plan,options={})=>createYouTubeConnector({parts,invoke,method,account,isClosed:()=>closed},plan,options),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}};return source}export function itemId(item){if(typeof item.id==="string")return item.id;if(typeof item.videoId==="string")return item.videoId;if(object(item.id)){for(const key of["videoId","channelId","playlistId"])if(typeof item.id[key]==="string")return key+":"+item.id[key]}const value=JSON.parse(JSON.stringify(item.id??item));return createHash("sha256").update(Original.jcsCanonicalize(value)).digest("hex")}export function itemTime(item){const snippet=object(item.snippet)?item.snippet:{};for(const value of[item.time,item.updated,item.updatedAt,snippet.updatedAt,snippet.publishedAt])if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return"1970-01-01T00:00:00.000Z"}
|
|
1
|
+
import{createHash}from"node:crypto";import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{actionNotApplied,actionOutcome,cache,connectionState,readResult,validateRead}from"@zortexhq/plugin-connector-core/api";import{pinnedMethods,discoveryPin}from"./discovery-data.js";import{creatorMethods}from"./creator-data.js";import{object,invalidSchema}from"./schema.js";import{createYouTubeConnector}from"./connector.js";import{readTakeout}from"./takeout.js";import{youtubeContent}from"./content.js";const methodMap=new Map([...pinnedMethods,...creatorMethods].flatMap(method=>[[method.id,method],[method.contractName,method]]));const info={content:youtubeContent,source:"youtube",label:"YouTube",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["authorized_collections"],limitations:["provider_history_limits"]},readById:true};export function createYouTubeSource({parts,auth,vault,transport,takeoutRoot}){const stop=new AbortController,pending=new Set;let closed=false;const track=work=>{pending.add(work);return work.finally(()=>pending.delete(work))};const unavailable=()=>businessError("unavailable","YouTube source is inactive.","connector");const aborted=()=>businessError("aborted","YouTube read was cancelled.","connector");function catalog(options={}){const{query="",resource,limit=20,cursor=0,profile="data"}=options;if(typeof query!=="string"||query.length>500||resource!==void 0&&typeof resource!=="string"||!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return businessError("invalid_argument","Catalog query/limit/cursor is invalid.","connector");if(!["data","analytics","reporting","all"].includes(profile))return businessError("invalid_argument","Unknown YouTube capability profile.","connector");const selected=[...pinnedMethods,...creatorMethods].filter(m=>(profile==="all"||(m.profile??"data")===profile)&&(!resource||m.resource===resource)&&(!query||[m.id,m.description??""].join(" ").toLowerCase().includes(query.toLowerCase())));return Original.ok({total:selected.length,methods:selected.slice(cursor,cursor+limit).map(m=>({id:m.id,contract:m.contractName,resource:m.resource,method:m.httpMethod,scopes:m.scopes??[],body:!!m.request?.$ref,media:!!m.supportsMediaUpload})),...cursor+limit<selected.length?{next:cursor+limit}:{},pin:discoveryPin,gaps:["watchHistory/watchLater require explicit read-only Takeout","creator Analytics/Reporting need separate admitted profile and scopes","audio/video bytes require provider permission","write effects require original action rail verification; HTTP success is not EFFECTED"]})}function method(id){const found=methodMap.get(id);return found?Original.ok(structuredClone(found)):businessError("not_found","Unknown pinned YouTube method.","connector")}async function invokeInner(id,input,options={},level1=false,dispatch=()=>{}){if(closed)return unavailable();const m=methodMap.get(id);if(!m)return businessError("not_found","Unknown pinned YouTube method.","connector");const invalid=invalidSchema(m.params,input);if(invalid)return businessError("invalid_argument",invalid,"connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const conn=await vault.connection("youtube");if(!("ok"in conn))return conn;if(!conn.ok||conn.ok.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(closed||signal.aborted)return aborted();if(!m.scopes?.length)return businessError("failed_precondition","The pinned provider method "+m.id+" publishes no OAuth scope requirement. Scope/admission reconnaissance is required before a dispatch; no permission was guessed.","auth");if(!(m.scopes??[]).some(scope=>conn.ok.scopes.includes(scope)))return businessError("permission_denied","Method "+id+" requires one of the declared scopes: "+(m.scopes??[]).join(", ")+". Reauthorize this source; no API-key fallback.","auth");if(input.params.onBehalfOfContentOwner!==void 0&&!conn.ok.scopes.includes("https://www.googleapis.com/auth/youtubepartner"))return businessError("permission_denied","Content-owner operations require the partner scope and linked CMS admission.","auth");let pathname=m.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(input.params)){if(m.parameters?.[key]?.location==="path"){const text=String(value);if(text.split("/").some(segment=>segment==="."||segment==="..")||/[?#%\\]/.test(text))return businessError("invalid_argument","Path parameters cannot contain traversal or encoded routing material.","connector");const reserved=pathname.includes("{+"+key+"}");if(reserved&&!/^[A-Za-z0-9_./-]+$/.test(text))return businessError("invalid_argument","Reserved resource paths must be canonical provider resource names.","connector");pathname=pathname.replace(reserved?"{+"+key+"}":"{"+key+"}",reserved?text.split("/").map(encodeURIComponent).join("/"):encodeURIComponent(text))}else query.set(key,Array.isArray(value)?value.join(","):String(value))}if(pathname.includes("{"))return businessError("invalid_argument","Provider path parameter is missing.","connector");if(input.media)return businessError("failed_precondition","Media upload needs the separately admitted bounded streaming transport; no effect was dispatched.","connector");if(m.id==="youtube.youtube.v3.liveChat.messages.stream")return businessError("failed_precondition","The pinned server-streaming RPC requires an admitted cancelable stream transport; use liveChatMessages.list with pageToken until that profile is enabled.","connector");if(m.httpMethod!=="GET"&&!transport&&!level1)return businessError("failed_precondition","Write transport and original action admission are required for "+id+"; no effect was dispatched.","connector");const url=new URL(pathname,m.baseUrl??"https://www.googleapis.com/");url.search=query.toString();dispatch();const raw=transport?await transport("youtube",url.href,{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"},signal}):await auth.requestRaw("youtube",url.href,{signal,...level1?{method:m.httpMethod,...input.body===void 0?{}:{body:JSON.stringify(input.body),contentType:"application/json"}}:{}});if(closed||signal.aborted)return aborted();if(!("ok"in raw))return raw;if(Buffer.byteLength(raw.ok.body,"utf8")>2*1024*1024)return businessError("resource_exhausted","YouTube response exceeds the bounded broker body budget. Use an admitted streaming path; no body was truncated.","connector");const reason=parts.googleErrorReasonV1(raw.ok.body),baseOverride=parts.googleStatusOverrideV1(raw.ok.body),status=parts.webStatusErrorV1(raw.ok.status,{provider:"YouTube",what:id,headers:raw.ok.headers,bodyOverride:status2=>status2===403&&reason==="quotaExceeded"?{code:"resource_exhausted",retryability:"throttling",meaning:"the YouTube project quota bucket is exhausted (quotaExceeded)"}:baseOverride(status2),...reason?{detail:reason}:{}});if(status)return{err:status};if(m.supportsMediaDownload){return Original.ok({method:id,resource:m.resource,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain",items:[{id:input.params.id??input.params.resourceName,content:raw.ok.body,mime:raw.ok.headers["content-type"]??"text/plain"}],warnings:[],effect:"read",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}if(raw.ok.status===204||!raw.ok.body)return Original.ok({method:id,resource:m.resource,items:[],warnings:["Provider response carries no body; upstream effect remains unverified."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}});let data;try{data=JSON.parse(raw.ok.body)}catch{return businessError("data_loss","YouTube returned invalid JSON for "+id+".","connector")}if(!object(data))return businessError("data_loss","YouTube response must be an object.","connector");if(data.items!==void 0&&(!Array.isArray(data.items)||data.items.some(item=>!object(item))))return businessError("data_loss","YouTube response items are malformed.","connector");if(data.nextPageToken!==void 0&&(typeof data.nextPageToken!=="string"||!data.nextPageToken||data.nextPageToken.length>6e3))return businessError("data_loss","YouTube nextPageToken is malformed.","connector");const items=Array.isArray(data.items)?data.items:typeof data.id==="string"?[data]:[];return Original.ok({method:id,resource:m.resource,data,items,...typeof data.nextPageToken==="string"?{nextPageToken:data.nextPageToken}:{},warnings:m.httpMethod==="GET"?[]:["HTTP response accepted. Only original action read-after-write/event-confirm can mark EFFECTED."],effect:m.httpMethod==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}function invoke(id,input,options={},level1=false){let dispatched=false;return track(invokeInner(id,input,options,level1,()=>{dispatched=true}).catch(error=>{if(closed||options.signal?.aborted)return aborted();const cause=object(error)?Original.validateStructuredError(error.structuredError):void 0;return parts.connectorError("unavailable","Trusted YouTube transport failed before a confirmed provider response. Raw custody exception text is not a tool result.","transient",cause&&"ok"in cause?cause.ok:void 0)}).then(result=>dispatched?actionOutcome(result,"unknown"):actionNotApplied(result)))}async function*pages(id,params,options={}){const m=methodMap.get(id);if(!m||m.httpMethod!=="GET"){yield businessError("invalid_argument","Only pinned GET methods can be paginated.","connector");return}if(options.maxPages!==void 0&&(!Number.isInteger(options.maxPages)||options.maxPages<1)){yield businessError("invalid_argument","maxPages must be a positive integer.","connector");return}const seen=new Set;let token=typeof params.pageToken==="string"?params.pageToken:void 0,count=0;for(;;){if(token&&seen.has(token)){yield businessError("failed_precondition","YouTube repeated a page token; coverage is incomplete.","connector");return}if(token)seen.add(token);const result=await invoke(id,{params:{...params,...token?{pageToken:token}:{}}},options);yield result;if(!("ok"in result))return;count++;token=result.ok.nextPageToken;if(!token)return;if(options.maxPages!==void 0&&count>=options.maxPages){yield businessError("resource_exhausted","Selected page budget ended with a nonterminal token; coverage is incomplete.","connector");return}}}async function readInner(request,options={}){if(closed)return unavailable();const bad=validateRead(request,["fileId"]);if(bad)return bad;request=structuredClone(request);if(request.fileId!==void 0&&(!/^[A-Za-z0-9_-]{1,200}$/.test(request.fileId)||request.query!==void 0||request.since!==void 0||request.until!==void 0))return businessError("invalid_argument","An exact YouTube video read takes fileId without query or time bounds.","connector");const selected=request.fileId?"youtube.videos.list":request.query?"youtube.search.list":"youtube.activities.list";const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;if(signal.aborted)return aborted();const connection=await vault.connection("youtube");if(!("ok"in connection))return connection;const captured=structuredClone(connection.ok);if(!captured||captured.state!=="connected")return businessError("unauthenticated","Connect YouTube before reading its account.","auth");if(typeof captured.accountId!=="string"||!captured.accountId.trim())return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");const firstScopes=methodMap.get(selected)?.scopes??[],detailScopes=request.query?methodMap.get("youtube.videos.list")?.scopes??[]:firstScopes,scopes=firstScopes.filter(scope=>detailScopes.includes(scope)),readonly="https://www.googleapis.com/auth/youtube.readonly";const requiredScope=scopes.includes(readonly)&&captured.scopes.includes(readonly)?readonly:scopes.find(scope=>captured.scopes.includes(scope));if(!requiredScope)return businessError("permission_denied","The selected YouTube query requires one of its pinned read scopes.","auth");const fence=async()=>{if(closed||signal.aborted)return aborted();const current=await vault.connection("youtube");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==captured.accountId||!current.ok.scopes.includes(requiredScope))return businessError("permission_denied","YouTube selected read connection or scope changed.","auth");return Original.ok(void 0)};const boundInvoke=async(id,input)=>{const before=await fence();if(!("ok"in before))return before;const answer2=await invoke(id,input,{signal});const after=await fence();return"ok"in after?answer2:after};const wanted=request.limit??1,params=request.fileId?{part:["snippet","contentDetails","status","statistics"],id:[request.fileId]}:request.query?{part:["snippet"],q:request.query,type:["video"],maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}}:{part:["snippet","contentDetails"],mine:true,maxResults:Math.min(wanted,50),...request.since?{publishedAfter:new Date(request.since).toISOString()}:{},...request.until?{publishedBefore:new Date(request.until).toISOString()}:{}};let answer=await boundInvoke(selected,{params});if("err"in answer&&selected==="youtube.activities.list"&&answer.err.code==="permission_denied"){const channels=await boundInvoke("youtube.channels.list",{params:{part:["id"],mine:true,maxResults:1}});if("ok"in channels&&!channels.ok.items.length)return readResult("youtube",[],["This Google account has no YouTube channel, so it has no own activity to read; full sync records it as no-youtube-channel."])}if(!("ok"in answer))return answer;const items=[...answer.ok.items],seen=new Set;let steps=1;while(items.length<wanted&&answer.ok.nextPageToken){const token=answer.ok.nextPageToken;if(seen.has(token))return businessError("failed_precondition","Selected YouTube read repeated a token; no complete result was asserted.","connector");seen.add(token);if(++steps>100)return businessError("resource_exhausted","Selected YouTube read exceeded the page budget before satisfying its limit; no complete result was asserted.","connector");answer=await boundInvoke(selected,{params:{...params,pageToken:token}});if(!("ok"in answer))return answer;items.push(...answer.ok.items)}let retained=items.slice(0,wanted),resource=answer.ok.resource;if(request.query&&retained.length){const selectedItems=retained,details=[];for(let index=0;index<selectedItems.length;index+=50){const block=selectedItems.slice(index,index+50),ids=block.map(item=>object(item.id)?item.id.videoId:void 0).filter(id=>typeof id==="string");if(ids.length!==block.length)return businessError("data_loss","A selected YouTube video search result lacks its native video id.","connector");const hydrated=await boundInvoke("youtube.videos.list",{params:{part:["snippet","contentDetails","status","statistics","topicDetails","recordingDetails","localizations"],id:ids}});if(!("ok"in hydrated))return hydrated;for(const item of hydrated.ok.items)details.push({...item,_selection:block.find(selected2=>object(selected2.id)&&selected2.id.videoId===item.id)??null})}retained=details;resource="videos"}const records=retained.map(item=>({source:"youtube",sourceId:captured.accountId+":"+resource+":"+itemId(item),stream:resource,kind:"youtube."+resource.toLowerCase()+".changed",ts:itemTime(item),body:JSON.stringify(item),fields:{...item}}));const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;if(closed||signal.aborted)return aborted();return readResult("youtube",records,[...answer.ok.warnings,...answer.ok.nextPageToken||items.length>wanted?["More provider results exist beyond this selected batch."]:[],...retained.length<Math.min(items.length,wanted)?["Some selected videos are currently inaccessible/deleted; search metadata is retained only as an attributed missing detail, never a fabricated video body."]:[],"This selected API query does not establish complete YouTube account or archive coverage."])}function read(request,options={}){return track(readInner(request,options))}async function importTakeout(root=takeoutRoot??"",options={}){if(closed)return unavailable();if(!root)return businessError("failed_precondition","Supply an explicit extracted read-only Takeout copy; API success cannot substitute for history.","connector");const signal=options.signal?AbortSignal.any([stop.signal,options.signal]):stop.signal;const result=await readTakeout(root,signal);if(!("ok"in result))return result;if(closed||signal.aborted)return aborted();const saved=await cache(vault,"youtube",result.ok.records);if(!("ok"in saved))return saved;return result}const account=async()=>{const row=await vault.connection("youtube");if(!("ok"in row))return row;if(!row.ok||row.ok.state!=="connected")return businessError("unauthenticated","YouTube identity needs a connected account.","auth");if(!row.ok.accountId)return businessError("failed_precondition","Verified Google subject is missing; a short-lived grant id is never a durable account identity.","auth");return Original.ok(row.ok.accountId)};function actionSchema(schema){const{id:_discoveryType,...result}=schema;if(result.properties)result.properties=Object.fromEntries(Object.entries(result.properties).map(([key,value])=>[key,actionSchema(value)]));if(result.items)result.items=actionSchema(result.items);if(object(result.additionalProperties))result.additionalProperties=actionSchema(result.additionalProperties);return result}const actions={catalog,method:id=>{const result=method(id);if(!("ok"in result))return result;const m=result.ok;return Original.ok({...m,params:actionSchema(m.params),...!m.supportsMediaUpload&&m.id!=="youtube.youtube.v3.liveChat.messages.stream"&&(!m.profile||m.httpMethod==="GET")?{level:1,effect:m.httpMethod==="GET"?"read":"write"}:{}})},invoke:(id,input,options={})=>invoke(id,input,options,true)};const source={info,actions,catalog,method,invoke,pages,read,status:()=>closed?Promise.resolve(Original.ok({...info,state:"unavailable",message:"YouTube source is inactive."})):connectionState(vault,info),connect:options=>closed?Promise.resolve(unavailable()):track(auth.connect("youtube",options)),job:id=>closed?unavailable():auth.job(id),cancelJob:id=>auth.cancelJob(id),importTakeout:(root,options)=>track(importTakeout(root,options)),createConnector:(plan,options={})=>createYouTubeConnector({parts,invoke,method,account,isClosed:()=>closed},plan,options),async close(){closed=true;stop.abort();await Promise.allSettled([...pending])}};return source}export function itemId(item){if(typeof item.id==="string")return item.id;if(typeof item.videoId==="string")return item.videoId;if(object(item.id)){for(const key of["videoId","channelId","playlistId"])if(typeof item.id[key]==="string")return key+":"+item.id[key]}const value=JSON.parse(JSON.stringify(item.id??item));return createHash("sha256").update(Original.jcsCanonicalize(value)).digest("hex")}export function itemTime(item){const snippet=object(item.snippet)?item.snippet:{};for(const value of[item.time,item.updated,item.updatedAt,snippet.updatedAt,snippet.publishedAt])if(typeof value==="string"&&Number.isFinite(Date.parse(value)))return new Date(value).toISOString();return"1970-01-01T00:00:00.000Z"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const text=(bytes,description)=>({type:"string",minLength:1,"x-maxBytes":bytes,...description?{description}:{}});const source={type:"string",pattern:"^[a-z][a-z0-9-]{0,63}$"};const object=(properties,required)=>({type:"object",properties,required,additionalProperties:false});const risks={type:"array",maxItems:8,uniqueItems:true,items:{type:"string",enum:["contact","credential","third-party-private","private-opinion","complaint","embarrassing","health","relationship","financial","political","sexual","internal-joke","draft","unverified","other"]}};const decision={necessity:{type:"string",enum:["required","supporting","not-needed"]},risks,decision:{type:"string",enum:["include","redact","exclude","ask"],description:"Legacy ask is normalized to include; no confirmation step."},confidence:{type:"string",enum:["high","medium","low"]},reason:text(500),question:{description:"Ignored legacy compatibility field."}};const decisionRequired=["necessity","risks","decision","confidence","reason"];const fact={...object({ref:text(500,"Must match a selected candidate or Connector ref."),title:text(300),sourceQuote:text(2e3,"Exact source span; verified against selected evidence."),shareText:text(1600,"Exact outbound text for include/redact."),...decision},["ref","title","sourceQuote",...decisionRequired]),allOf:[{if:{properties:{decision:{enum:["include","redact"]}}},then:{required:["shareText"]}},{if:{properties:{decision:{const:"exclude"}}},then:{not:{required:["shareText"]}}}]};const file=(key,value)=>object({[key]:value,reviewBasis:{type:"string",enum:["content","metadata-only"]},...decision},[key,"reviewBasis",...decisionRequired]);const files=item=>({type:"array",minItems:1,maxItems:40,items:item,description:"Unique provider IDs or local paths; at most 20 included files, 10 MiB per file and 25 MiB total."});export const shareIntentSchema={...object({intent:text(2e3),audience:text(240),purpose:text(1e3),candidateRefs:{type:"array",maxItems:20,uniqueItems:true,items:text(500)},facts:{type:"array",maxItems:40,items:fact,description:"Required when any candidate or Connector ref is selected. No facts when no refs are selected."},connectorSelections:{type:"array",minItems:1,maxItems:5,items:object({ref:text(500,"Unique across candidateRefs and Connector selections."),source,action:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,199}$"},params:{type:"object",description:"Complete JSON, at most 32 KiB; credentials are refused."}},["ref","source","action","params"])},fileSelection:{oneOf:[object({source:{const:"computer-files"},folderPath:{type:"string",description:"Absolute permitted local directory."},folderLabel:text(300),files:files(file("path",{type:"string",description:"Absolute path inside folderPath."}))},["source","folderPath","folderLabel","files"]),object({source:{const:"google-drive"},folderLabel:text(300),files:files(file("fileId",{type:"string",pattern:"^[A-Za-z0-9_-]{1,500}$"}))},["source","folderLabel","files"]),object({source:{const:"connector"},connector:source,folderLabel:text(300),files:files(file("id",text(1024)))},["source","connector","folderLabel","files"])]},keywords:{type:"array",maxItems:20,items:text(120)},excludeTerms:{type:"array",maxItems:20,items:text(120)},maxItems:{type:"integer",minimum:1,maximum:20,default:8}},["intent","audience","purpose","candidateRefs"]),allOf:[{if:{anyOf:[{properties:{candidateRefs:{minItems:1}},required:["candidateRefs"]},{required:["connectorSelections"]}]},then:{required:["facts"],properties:{facts:{minItems:1}}},else:{properties:{facts:{maxItems:0}}}}]};const url={type:"string",description:"Exact short link returned by this Share service."};export const shareActionSchemas=[{name:"share.preview",effect:"read",description:"Optionally review one static Share selection. Publication may be called directly.",inputSchema:shareIntentSchema},{name:"share.create-link",effect:"write",description:"Create one static shared snapshot directly from this complete selection, or an existing preview. No prior preview or confirmation is required.",inputSchema:{oneOf:[shareIntentSchema,object({previewId:{type:"string",minLength:1}},["previewId"])]}},{name:"share.inspect-link",effect:"read",description:"Inspect the verified contents and file metadata of one shared link.",inputSchema:object({url},["url"])},{name:"share.read-file",effect:"read",description:"Read bounded UTF-8 text or download metadata from a verified shared file.",inputSchema:object({url,fileId:{type:"string",pattern:"^[A-Za-z0-9_-]{8}$"}},["url","fileId"])}];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{};
|
|
1
|
+
export{shareActionSchemas,shareIntentSchema}from"./action-schemas.js";
|