AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(pieces): add AI-agent atomics and output schemas to linkedin, youtube and twitter (#15688)
Odai Ahmad911117a8f8c7
diff --git a/bun.lock b/bun.lockindex 550b88e3561..354f7037a74 100644--- a/bun.lock+++ b/bun.lock@@ -5143,7 +5143,7 @@},"packages/pieces/community/linkedin": {"name": "@activepieces/piece-linkedin",- "version": "0.3.0",+ "version": "0.4.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -9267,7 +9267,7 @@},"packages/pieces/community/twitter": {"name": "@activepieces/piece-twitter",- "version": "0.3.7",+ "version": "0.4.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -10048,7 +10048,7 @@},"packages/pieces/community/youtube": {"name": "@activepieces/piece-youtube",- "version": "0.6.0",+ "version": "0.7.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/community/linkedin/package.json b/packages/pieces/community/linkedin/package.jsonindex d78cdc1eb99..53c8b962555 100644--- a/packages/pieces/community/linkedin/package.json+++ b/packages/pieces/community/linkedin/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-linkedin",- "version": "0.3.0",+ "version": "0.4.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {diff --git a/packages/pieces/community/linkedin/src/index.ts b/packages/pieces/community/linkedin/src/index.tsindex a1f7b7c0be0..6ed72a5088d 100644--- a/packages/pieces/community/linkedin/src/index.ts+++ b/packages/pieces/community/linkedin/src/index.ts@@ -9,6 +9,12 @@ import { createCompanyUpdate } from './lib/actions/create-company-update';import { createShareUpdate } from './lib/actions/create-share-update';import { createCustomApiCallAction } from '@activepieces/pieces-common';import { linkedinCommon } from './lib/common';+import { createMemberPost } from './lib/actions/create-member-post';+import { getCurrentMemberProfile } from './lib/actions/get-current-member-profile';+import { listManagedOrganizations } from './lib/actions/list-managed-organizations';+import { updatePostCommentary } from './lib/actions/update-post-commentary';+import { deletePost } from './lib/actions/delete-post';+import { createImageUploadUrl } from './lib/actions/create-image-upload-url';export const linkedinAuth = PieceAuth.OAuth2({authUrl: 'https://www.linkedin.com/oauth/v2/authorization',@@ -28,7 +34,7 @@ export const linkedin = createPiece({displayName: 'LinkedIn',description: 'Connect and network with professionals',- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/linkedin.png',categories: [PieceCategory.MARKETING],authors: ["aasimsani","kishanprmr","MoShizzle","khaledmashaly","abuaboud", "izdrail"],@@ -36,6 +42,12 @@ export const linkedin = createPiece({actions: [createShareUpdate,createCompanyUpdate,+ getCurrentMemberProfile,+ listManagedOrganizations,+ createMemberPost,+ updatePostCommentary,+ deletePost,+ createImageUploadUrl,createCustomApiCallAction({auth: linkedinAuth,baseUrl: () => {diff --git a/packages/pieces/community/linkedin/src/lib/actions/create-company-update.ts b/packages/pieces/community/linkedin/src/lib/actions/create-company-update.tsindex 28a7bc581c9..3ffbfc6fb20 100644--- a/packages/pieces/community/linkedin/src/lib/actions/create-company-update.ts+++ b/packages/pieces/community/linkedin/src/lib/actions/create-company-update.ts@@ -1,11 +1,5 @@import { createAction } from '@activepieces/pieces-framework';-import {- AuthenticationType,- httpClient,- HttpMethod,- HttpRequest,-} from '@activepieces/pieces-common';-import { Image, linkedinCommon, santizeText } from '../common';+import { linkedinCommon, publishOrganizationPost } from '../common';import { linkedinAuth } from '../..';import { createCompanyUpdateActionOutputSchema } from '../output-schemas';@@ -15,7 +9,7 @@ export const createCompanyUpdate = createAction({classification: 'WRITE',displayName: 'Create Company Update',description: 'Create a new company update for Company Page',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Publishes a new post to a LinkedIn organization (company) page, with optional image and link preview; posts are always public. Use this to share content on behalf of a company rather than a personal profile, and requires the target organization id plus admin access to that page. Not idempotent: each call creates a separate post, so repeating it with the same text produces a duplicate.',@@ -32,49 +26,17 @@ export const createCompanyUpdate = createAction({outputSchema: createCompanyUpdateActionOutputSchema,run: async (context) => {- const imageUrl = context.propsValue.imageUrl;- const bodyConfig: {- urn: string;- text: string;- link?: string | undefined;- linkDescription?: string | undefined;- linkTitle?: string | undefined;- visibility: string;- image?: Image | undefined;- } = {- urn: `organization:${context.propsValue.company}`,- text: santizeText(context.propsValue.text),- link: context.propsValue.link,- linkDescription: context.propsValue.linkDescription,- linkTitle: context.propsValue.linkTitle,- visibility: 'PUBLIC',- };+ const { company, text, link, linkTitle, linkDescription, imageUrl } =+ context.propsValue;- if (imageUrl) {- bodyConfig.image = await linkedinCommon.uploadImage(- context.auth.access_token,- `organization:${context.propsValue.company}`,- imageUrl- );- }-- const requestBody = linkedinCommon.generatePostRequestBody(bodyConfig);- const createPostHeaders: any = linkedinCommon.linkedinHeaders;-- const request: HttpRequest = {- method: HttpMethod.POST,- url: `${linkedinCommon.baseUrl}/rest/posts`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: context.auth.access_token,- },- headers: createPostHeaders,- body: requestBody,- };-- const response = await httpClient.sendRequest(request);- return {- success: true,- };+ return await publishOrganizationPost({+ accessToken: context.auth.access_token,+ organizationId: String(company),+ text,+ imageFile: imageUrl,+ link,+ linkTitle,+ linkDescription,+ });},});diff --git a/packages/pieces/community/linkedin/src/lib/actions/create-image-upload-url.ts b/packages/pieces/community/linkedin/src/lib/actions/create-image-upload-url.tsnew file mode 100644index 00000000000..89cd729ac4e--- /dev/null+++ b/packages/pieces/community/linkedin/src/lib/actions/create-image-upload-url.ts@@ -0,0 +1,85 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import {+ AuthenticationType,+ HttpMethod,+ httpClient,+} from '@activepieces/pieces-common';+import {+ buildLinkedinError,+ getMemberUrn,+ linkedinCommon,+} from '../common';+import { linkedinAuth } from '../..';+import { createImageUploadUrlActionOutputSchema } from '../output-schemas';++export const createImageUploadUrl = createAction({+ auth: linkedinAuth,+ name: 'create_image_upload_url',+ classification: 'WRITE',+ displayName: 'Create Image Upload URL',+ description: 'Reserve a LinkedIn image URN and a URL to upload the bytes to',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Registers a new LinkedIn image and reserves a short-lived URL to upload its bytes to. This is step one of two: PUT the raw image bytes to the returned upload URL, then pass the returned image URN as the Image URN of Create Member Post. The URL expires, so reserve it immediately before uploading, and note it is not idempotent because each call reserves a new image.',+ idempotent: false,+ },+ props: {+ owner_urn: Property.ShortText({+ displayName: 'Owner URN',+ description:+ 'Who will own the image. Defaults to the connected member.',+ required: false,+ }),+ },+ outputSchema: createImageUploadUrlActionOutputSchema,++ run: async (context) => {+ const ownerInput = context.propsValue.owner_urn;+ const owner =+ ownerInput && ownerInput.length > 0+ ? ownerInput+ : getMemberUrn(context.auth.data.id_token);++ try {+ const response = await httpClient.sendRequest<InitializeUploadResponse>({+ method: HttpMethod.POST,+ url: `${linkedinCommon.baseUrl}/rest/images`,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: context.auth.access_token,+ },+ headers: { ...linkedinCommon.linkedinHeaders },+ queryParams: {+ action: 'initializeUpload',+ },+ body: {+ initializeUploadRequest: {+ owner,+ },+ },+ });++ const value = response.body.value;+ return {+ owner_urn: owner,+ image_urn: value?.image ?? null,+ upload_url: value?.uploadUrl ?? null,+ upload_url_expires_at: value?.uploadUrlExpiresAt ?? null,+ };+ } catch (error) {+ throw buildLinkedinError({+ error,+ resource: `an image upload for ${owner}`,+ });+ }+ },+});++interface InitializeUploadResponse {+ value?: {+ image?: string;+ uploadUrl?: string;+ uploadUrlExpiresAt?: number;+ };+}diff --git a/packages/pieces/community/linkedin/src/lib/actions/create-member-post.ts b/packages/pieces/community/linkedin/src/lib/actions/create-member-post.tsnew file mode 100644index 00000000000..f75ff6a8b41--- /dev/null+++ b/packages/pieces/community/linkedin/src/lib/actions/create-member-post.ts@@ -0,0 +1,94 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import {+ buildLinkedinError,+ linkedinCommon,+ publishMemberPost,+} from '../common';+import { linkedinAuth } from '../..';+import { createMemberPostActionOutputSchema } from '../output-schemas';++export const createMemberPost = createAction({+ auth: linkedinAuth,+ name: 'create_member_post',+ classification: 'WRITE',+ displayName: 'Create Member Post',+ description:+ "Publish a post on the connected LinkedIn member's personal profile",+ audience: 'ai',+ aiMetadata: {+ description:+ "Publishes a post to the connected LinkedIn member's own profile and returns the created post URN. This is the only way to publish from this piece: posts always appear as the member who authorized the connection, and publishing as a company page is not available. Not idempotent — every call creates a new post, so a retry publishes a duplicate.",+ idempotent: false,+ },+ props: {+ text: Property.LongText({+ displayName: 'Text',+ description: 'Body of the post.',+ required: true,+ }),+ visibility: Property.StaticDropdown({+ displayName: 'Visibility',+ description: 'Who can see the post.',+ required: true,+ defaultValue: 'PUBLIC',+ options: {+ options: [+ { label: 'Public', value: 'PUBLIC' },+ { label: 'Connections Only', value: 'CONNECTIONS' },+ ],+ },+ }),+ link: Property.ShortText({+ displayName: 'Link URL',+ description: 'Optional URL to attach as an article preview.',+ required: false,+ }),+ link_title: Property.ShortText({+ displayName: 'Link Title',+ required: false,+ }),+ link_description: Property.ShortText({+ displayName: 'Link Description',+ required: false,+ }),+ image: linkedinCommon.imageUrl,+ image_urn: Property.ShortText({+ displayName: 'Image URN',+ description:+ 'URN of an image already uploaded to LinkedIn, for example urn:li:image:D4E10AQ.... Obtain it from Create Image Upload URL and PUT the bytes to that upload URL before posting.',+ required: false,+ }),+ },+ outputSchema: createMemberPostActionOutputSchema,++ run: async (context) => {+ const {+ text,+ visibility,+ link,+ link_title,+ link_description,+ image,+ image_urn,+ } = context.propsValue;++ try {+ return await publishMemberPost({+ accessToken: context.auth.access_token,+ idToken: context.auth.data.id_token,+ text,+ visibility,+ imageFile: image,+ imageUrn: image_urn,+ link,+ linkTitle: link_title,+ linkDescription: link_description,+ });+ } catch (error) {+ throw buildLinkedinError({+ error,+ resource: 'the authenticated member profile',+ });+ }+ },+});diff --git a/packages/pieces/community/linkedin/src/lib/actions/create-share-update.ts b/packages/pieces/community/linkedin/src/lib/actions/create-share-update.tsindex 657e2d691db..a95e81140e6 100644--- a/packages/pieces/community/linkedin/src/lib/actions/create-share-update.ts+++ b/packages/pieces/community/linkedin/src/lib/actions/create-share-update.ts@@ -1,12 +1,5 @@import { createAction } from '@activepieces/pieces-framework';-import {- AuthenticationType,- httpClient,- HttpMethod,- HttpRequest,-} from '@activepieces/pieces-common';-import { Image, linkedinCommon, santizeText } from '../common';-import jwt, { JwtPayload } from 'jsonwebtoken';+import { linkedinCommon, publishMemberPost } from '../common';import { linkedinAuth } from '../..';import { createShareUpdateActionOutputSchema } from '../output-schemas';@@ -16,7 +9,7 @@ export const createShareUpdate = createAction({classification: 'WRITE',displayName: 'Create Share Update',description: 'Create a share update on LinkedIn',- audience: 'both',+ audience: 'human',aiMetadata: {description:"Publishes a new post to the authenticated user's personal LinkedIn profile, with optional image, link preview, and visibility setting. Use this to share content as an individual member (not a company page — use Create Company Update for that). Not idempotent: each call creates a separate post, so calling it again with the same text produces a duplicate.",@@ -33,46 +26,18 @@ export const createShareUpdate = createAction({outputSchema: createShareUpdateActionOutputSchema,run: async (context) => {-- const token = context.auth.data.id_token;- const decoded: JwtPayload = jwt.decode(token) as JwtPayload;- const imageUrl = context.propsValue.imageUrl;- const { text, link, linkDescription, linkTitle, visibility } =+ const { text, link, linkDescription, linkTitle, visibility, imageUrl } =context.propsValue;- let image: Image | undefined;- if (imageUrl) {- image = await linkedinCommon.uploadImage(- context.auth.access_token,- `person:${decoded.sub}`,- imageUrl- );- }- const requestBody = linkedinCommon.generatePostRequestBody({- urn: `person:${decoded.sub}`,- text: santizeText(text),+ return await publishMemberPost({+ accessToken: context.auth.access_token,+ idToken: context.auth.data.id_token,+ text,+ visibility,+ imageFile: imageUrl,link,- linkDescription,linkTitle,- visibility,- image,+ linkDescription,});- const createPostHeaders: any = linkedinCommon.linkedinHeaders;-- const request: HttpRequest = {- method: HttpMethod.POST,- url: `${linkedinCommon.baseUrl}/rest/posts`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: context.auth.access_token,- },- headers: createPostHeaders,- body: requestBody,- };-- const response = await httpClient.sendRequest(request);- return {- success: true,- };},});diff --git a/packages/pieces/community/linkedin/src/lib/actions/delete-post.ts b/packages/pieces/community/linkedin/src/lib/actions/delete-post.tsnew file mode 100644index 00000000000..66699b71ac4--- /dev/null+++ b/packages/pieces/community/linkedin/src/lib/actions/delete-post.ts@@ -0,0 +1,70 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import {+ AuthenticationType,+ HttpMethod,+ httpClient,+} from '@activepieces/pieces-common';+import {+ buildLinkedinError,+ encodeUrn,+ getLinkedinErrorStatus,+ linkedinCommon,+} from '../common';+import { linkedinAuth } from '../..';+import { deletePostActionOutputSchema } from '../output-schemas';++export const deletePost = createAction({+ auth: linkedinAuth,+ name: 'delete_post',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Post',+ description: 'Permanently delete a LinkedIn post by its URN',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a LinkedIn post, together with its comments, reactions and statistics. This cannot be undone and the post cannot be recovered, so confirm the URN is the intended post before calling; to fix wording instead, use Update Post Commentary. Safe to retry: deleting an already deleted post reports success without changing anything.',+ idempotent: true,+ },+ props: {+ post_urn: Property.ShortText({+ displayName: 'Post URN',+ description:+ 'URN of the post to delete, for example urn:li:share:7212345678901234567.',+ required: true,+ }),+ },+ outputSchema: deletePostActionOutputSchema,++ run: async (context) => {+ const postUrn = context.propsValue.post_urn;+ try {+ await httpClient.sendRequest({+ method: HttpMethod.DELETE,+ url: `${linkedinCommon.baseUrl}/rest/posts/${encodeUrn(postUrn)}`,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: context.auth.access_token,+ },+ headers: {+ ...linkedinCommon.linkedinHeaders,+ 'X-RestLi-Method': 'DELETE',+ },+ });++ return {+ deleted: true,+ post_urn: postUrn,+ already_deleted: false,+ };+ } catch (error) {+ if (getLinkedinErrorStatus(error) === 404) {+ return {+ deleted: true,+ post_urn: postUrn,+ already_deleted: true,+ };+ }+ throw buildLinkedinError({ error, resource: `the post ${postUrn}` });+ }+ },+});diff --git a/packages/pieces/community/linkedin/src/lib/actions/get-current-member-profile.ts b/packages/pieces/community/linkedin/src/lib/actions/get-current-member-profile.tsnew file mode 100644index 00000000000..0513c0267b0--- /dev/null+++ b/packages/pieces/community/linkedin/src/lib/actions/get-current-member-profile.ts@@ -0,0 +1,84 @@+import { createAction } from '@activepieces/pieces-framework';+import {+ AuthenticationType,+ HttpMethod,+ httpClient,+} from '@activepieces/pieces-common';+import { buildLinkedinError, linkedinCommon } from '../common';+import { linkedinAuth } from '../..';+import { getCurrentMemberProfileActionOutputSchema } from '../output-schemas';++const readLocale = (locale: unknown): string | null => {+ if (typeof locale === 'string') {+ return locale;+ }+ if (typeof locale === 'object' && locale !== null) {+ const language = Reflect.get(locale, 'language');+ const country = Reflect.get(locale, 'country');+ if (typeof language === 'string' && typeof country === 'string') {+ return `${language}_${country}`;+ }+ if (typeof language === 'string') {+ return language;+ }+ }+ return null;+};++export const getCurrentMemberProfile = createAction({+ auth: linkedinAuth,+ name: 'get_current_member_profile',+ classification: 'READ',+ displayName: 'Get Current Member Profile',+ description: 'Get the profile of the LinkedIn member who owns the connection',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Reads the OpenID profile of the LinkedIn member that authorized the connection, including the member URN needed as the author of a post or an image upload. Call this first whenever another action asks for an author URN. Safe to retry; it never changes anything.',+ idempotent: true,+ },+ props: {},+ outputSchema: getCurrentMemberProfileActionOutputSchema,++ run: async (context) => {+ try {+ const response = await httpClient.sendRequest<UserInfoResponse>({+ method: HttpMethod.GET,+ url: `${linkedinCommon.baseUrl}/v2/userinfo`,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: context.auth.access_token,+ },+ });++ const profile = response.body;+ return {+ sub: profile.sub ?? null,+ member_urn: profile.sub ? `urn:li:person:${profile.sub}` : null,+ name: profile.name ?? null,+ given_name: profile.given_name ?? null,+ family_name: profile.family_name ?? null,+ email: profile.email ?? null,+ email_verified: profile.email_verified ?? null,+ picture: profile.picture ?? null,+ locale: readLocale(profile.locale),+ };+ } catch (error) {+ throw buildLinkedinError({+ error,+ resource: 'the authenticated member profile',+ });+ }+ },+});++interface UserInfoResponse {+ sub?: string;+ name?: string;+ given_name?: string;+ family_name?: string;+ email?: string;+ email_verified?: boolean;+ picture?: string;+ locale?: unknown;+}diff --git a/packages/pieces/community/linkedin/src/lib/actions/list-managed-organizations.ts b/packages/pieces/community/linkedin/src/lib/actions/list-managed-organizations.tsnew file mode 100644index 00000000000..82c3d2078a6--- /dev/null+++ b/packages/pieces/community/linkedin/src/lib/actions/list-managed-organizations.ts@@ -0,0 +1,199 @@+import { createAction } from '@activepieces/pieces-framework';+import {+ AuthenticationType,+ HttpMethod,+ httpClient,+} from '@activepieces/pieces-common';+import {+ buildLinkedinError,+ encodeUrn,+ linkedinCommon,+ linkedinRawGet,+ organizationIdOf,+} from '../common';+import { linkedinAuth } from '../..';+import { listManagedOrganizationsActionOutputSchema } from '../output-schemas';++const ACL_PAGE_SIZE = 100;+const ACL_MAX_PAGES = 20;+const LOOKUP_CHUNK_SIZE = 50;++const readAclOrganizationUrn = (element: AclElement): string | null =>+ element.organizationTarget ??+ element.organization ??+ element.organizationalTarget ??+ null;++const hasNextLink = (paging: AclPaging | undefined): boolean | null => {+ if (paging === undefined || !Array.isArray(paging.links)) {+ return null;+ }+ return paging.links.some((link) => link.rel === 'next');+};++const chunk = <T>({ values, size }: { values: T[]; size: number }): T[][] => {+ const chunks: T[][] = [];+ for (let index = 0; index < values.length; index += size) {+ chunks.push(values.slice(index, index + size));+ }+ return chunks;+};++const fetchAllAclElements = async ({+ accessToken,+}: {+ accessToken: string;+}): Promise<AclElement[]> => {+ const collected: AclElement[] = [];+ let start = 0;++ for (let page = 0; page < ACL_MAX_PAGES; page++) {+ const response = await httpClient.sendRequest<AclResponse>({+ method: HttpMethod.GET,+ url: `${linkedinCommon.baseUrl}/rest/organizationAcls`,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: accessToken,+ },+ headers: { ...linkedinCommon.linkedinHeaders },+ queryParams: {+ q: 'roleAssignee',+ role: 'ADMINISTRATOR',+ state: 'APPROVED',+ start: String(start),+ count: String(ACL_PAGE_SIZE),+ },+ });++ const elements = response.body.elements ?? [];+ collected.push(...elements);++ if (elements.length === 0) {+ break;+ }+ const next = hasNextLink(response.body.paging);+ if (next === false) {+ break;+ }+ if (next === null && elements.length < ACL_PAGE_SIZE) {+ break;+ }+ start += elements.length;+ }++ return collected;+};++export const listManagedOrganizations = createAction({+ auth: linkedinAuth,+ name: 'list_managed_organizations',+ classification: 'SEARCH',+ displayName: 'List Managed Organizations',+ description:+ 'List the LinkedIn organization pages the connected member administers',+ audience: 'ai',+ aiMetadata: {+ description:+ "Lists every LinkedIn company page on which the connected member holds an approved administrator role, with each page's organization id, URN, vanity name, website and the member's role on it. Use it to discover or audit which company pages an account manages; no other action in this piece consumes the organization id yet. Safe to retry; read-only.",+ idempotent: true,+ },+ props: {},+ outputSchema: listManagedOrganizationsActionOutputSchema,++ run: async (context) => {+ const accessToken = context.auth.access_token;+ try {+ const elements = await fetchAllAclElements({ accessToken });+ const seen = new Set<string>();+ const rows = elements+ .map((element) => ({+ organization_urn: readAclOrganizationUrn(element),+ role: element.role ?? null,+ state: element.state ?? null,+ }))+ .filter((row) => {+ if (row.organization_urn === null || seen.has(row.organization_urn)) {+ return false;+ }+ seen.add(row.organization_urn);+ return true;+ });++ if (elements.length > 0 && rows.length === 0) {+ throw new Error(+ `LinkedIn returned ${elements.length} organization role assignment(s) but none carried a recognised organization URN, so no organization id could be resolved. The keys present on the first entry were: ${Object.keys(+ elements[0]+ ).join(', ')}. This is an API shape change, not an empty account.`+ );+ }++ if (rows.length === 0) {+ return { organizations: [], count: 0 };+ }++ const ids = rows.map((row) => organizationIdOf(String(row.organization_urn)));+ const results: OrganizationLookupResults = {};+ for (const idChunk of chunk({ values: ids, size: LOOKUP_CHUNK_SIZE })) {+ const lookup = await linkedinRawGet<OrganizationLookupResponse>({+ accessToken,+ resource: 'the names of the administered organizations',+ url: `${linkedinCommon.baseUrl}/rest/organizations?ids=List(${idChunk+ .map((id) => encodeUrn(id))+ .join(',')})`,+ });+ Object.assign(results, lookup.results ?? {});+ }++ const organizations = rows.map((row) => {+ const id = organizationIdOf(String(row.organization_urn));+ const organization = results[id];+ return {+ organization_urn: row.organization_urn,+ organization_id: id,+ name: organization?.localizedName ?? null,+ vanity_name: organization?.vanityName ?? null,+ website: organization?.localizedWebsite ?? null,+ role: row.role,+ state: row.state,+ };+ });++ return { organizations, count: organizations.length };+ } catch (error) {+ throw buildLinkedinError({+ error,+ resource: 'the organizations administered by this account',+ });+ }+ },+});++interface AclElement {+ role?: string;+ state?: string;+ organization?: string;+ organizationTarget?: string;+ organizationalTarget?: string;+}++interface AclPaging {+ links?: { rel?: string }[];+}++interface AclResponse {+ elements?: AclElement[];+ paging?: AclPaging;+}++type OrganizationLookupResults = Record<+ string,+ {+ localizedName?: string;+ vanityName?: string;+ localizedWebsite?: string;+ }+>;++interface OrganizationLookupResponse {+ results?: OrganizationLookupResults;+}diff --git a/packages/pieces/community/linkedin/src/lib/actions/update-post-commentary.ts b/packages/pieces/community/linkedin/src/lib/actions/update-post-commentary.tsnew file mode 100644index 00000000000..148486557cd--- /dev/null+++ b/packages/pieces/community/linkedin/src/lib/actions/update-post-commentary.ts@@ -0,0 +1,131 @@+import { Property, createAction } from '@activepieces/pieces-framework';+import {+ AuthenticationType,+ HttpMethod,+ httpClient,+} from '@activepieces/pieces-common';+import {+ buildLinkedinError,+ encodeUrn,+ linkedinCommon,+ santizeText,+} from '../common';+import { linkedinAuth } from '../..';+import { updatePostCommentaryActionOutputSchema } from '../output-schemas';++export const updatePostCommentary = createAction({+ auth: linkedinAuth,+ name: 'update_post_commentary',+ classification: 'WRITE',+ displayName: 'Update Post Commentary',+ description:+ 'Edit the commentary, call-to-action label or landing page of an existing LinkedIn post',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Edits an already published LinkedIn post in place, changing only the fields you supply. Use this to correct a post rather than Delete Post followed by a fresh Create Member Post, which would throw away the existing engagement. At least one field is required, fields left empty keep their current value, and applying the same values again is safe to retry.',+ idempotent: true,+ },+ props: {+ post_urn: Property.ShortText({+ displayName: 'Post URN',+ description:+ 'URN of the post to edit, for example urn:li:share:7212345678901234567.',+ required: true,+ }),+ commentary: Property.LongText({+ displayName: 'Commentary',+ description: 'New body text. Leave empty to keep the current text.',+ required: false,+ }),+ content_call_to_action_label: Property.StaticDropdown({+ displayName: 'Call To Action Label',+ description:+ 'New call-to-action button label. Leave empty to keep the current one.',+ required: false,+ options: {+ options: [+ { label: 'Apply', value: 'APPLY' },+ { label: 'Download', value: 'DOWNLOAD' },+ { label: 'View Quote', value: 'VIEW_QUOTE' },+ { label: 'Learn More', value: 'LEARN_MORE' },+ { label: 'Sign Up', value: 'SIGN_UP' },+ { label: 'Subscribe', value: 'SUBSCRIBE' },+ { label: 'Register', value: 'REGISTER' },+ { label: 'Join', value: 'JOIN' },+ { label: 'Attend', value: 'ATTEND' },+ { label: 'Request Demo', value: 'REQUEST_DEMO' },+ { label: 'See More', value: 'SEE_MORE' },+ ],+ },+ }),+ content_landing_page: Property.ShortText({+ displayName: 'Landing Page URL',+ description:+ 'New destination for the call-to-action button. Leave empty to keep the current one.',+ required: false,+ }),+ },+ outputSchema: updatePostCommentaryActionOutputSchema,++ run: async (context) => {+ const {+ post_urn,+ commentary,+ content_call_to_action_label,+ content_landing_page,+ } = context.propsValue;++ const patch = {+ ...(commentary !== undefined && commentary !== null && commentary !== ''+ ? { commentary: santizeText(commentary) }+ : {}),+ ...(content_call_to_action_label !== undefined &&+ content_call_to_action_label !== null &&+ content_call_to_action_label !== ''+ ? { contentCallToActionLabel: content_call_to_action_label }+ : {}),+ ...(content_landing_page !== undefined &&+ content_landing_page !== null &&+ content_landing_page !== ''+ ? { contentLandingPage: content_landing_page }+ : {}),+ };++ const updatedFields = Object.keys(patch);+ if (updatedFields.length === 0) {+ throw new Error(+ 'Nothing to update. Supply at least one of Commentary, Call To Action Label or Landing Page URL.'+ );+ }++ try {+ await httpClient.sendRequest({+ method: HttpMethod.POST,+ url: `${linkedinCommon.baseUrl}/rest/posts/${encodeUrn(post_urn)}`,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: context.auth.access_token,+ },+ headers: {+ ...linkedinCommon.linkedinHeaders,+ 'X-RestLi-Method': 'PARTIAL_UPDATE',+ },+ body: {+ patch: {+ $set: patch,+ },+ },+ });++ return {+ success: true,+ post_urn,+ updated_fields: updatedFields.join(', '),+ updated_field_count: updatedFields.length,+ };+ } catch (error) {+ throw buildLinkedinError({ error, resource: `the post ${post_urn}` });+ }+ },+});diff --git a/packages/pieces/community/linkedin/src/lib/common/index.ts b/packages/pieces/community/linkedin/src/lib/common/index.tsindex 1d16619c57f..3d281c39552 100644--- a/packages/pieces/community/linkedin/src/lib/common/index.ts+++ b/packages/pieces/community/linkedin/src/lib/common/index.ts@@ -3,9 +3,12 @@ import {HttpMethod,httpClient,AuthenticationType,+ HttpError,+ HttpHeaders,} from '@activepieces/pieces-common';import FormData from 'form-data';+import jwt from 'jsonwebtoken';import { linkedinAuth } from '../..';export const santizeText = (text: string) => {@@ -137,13 +140,15 @@ export const linkedinCommon = {generatePostRequestBody: (data: {urn: string;- text: any;+ text: string;link?: string | undefined;linkTitle?: string | undefined;linkDescription?: string | undefined;visibility: string;image?: Image | undefined;+ imageUrn?: string | undefined;}) => {+ const mediaId = data.image?.value.image ?? data.imageUrn;const requestObject: Post = {author: `urn:li:${data.urn}`,lifecycleState: 'PUBLISHED',@@ -161,13 +166,13 @@ export const linkedinCommon = {source: data.link,title: data.linkTitle,description: data.linkDescription,- thumbnail: data.image?.value.image,+ thumbnail: mediaId,},};- } else if (data.image) {+ } else if (mediaId) {requestObject.content = {media: {- id: data.image.value.image,+ id: mediaId,},};}@@ -219,6 +224,236 @@ export const linkedinCommon = {return uploadData;},};++const readErrorStatus = (error: unknown): number | null => {+ if (typeof error !== 'object' || error === null) {+ return null;+ }+ const response = Reflect.get(error, 'response');+ if (typeof response !== 'object' || response === null) {+ return null;+ }+ const status = Reflect.get(response, 'status');+ return typeof status === 'number' ? status : null;+};++export const getLinkedinErrorStatus = (error: unknown): number | null =>+ readErrorStatus(error);++export const buildLinkedinError = ({+ error,+ resource,+}: {+ error: unknown;+ resource: string;+}): Error => {+ const status = readErrorStatus(error);+ if (status === 401) {+ return new Error(+ `LinkedIn rejected the connection while accessing ${resource}. Reconnect the LinkedIn account and try again.`+ );+ }+ if (status === 403) {+ return new Error(+ `LinkedIn denied access to ${resource}. The connected account needs an approved admin role on the target LinkedIn page, and the connection must grant the matching permission.`+ );+ }+ if (status === 404) {+ return new Error(`LinkedIn could not find ${resource}.`);+ }+ if (status === 429) {+ return new Error(+ `LinkedIn rate limit reached while accessing ${resource}. Wait before retrying.`+ );+ }+ return error instanceof Error ? error : new Error(String(error));+};++export const encodeUrn = (urn: string): string => encodeURIComponent(urn);++export const organizationIdOf = (urn: string): string =>+ urn.substring(urn.lastIndexOf(':') + 1);++export const getMemberSub = (idToken: string): string => {+ const decoded = jwt.decode(idToken);+ if (decoded === null || typeof decoded === 'string') {+ return '';+ }+ const sub = decoded.sub;+ if (typeof sub !== 'string' || sub.length === 0) {+ return '';+ }+ return sub;+};++export const getMemberUrn = (idToken: string): string => {+ const sub = getMemberSub(idToken);+ if (sub.length === 0) {+ throw new Error(+ 'Could not resolve the authenticated LinkedIn member from the connection. Reconnect the LinkedIn account so that an OpenID token is issued.'+ );+ }+ return `urn:li:person:${sub}`;+};++export const linkedinJsonHeaders = (): HttpHeaders => ({+ ...linkedinCommon.linkedinHeaders,+});++export const linkedinRawGet = async <T>({+ accessToken,+ url,+ resource,+}: {+ accessToken: string;+ url: string;+ resource: string;+}): Promise<T> => {+ const response = await fetch(url, {+ method: 'GET',+ headers: {+ ...linkedinCommon.linkedinHeaders,+ Authorization: `Bearer ${accessToken}`,+ },+ });+ const text = await response.text();+ if (!response.ok) {+ throw new HttpError(undefined, {+ status: response.status,+ responseBody: text,+ });+ }+ if (text.length === 0) {+ return JSON.parse('{}');+ }+ try {+ return JSON.parse(text);+ } catch {+ throw new Error(+ `LinkedIn returned a ${response.status} response for ${resource} that is not valid JSON. The body started with: ${text.slice(+ 0,+ MAX_ERROR_BODY_CHARS+ )}`+ );+ }+};++export const readRestliId = (headers: HttpHeaders | undefined): string | null => {+ if (headers === undefined) {+ return null;+ }+ const entry = Object.entries(headers).find(+ ([key]) => key.toLowerCase() === 'x-restli-id'+ );+ const value = entry === undefined ? undefined : entry[1];+ if (typeof value === 'string') {+ return value;+ }+ if (Array.isArray(value) && typeof value[0] === 'string') {+ return value[0];+ }+ return null;+};++export const createLinkedinPost = async ({+ accessToken,+ body,+}: {+ accessToken: string;+ body: Post;+}): Promise<PostCreationResult> => {+ const response = await httpClient.sendRequest({+ method: HttpMethod.POST,+ url: `${linkedinCommon.baseUrl}/rest/posts`,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: accessToken,+ },+ headers: linkedinJsonHeaders(),+ body,+ });+ return {+ success: true,+ post_urn: readRestliId(response.headers),+ };+};++export const publishMemberPost = async ({+ accessToken,+ idToken,+ text,+ visibility,+ imageFile,+ imageUrn,+ link,+ linkTitle,+ linkDescription,+}: {+ accessToken: string;+ idToken: string;+ text: string;+ visibility: string;+ imageFile?: ApFile;+ imageUrn?: string;+ link?: string;+ linkTitle?: string;+ linkDescription?: string;+}): Promise<PostCreationResult> => {+ const shortUrn = getMemberUrn(idToken).substring('urn:li:'.length);+ let image: Image | undefined;+ if (imageFile) {+ image = await linkedinCommon.uploadImage(accessToken, shortUrn, imageFile);+ }+ const body = linkedinCommon.generatePostRequestBody({+ urn: shortUrn,+ text: santizeText(text),+ link,+ linkTitle,+ linkDescription,+ visibility,+ image,+ imageUrn,+ });+ return await createLinkedinPost({ accessToken, body });+};++export const publishOrganizationPost = async ({+ accessToken,+ organizationId,+ text,+ imageFile,+ imageUrn,+ link,+ linkTitle,+ linkDescription,+}: {+ accessToken: string;+ organizationId: string;+ text: string;+ imageFile?: ApFile;+ imageUrn?: string;+ link?: string;+ linkTitle?: string;+ linkDescription?: string;+}): Promise<PostCreationResult> => {+ const shortUrn = `organization:${organizationId}`;+ let image: Image | undefined;+ if (imageFile) {+ image = await linkedinCommon.uploadImage(accessToken, shortUrn, imageFile);+ }+ const body = linkedinCommon.generatePostRequestBody({+ urn: shortUrn,+ text: santizeText(text),+ link,+ linkTitle,+ linkDescription,+ visibility: 'PUBLIC',+ image,+ imageUrn,+ });+ return await createLinkedinPost({ accessToken, body });+};+export interface UgcPost {author: string;lifecycleState: string;@@ -277,3 +512,10 @@ export interface Image {image: string;};}++export interface PostCreationResult {+ success: boolean;+ post_urn: string | null;+}++export const MAX_ERROR_BODY_CHARS = 200;diff --git a/packages/pieces/community/linkedin/src/lib/output-schemas.ts b/packages/pieces/community/linkedin/src/lib/output-schemas.tsindex 244eba07eff..faf3b4c80b0 100644--- a/packages/pieces/community/linkedin/src/lib/output-schemas.ts+++ b/packages/pieces/community/linkedin/src/lib/output-schemas.ts@@ -1,23 +1,190 @@import { OutputSchema } from '@activepieces/pieces-framework';+const postCreationFields: OutputSchema['fields'] = [+ {+ key: 'success',+ label: 'Success',+ format: 'boolean',+ },+ {+ key: 'post_urn',+ label: 'Post URN',+ description:+ 'URN of the created post, used by Update Post Commentary and Delete Post.',+ },+];+export const createShareUpdateActionOutputSchema: OutputSchema = {+ fields: postCreationFields,+};++export const createCompanyUpdateActionOutputSchema: OutputSchema = {+ fields: postCreationFields,+};++export const createMemberPostActionOutputSchema: OutputSchema = {+ fields: postCreationFields,+};++export const getCurrentMemberProfileActionOutputSchema: OutputSchema = {fields: [{- key: 'success',- label: 'Success',- value: 'success',+ key: 'sub',+ label: 'Member ID',+ },+ {+ key: 'member_urn',+ label: 'Member URN',+ description:+ 'Author URN accepted by Create Member Post and Create Image Upload URL.',+ },+ {+ key: 'name',+ label: 'Full Name',+ },+ {+ key: 'given_name',+ label: 'First Name',+ },+ {+ key: 'family_name',+ label: 'Last Name',+ },+ {+ key: 'email',+ label: 'Email',+ format: 'email',+ },+ {+ key: 'email_verified',+ label: 'Email Verified',format: 'boolean',},+ {+ key: 'picture',+ label: 'Profile Picture',+ format: 'image',+ },+ {+ key: 'locale',+ label: 'Locale',+ },],};-export const createCompanyUpdateActionOutputSchema: OutputSchema = {+export const listManagedOrganizationsActionOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'organizations',+ label: 'Organizations',+ labelKey: 'name',+ listItems: [+ {+ key: 'organization_urn',+ label: 'Organization URN',+ },+ {+ key: 'organization_id',+ label: 'Organization ID',+ },+ {+ key: 'name',+ label: 'Name',+ },+ {+ key: 'vanity_name',+ label: 'Vanity Name',+ },+ {+ key: 'website',+ label: 'Website',+ format: 'url',+ },+ {+ key: 'role',+ label: 'Role',+ },+ {+ key: 'state',+ label: 'State',+ },+ ],+ },+ {+ key: 'count',+ label: 'Count',+ format: 'number',+ },+ ],+};++export const updatePostCommentaryActionOutputSchema: OutputSchema = {fields: [{key: 'success',label: 'Success',- value: 'success',format: 'boolean',},+ {+ key: 'post_urn',+ label: 'Post URN',+ },+ {+ key: 'updated_fields',+ label: 'Updated Fields',+ description: 'Comma-separated names of the fields that were changed.',+ },+ {+ key: 'updated_field_count',+ label: 'Updated Field Count',+ format: 'number',+ },+ ],+};++export const createImageUploadUrlActionOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'owner_urn',+ label: 'Owner URN',+ },+ {+ key: 'image_urn',+ label: 'Image URN',+ description:+ 'Pass this as the Image URN of Create Member Post once the bytes are uploaded.',+ },+ {+ key: 'upload_url',+ label: 'Upload URL',+ format: 'url',+ description: 'PUT the raw image bytes here before posting.',+ },+ {+ key: 'upload_url_expires_at',+ label: 'Upload URL Expires At',+ format: 'datetime',+ },+ ],+};++export const deletePostActionOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'deleted',+ label: 'Deleted',+ format: 'boolean',+ },+ {+ key: 'post_urn',+ label: 'Post URN',+ },+ {+ key: 'already_deleted',+ label: 'Already Deleted',+ format: 'boolean',+ description:+ 'True when the post was already gone, so this call changed nothing.',+ },],};diff --git a/packages/pieces/community/twitter/package.json b/packages/pieces/community/twitter/package.jsonindex ac5fd02a9a2..4253f3cd248 100644--- a/packages/pieces/community/twitter/package.json+++ b/packages/pieces/community/twitter/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-twitter",- "version": "0.3.7",+ "version": "0.4.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/twitter/src/index.ts b/packages/pieces/community/twitter/src/index.tsindex d94a94ff562..996169da065 100644--- a/packages/pieces/community/twitter/src/index.ts+++ b/packages/pieces/community/twitter/src/index.ts@@ -7,6 +7,7 @@ import { PieceCategory } from '@activepieces/pieces-framework';import { TwitterApi } from 'twitter-api-v2';import { createTweet } from './lib/actions/create-tweet';import { createReply } from './lib/actions/create-reply';+import { xGetAuthenticatedUser } from './lib/actions/x-get-authenticated-user';const markdownDescription = `If you don't have the credentials down below, please follow these steps to obtain the required credentials:@@ -84,11 +85,11 @@ export const twitterAuth = PieceAuth.CustomAuth({export const twitter = createPiece({displayName: 'Twitter',description: 'Social media platform with over 500 million user',- minimumSupportedRelease: '0.36.1',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/twitter.png',categories: [PieceCategory.COMMUNICATION],authors: ["Abdallah-Alwarawreh","Salem-Alaa","kishanprmr","AbdulTheActivePiecer","khaledmashaly","abuaboud"],auth: twitterAuth,- actions: [createTweet, createReply],+ actions: [createTweet, createReply, xGetAuthenticatedUser],triggers: [],});diff --git a/packages/pieces/community/twitter/src/lib/actions/x-get-authenticated-user.ts b/packages/pieces/community/twitter/src/lib/actions/x-get-authenticated-user.tsnew file mode 100644index 00000000000..8098aefb218--- /dev/null+++ b/packages/pieces/community/twitter/src/lib/actions/x-get-authenticated-user.ts@@ -0,0 +1,42 @@+import { createAction } from '@activepieces/pieces-framework';+import { TwitterApi } from 'twitter-api-v2';+import { twitterAuth } from '../..';+import { twitterFieldSets, twitterHelpers } from '../common';+import { getAuthenticatedUserOutputSchema } from '../output-schemas';++export const xGetAuthenticatedUser = createAction({+ auth: twitterAuth,+ name: 'x_get_authenticated_user',+ classification: 'READ',+ displayName: 'Get Authenticated User',+ description: 'Retrieve the X account the connection belongs to.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Retrieve the profile of the X account this connection authenticates as, including its numeric id, @handle, bio and follower counts. Use it to confirm which X account a connection belongs to, or to read the follower, following and post counts for that account. It only ever returns the connected account and takes no input, so it cannot look up any other user.',+ idempotent: true,+ },+ outputSchema: getAuthenticatedUserOutputSchema,+ props: {},+ async run(context) {+ const { consumerKey, consumerSecret, accessToken, accessTokenSecret } =+ context.auth.props;+ const userClient = new TwitterApi({+ appKey: consumerKey,+ appSecret: consumerSecret,+ accessToken: accessToken,+ accessSecret: accessTokenSecret,+ });++ try {+ return await userClient.v2.me({+ 'user.fields': twitterFieldSets.user,+ });+ } catch (error: unknown) {+ throw twitterHelpers.buildError({+ error: twitterHelpers.asTwitterError(error),+ notFoundHint: 'the authenticated account could not be resolved.',+ });+ }+ },+});diff --git a/packages/pieces/community/twitter/src/lib/common/index.ts b/packages/pieces/community/twitter/src/lib/common/index.tsindex 70547130c1a..bde6fd3f3c9 100644--- a/packages/pieces/community/twitter/src/lib/common/index.ts+++ b/packages/pieces/community/twitter/src/lib/common/index.ts@@ -1,5 +1,57 @@import { Property } from '@activepieces/pieces-framework';+function describeStatus({+ code,+ notFoundHint,+}: {+ code?: number;+ notFoundHint: string;+}): string | undefined {+ if (code === 401) {+ return 'X API 401: the stored credentials were rejected. Reconnect the X connection.';+ }+ if (code === 403) {+ return 'X API 403: the X app permission level does not allow this operation, or the target resource does not belong to the authenticated account.';+ }+ if (code === 404) {+ return `X API 404: ${notFoundHint}`;+ }+ if (code === 429) {+ return 'X API 429: rate limit reached. Wait for the limit window to reset before retrying.';+ }+ return undefined;+}++function asTwitterError(value: unknown): TwitterErrorLike {+ if (typeof value === 'object' && value !== null) {+ return value;+ }+ return { message: String(value) };+}++function buildError({+ error,+ notFoundHint,+}: {+ error: TwitterErrorLike;+ notFoundHint: string;+}): Error {+ const described = describeStatus({ code: error?.code, notFoundHint });+ if (described === undefined && error?.errors === undefined) {+ const cause =+ typeof error?.message === 'string' && error.message.length > 0+ ? error.message+ : String(error);+ return new Error(`X API request failed: ${cause}`);+ }+ return new Error(+ `${described ?? 'X API request failed.'} ${JSON.stringify({+ code: error?.code,+ errors: error?.errors,+ })}`+ );+}+export const twitterCommon = {text: Property.LongText({displayName: 'Text',@@ -24,4 +76,19 @@ export const twitterCommon = {'An image, video or GIF url or base64 to attach to the tweet',required: false,}),- };\ No newline at end of file+ };++export const twitterHelpers = {+ buildError,+ asTwitterError,+};++export const twitterFieldSets = {+ user: 'created_at,description,public_metrics,verified,profile_image_url',+};++export type TwitterErrorLike = {+ code?: number;+ errors?: unknown;+ message?: string;+};diff --git a/packages/pieces/community/twitter/src/lib/output-schemas.ts b/packages/pieces/community/twitter/src/lib/output-schemas.tsnew file mode 100644index 00000000000..8a7a22b94c3--- /dev/null+++ b/packages/pieces/community/twitter/src/lib/output-schemas.ts@@ -0,0 +1,36 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const userPublicMetricsFields: OutputSchema['fields'] = [+ { key: 'followers_count', label: 'Followers', format: 'number' },+ { key: 'following_count', label: 'Following', format: 'number' },+ { key: 'tweet_count', label: 'Posts', format: 'number' },+ { key: 'listed_count', label: 'Listed In', format: 'number' },+ { key: 'like_count', label: 'Likes Given', format: 'number' },+ { key: 'media_count', label: 'Media Posted', format: 'number' },+];++const userFields: OutputSchema['fields'] = [+ { key: 'id', label: 'User ID' },+ { key: 'username', label: 'Username' },+ { key: 'name', label: 'Display Name' },+ { key: 'description', label: 'Bio' },+ { key: 'created_at', label: 'Created At', format: 'datetime' },+ { key: 'profile_image_url', label: 'Profile Image', format: 'image' },+ { key: 'verified', label: 'Verified', format: 'boolean' },+ {+ key: 'public_metrics',+ label: 'Public Metrics',+ children: userPublicMetricsFields,+ },+];++export const getAuthenticatedUserOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'data',+ label: 'Account',+ description: 'The X account this connection authenticates as.',+ children: userFields,+ },+ ],+};diff --git a/packages/pieces/community/youtube/package.json b/packages/pieces/community/youtube/package.jsonindex c71da167011..53ff2599169 100644--- a/packages/pieces/community/youtube/package.json+++ b/packages/pieces/community/youtube/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-youtube",- "version": "0.6.0",+ "version": "0.7.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/youtube/src/i18n/translation.json b/packages/pieces/community/youtube/src/i18n/translation.jsonindex bac93e74890..06c3638e6c9 100644--- a/packages/pieces/community/youtube/src/i18n/translation.json+++ b/packages/pieces/community/youtube/src/i18n/translation.json@@ -154,5 +154,127 @@"New Video In Channel": "New Video In Channel","Runs when a new video is added to a YouTube channel": "Runs when a new video is added to a YouTube channel","Channel ID, URL, or handle": "Channel ID, URL, or handle",- "YouTube channel's ID, URL, or handle (e.g: @DutchPilotGirl)": "YouTube channel's ID, URL, or handle (e.g: @DutchPilotGirl)"-}\ No newline at end of file+ "YouTube channel's ID, URL, or handle (e.g: @DutchPilotGirl)": "YouTube channel's ID, URL, or handle (e.g: @DutchPilotGirl)",+ "Create Playlist": "Create Playlist",+ "Create a new playlist on the authenticated account channel.": "Create a new playlist on the authenticated account channel.",+ "Playlist title, up to 150 characters.": "Playlist title, up to 150 characters.",+ "Description": "Description",+ "Playlist description, up to 5000 characters.": "Playlist description, up to 5000 characters.",+ "Privacy Status": "Privacy Status",+ "Who can see the playlist. Defaults to private.": "Who can see the playlist. Defaults to private.",+ "Private": "Private",+ "Unlisted": "Unlisted",+ "Public": "Public",+ "Default Language": "Default Language",+ "BCP-47 language code of the title and description (for example: en, es, ja).": "BCP-47 language code of the title and description (for example: en, es, ja).",+ "Update Playlist": "Update Playlist",+ "Update the title, description, tags or privacy of an existing playlist.": "Update the title, description, tags or privacy of an existing playlist.",+ "The playlist to update. This is the `list` parameter in a playlist URL (e.g. `PLbpi6ZahtOH6Ar_3GPy3workLYfGa7mGm`).": "The playlist to update. This is the `list` parameter in a playlist URL (e.g. `PLbpi6ZahtOH6Ar_3GPy3workLYfGa7mGm`).",+ "New title. Leave blank to keep the current title.": "New title. Leave blank to keep the current title.",+ "New description. Leave blank to keep the current description.": "New description. Leave blank to keep the current description.",+ "Tags Update Mode": "Tags Update Mode",+ "How to treat the Tags field. Leave Unchanged keeps the existing tags.": "How to treat the Tags field. Leave Unchanged keeps the existing tags.",+ "Leave unchanged": "Leave unchanged",+ "Replace with the tags below": "Replace with the tags below",+ "Clear all tags": "Clear all tags",+ "Tags": "Tags",+ "Tags to set when Tags Update Mode is Replace.": "Tags to set when Tags Update Mode is Replace.",+ "New privacy. Leave Unchanged keeps the current value.": "New privacy. Leave Unchanged keeps the current value.",+ "BCP-47 language code of the title and description. Leave blank to keep the current value.": "BCP-47 language code of the title and description. Leave blank to keep the current value.",+ "Delete Playlist": "Delete Playlist",+ "Permanently delete a playlist owned by the connected account.": "Permanently delete a playlist owned by the connected account.",+ "The playlist to delete. This is the `list` parameter in a playlist URL.": "The playlist to delete. This is the `list` parameter in a playlist URL.",+ "Add Video To Playlist": "Add Video To Playlist",+ "Add a video to a playlist owned by the connected account.": "Add a video to a playlist owned by the connected account.",+ "The playlist to add to. This is the `list` parameter in a playlist URL.": "The playlist to add to. This is the `list` parameter in a playlist URL.",+ "Position": "Position",+ "Zero-based position in the playlist. Leave blank to append to the end.": "Zero-based position in the playlist. Leave blank to append to the end.",+ "Remove Video From Playlist": "Remove Video From Playlist",+ "Remove one entry from a playlist owned by the connected account.": "Remove one entry from a playlist owned by the connected account.",+ "Playlist Item ID": "Playlist Item ID",+ "The playlist item ID (a long opaque string), not the video ID. Obtain it from List Playlist Videos or Add Video To Playlist.": "The playlist item ID (a long opaque string), not the video ID. Obtain it from List Playlist Videos or Add Video To Playlist.",+ "Post Video Comment": "Post Video Comment",+ "Post a new top-level comment on a video.": "Post a new top-level comment on a video.",+ "Comment Text": "Comment Text",+ "The comment body to post.": "The comment body to post.",+ "Reply To Comment": "Reply To Comment",+ "Reply to an existing top-level comment.": "Reply to an existing top-level comment.",+ "Parent Comment ID": "Parent Comment ID",+ "The ID of a top-level comment, from `items[].snippet.topLevelComment.id` in List Comment Threads. Reply IDs are not accepted.": "The ID of a top-level comment, from `items[].snippet.topLevelComment.id` in List Comment Threads. Reply IDs are not accepted.",+ "Reply Text": "Reply Text",+ "The reply body to post.": "The reply body to post.",+ "Delete Comment": "Delete Comment",+ "Permanently delete a comment or reply.": "Permanently delete a comment or reply.",+ "Comment ID": "Comment ID",+ "The comment or reply ID, from List Comment Threads or from Post Video Comment.": "The comment or reply ID, from List Comment Threads or from Post Video Comment.",+ "Set Comment Moderation Status": "Set Comment Moderation Status",+ "Publish, hold for review, or reject comments on the connected account videos.": "Publish, hold for review, or reject comments on the connected account videos.",+ "Comment IDs": "Comment IDs",+ "A comment ID, or a comma-separated list of comment IDs, from List Comment Threads.": "A comment ID, or a comma-separated list of comment IDs, from List Comment Threads.",+ "Moderation Status": "Moderation Status",+ "The status to apply to every listed comment.": "The status to apply to every listed comment.",+ "Published": "Published",+ "Held For Review": "Held For Review",+ "Rejected": "Rejected",+ "Ban Author": "Ban Author",+ "Permanently ban the comment author from the channel. Only valid with the Rejected status and cannot be undone.": "Permanently ban the comment author from the channel. Only valid with the Rejected status and cannot be undone.",+ "No": "No",+ "Yes, ban the author": "Yes, ban the author",+ "Rate Video": "Rate Video",+ "Like, dislike, or remove the rating on a video.": "Like, dislike, or remove the rating on a video.",+ "The rating to apply. None removes any existing rating.": "The rating to apply. None removes any existing rating.",+ "Like": "Like",+ "Dislike": "Dislike",+ "None (remove rating)": "None (remove rating)",+ "Get Video Rating": "Get Video Rating",+ "Read the rating the connected account has given to one or more videos.": "Read the rating the connected account has given to one or more videos.",+ "Video IDs": "Video IDs",+ "A video ID, or a comma-separated list of up to 50 IDs (e.g. `dQw4w9WgXcQ,abc123`).": "A video ID, or a comma-separated list of up to 50 IDs (e.g. `dQw4w9WgXcQ,abc123`).",+ "List Channel Activities": "List Channel Activities",+ "List recent activity events on a channel, such as uploads and playlist additions.": "List recent activity events on a channel, such as uploads and playlist additions.",+ "Channel ID starting with `UC`. Leave blank to list the authenticated account own activity.": "Channel ID starting with `UC`. Leave blank to list the authenticated account own activity.",+ "Only include activities created at or after this datetime (RFC 3339).": "Only include activities created at or after this datetime (RFC 3339).",+ "Only include activities created before this datetime (RFC 3339).": "Only include activities created before this datetime (RFC 3339).",+ "Number of activities to return (0-50, default 25).": "Number of activities to return (0-50, default 25).",+ "List My Subscriptions": "List My Subscriptions",+ "List the channels the connected account is subscribed to.": "List the channels the connected account is subscribed to.",+ "Ordering of the subscriptions.": "Ordering of the subscriptions.",+ "Alphabetical": "Alphabetical",+ "Unread": "Unread",+ "For Channel ID": "For Channel ID",+ "Only return the subscription to this channel, if one exists. Returns an empty list otherwise.": "Only return the subscription to this channel, if one exists. Returns an empty list otherwise.",+ "Number of subscriptions to return (0-50, default 25).": "Number of subscriptions to return (0-50, default 25).",+ "List Trending Videos": "List Trending Videos",+ "List the most popular videos in a region, optionally by category.": "List the most popular videos in a region, optionally by category.",+ "ISO 3166-1 alpha-2 country code (for example: US, DE, JP). Defaults to US.": "ISO 3166-1 alpha-2 country code (for example: US, DE, JP). Defaults to US.",+ "Video Category ID": "Video Category ID",+ "Restrict the chart to one video category ID (for example: 10 for Music). Leave blank for all categories.": "Restrict the chart to one video category ID (for example: 10 for Music). Leave blank for all categories.",+ "Number of videos to return (1-50, default 25).": "Number of videos to return (1-50, default 25).",+ "List Channel Videos": "List Channel Videos",+ "List the videos uploaded by a channel, resolved from its uploads playlist.": "List the videos uploaded by a channel, resolved from its uploads playlist.",+ "Channel ID or Handle": "Channel ID or Handle",+ "A channel ID starting with `UC`, or a handle such as `@GoogleDevelopers`.": "A channel ID starting with `UC`, or a handle such as `@GoogleDevelopers`.",+ "Number of videos to return (0-50, default 25).": "Number of videos to return (0-50, default 25).",+ "Update Video Metadata": "Update Video Metadata",+ "Update the title, description, tags, category or status of a video you own.": "Update the title, description, tags, category or status of a video you own.",+ "Category ID": "Category ID",+ "New video category ID (for example: 10 for Music). Leave blank to keep the current category.": "New video category ID (for example: 10 for Music). Leave blank to keep the current category.",+ "License": "License",+ "New license. Leave Unchanged keeps the current value.": "New license. Leave Unchanged keeps the current value.",+ "Standard YouTube License": "Standard YouTube License",+ "Embeddable": "Embeddable",+ "Whether the video can be embedded on other sites. Leave Unchanged keeps the current value.": "Whether the video can be embedded on other sites. Leave Unchanged keeps the current value.",+ "Yes": "Yes",+ "Public Stats Viewable": "Public Stats Viewable",+ "Whether the video statistics are publicly visible. Leave Unchanged keeps the current value.": "Whether the video statistics are publicly visible. Leave Unchanged keeps the current value.",+ "Made For Kids": "Made For Kids",+ "Self-declaration that the video is made for kids. Leave Unchanged keeps the current value.": "Self-declaration that the video is made for kids. Leave Unchanged keeps the current value.",+ "Search YouTube": "Search YouTube",+ "Get Video Details": "Get Video Details",+ "Get Channel Details": "Get Channel Details",+ "List Channel Playlists": "List Channel Playlists",+ "List Playlist Videos": "List Playlist Videos",+ "List Comment Threads": "List Comment Threads",+ "List Caption Tracks": "List Caption Tracks",+ "Download Caption Track": "Download Caption Track"+}diff --git a/packages/pieces/community/youtube/src/index.ts b/packages/pieces/community/youtube/src/index.tsindex 4a5b684f376..e58282427cc 100644--- a/packages/pieces/community/youtube/src/index.ts+++ b/packages/pieces/community/youtube/src/index.ts@@ -14,12 +14,36 @@ import { youtubeGetVideoAction } from './lib/actions/get-video';import { youtubeGetChannelAction } from './lib/actions/get-channel';import { youtubeListPlaylistsAction } from './lib/actions/list-playlists';import { youtubeListCommentsAction } from './lib/actions/list-comments';+import { youtubeCreatePlaylistAction } from './lib/actions/create-playlist';+import { youtubeUpdatePlaylistAction } from './lib/actions/update-playlist';+import { youtubeDeletePlaylistAction } from './lib/actions/delete-playlist';+import { youtubeAddVideoToPlaylistAction } from './lib/actions/add-video-to-playlist';+import { youtubeRemoveVideoFromPlaylistAction } from './lib/actions/remove-video-from-playlist';+import { youtubePostVideoCommentAction } from './lib/actions/post-video-comment';+import { youtubeReplyToCommentAction } from './lib/actions/reply-to-comment';+import { youtubeDeleteCommentAction } from './lib/actions/delete-comment';+import { youtubeSetCommentModerationStatusAction } from './lib/actions/set-comment-moderation-status';+import { youtubeRateVideoAction } from './lib/actions/rate-video';+import { youtubeGetVideoRatingAction } from './lib/actions/get-video-rating';+import { youtubeListChannelActivitiesAction } from './lib/actions/list-channel-activities';+import { youtubeListMySubscriptionsAction } from './lib/actions/list-my-subscriptions';+import { youtubeListTrendingVideosAction } from './lib/actions/list-trending-videos';+import { youtubeListChannelVideosAction } from './lib/actions/list-channel-videos';+import { youtubeUpdateVideoMetadataAction } from './lib/actions/update-video-metadata';+import { youtubeSearchYoutubeAction } from './lib/actions/search-youtube';+import { youtubeGetVideoDetailsAction } from './lib/actions/get-video-details';+import { youtubeGetChannelDetailsAction } from './lib/actions/get-channel-details';+import { youtubeListChannelPlaylistsAction } from './lib/actions/list-channel-playlists';+import { youtubeListPlaylistVideosAction } from './lib/actions/list-playlist-videos';+import { youtubeListCommentThreadsAction } from './lib/actions/list-comment-threads';+import { youtubeListCaptionTracksAction } from './lib/actions/list-caption-tracks';+import { youtubeDownloadCaptionTrackAction } from './lib/actions/download-caption-track';export const youtube = createPiece({displayName: 'YouTube',description:'Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube',- minimumSupportedRelease: '0.33.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/youtube.png',categories: [PieceCategory.CONTENT_AND_FILES],auth: youtubeAuth,@@ -40,6 +64,30 @@ export const youtube = createPiece({youtubeGetChannelAction,youtubeListPlaylistsAction,youtubeListCommentsAction,+ youtubeCreatePlaylistAction,+ youtubeUpdatePlaylistAction,+ youtubeDeletePlaylistAction,+ youtubeAddVideoToPlaylistAction,+ youtubeRemoveVideoFromPlaylistAction,+ youtubePostVideoCommentAction,+ youtubeReplyToCommentAction,+ youtubeDeleteCommentAction,+ youtubeSetCommentModerationStatusAction,+ youtubeRateVideoAction,+ youtubeGetVideoRatingAction,+ youtubeListChannelActivitiesAction,+ youtubeListMySubscriptionsAction,+ youtubeListTrendingVideosAction,+ youtubeListChannelVideosAction,+ youtubeUpdateVideoMetadataAction,+ youtubeSearchYoutubeAction,+ youtubeGetVideoDetailsAction,+ youtubeGetChannelDetailsAction,+ youtubeListChannelPlaylistsAction,+ youtubeListPlaylistVideosAction,+ youtubeListCommentThreadsAction,+ youtubeListCaptionTracksAction,+ youtubeDownloadCaptionTrackAction,createCustomApiCallAction({baseUrl: () => 'https://www.googleapis.com/youtube/v3',auth: youtubeAuth,diff --git a/packages/pieces/community/youtube/src/lib/actions/add-video-to-playlist.ts b/packages/pieces/community/youtube/src/lib/actions/add-video-to-playlist.tsnew file mode 100644index 00000000000..bc03635d1a3--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/add-video-to-playlist.ts@@ -0,0 +1,71 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { addVideoToPlaylistOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeAddVideoToPlaylistAction = createAction({+ auth: youtubeAuth,+ outputSchema: addVideoToPlaylistOutputSchema,+ name: 'add_video_to_playlist',+ classification: 'WRITE',+ displayName: 'Add Video To Playlist',+ description: 'Add a video to a playlist owned by the connected account.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Adds one video to a playlist owned by the authenticated channel via playlistItems.insert and returns the new playlist item, whose ID is what Remove Video From Playlist needs. Use Create Playlist first when the playlist does not exist yet. YouTube allows the same video more than once, so retries add duplicate entries.',+ idempotent: false,+ },+ props: {+ playlistId: Property.ShortText({+ displayName: 'Playlist ID',+ description:+ 'The playlist to add to. This is the `list` parameter in a playlist URL.',+ required: true,+ }),+ videoId: Property.ShortText({+ displayName: 'Video ID',+ description: 'The `v` parameter in a YouTube URL (e.g. `dQw4w9WgXcQ`).',+ required: true,+ }),+ position: Property.Number({+ displayName: 'Position',+ description:+ 'Zero-based position in the playlist. Leave blank to append to the end.',+ required: false,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { playlistId, videoId, position } = context.propsValue;++ const snippet: PlaylistItemSnippetPayload = {+ playlistId,+ resourceId: { kind: 'youtube#video', videoId },+ };++ if (position !== undefined && position !== null) {+ const positionNumber = Math.trunc(Number(position));+ if (!Number.isFinite(positionNumber) || positionNumber < 0) {+ throw new Error('Position must be zero or greater.');+ }+ snippet.position = positionNumber;+ }++ return youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.POST,+ path: '/playlistItems',+ operation: 'Add Video To Playlist',+ queryParams: { part: 'snippet' },+ body: { snippet },+ });+ },+});++type PlaylistItemSnippetPayload = {+ playlistId: string;+ resourceId: { kind: string; videoId: string };+ position?: number;+};diff --git a/packages/pieces/community/youtube/src/lib/actions/create-playlist.ts b/packages/pieces/community/youtube/src/lib/actions/create-playlist.tsnew file mode 100644index 00000000000..2108ada3a9c--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/create-playlist.ts@@ -0,0 +1,76 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { createPlaylistOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeCreatePlaylistAction = createAction({+ auth: youtubeAuth,+ outputSchema: createPlaylistOutputSchema,+ name: 'create_playlist',+ classification: 'WRITE',+ displayName: 'Create Playlist',+ description: 'Create a new playlist on the authenticated account channel.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a playlist on the authenticated YouTube channel via playlists.insert and returns its new playlist ID. Use it before Add Video To Playlist; use Update Playlist to change an existing one instead. Every call creates another playlist, so retries duplicate it.',+ idempotent: false,+ },+ props: {+ title: Property.ShortText({+ displayName: 'Title',+ description: 'Playlist title, up to 150 characters.',+ required: true,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'Playlist description, up to 5000 characters.',+ required: false,+ }),+ privacyStatus: Property.StaticDropdown({+ displayName: 'Privacy Status',+ description: 'Who can see the playlist. Defaults to private.',+ required: false,+ defaultValue: 'private',+ options: {+ options: [+ { label: 'Private', value: 'private' },+ { label: 'Unlisted', value: 'unlisted' },+ { label: 'Public', value: 'public' },+ ],+ },+ }),+ defaultLanguage: Property.ShortText({+ displayName: 'Default Language',+ description:+ 'BCP-47 language code of the title and description (for example: en, es, ja).',+ required: false,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { title, description, privacyStatus, defaultLanguage } =+ context.propsValue;++ const snippet: Record<string, string> = { title };+ if (description) {+ snippet['description'] = description;+ }+ if (defaultLanguage) {+ snippet['defaultLanguage'] = defaultLanguage;+ }++ return youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.POST,+ path: '/playlists',+ operation: 'Create Playlist',+ queryParams: { part: 'snippet,status' },+ body: {+ snippet,+ status: { privacyStatus: privacyStatus ?? 'private' },+ },+ });+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/delete-comment.ts b/packages/pieces/community/youtube/src/lib/actions/delete-comment.tsnew file mode 100644index 00000000000..1f44addbfb9--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/delete-comment.ts@@ -0,0 +1,42 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { deleteCommentOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeDeleteCommentAction = createAction({+ auth: youtubeAuth,+ outputSchema: deleteCommentOutputSchema,+ name: 'delete_comment',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Comment',+ description: 'Permanently delete a comment or reply.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a YouTube comment or reply via comments.delete. Use Set Comment Moderation Status to hold or reject a comment recoverably instead of destroying it. Only comments the authenticated account authored, or comments on its own videos, can be deleted, and a repeated call fails because the comment is gone.',+ idempotent: false,+ },+ props: {+ commentId: Property.ShortText({+ displayName: 'Comment ID',+ description:+ 'The comment or reply ID, from List Comment Threads or from Post Video Comment.',+ required: true,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { commentId } = context.propsValue;++ await youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.DELETE,+ path: '/comments',+ operation: 'Delete Comment',+ queryParams: { id: commentId },+ });++ return { success: true, commentId };+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/delete-playlist.ts b/packages/pieces/community/youtube/src/lib/actions/delete-playlist.tsnew file mode 100644index 00000000000..cf323897f30--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/delete-playlist.ts@@ -0,0 +1,42 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { deletePlaylistOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeDeletePlaylistAction = createAction({+ auth: youtubeAuth,+ outputSchema: deletePlaylistOutputSchema,+ name: 'delete_playlist',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Playlist',+ description: 'Permanently delete a playlist owned by the connected account.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a playlist owned by the authenticated channel via playlists.delete. Use Remove Video From Playlist when only one entry should go; this removes the whole playlist and cannot be undone. A repeated call fails because the playlist no longer exists.',+ idempotent: false,+ },+ props: {+ playlistId: Property.ShortText({+ displayName: 'Playlist ID',+ description:+ 'The playlist to delete. This is the `list` parameter in a playlist URL.',+ required: true,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { playlistId } = context.propsValue;++ await youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.DELETE,+ path: '/playlists',+ operation: 'Delete Playlist',+ queryParams: { id: playlistId },+ });++ return { success: true, playlistId };+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/download-caption-track.ts b/packages/pieces/community/youtube/src/lib/actions/download-caption-track.tsnew file mode 100644index 00000000000..1dfb88bdd97--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/download-caption-track.ts@@ -0,0 +1,24 @@+import { createAction } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { downloadCaptionTrackOutputSchema } from '../output-schemas';+import { youtubeDownloadCaptionAction } from './download-caption';++export const youtubeDownloadCaptionTrackAction = createAction({+ auth: youtubeAuth,+ outputSchema: downloadCaptionTrackOutputSchema,+ name: 'download_caption_track',+ classification: 'READ',+ displayName: 'Download Caption Track',+ description:+ 'Returns a caption track text by caption ID using the YouTube captions.download endpoint. Requires permission to edit the video, so it only works for captions on videos the authenticated user owns. Auto-generated (asr) caption tracks cannot be downloaded and will return a 403.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Downloads the raw text of one caption track by caption ID, optionally as SRT, VTT, SBV, SCC or TTML and machine-translated into a target language. Use it after List Caption Tracks supplies the caption ID. It only serves tracks on videos the connected account can edit, and auto-generated (asr) tracks are refused with a 403. Read-only and idempotent.',+ idempotent: true,+ },+ props: youtubeDownloadCaptionAction.props,+ run: async (context) => ({+ caption: await youtubeDownloadCaptionAction.run(context),+ }),+});diff --git a/packages/pieces/community/youtube/src/lib/actions/download-caption.ts b/packages/pieces/community/youtube/src/lib/actions/download-caption.tsindex 50f953a1a96..da289530fe7 100644--- a/packages/pieces/community/youtube/src/lib/actions/download-caption.ts+++ b/packages/pieces/community/youtube/src/lib/actions/download-caption.ts@@ -12,7 +12,7 @@ export const youtubeDownloadCaptionAction = createAction({displayName: 'Download Caption',description:'Returns a caption track text by caption ID using the YouTube captions.download endpoint. Requires permission to edit the video, so it only works for captions on videos the authenticated user owns. Auto-generated (asr) caption tracks cannot be downloaded and will return a 403.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Downloads the raw text of one YouTube caption track identified by its caption ID, optionally emitting it as SRT, VTT, SBV, SCC, or TTML and machine-translating it into a target language code. Use it after List Captions has supplied the caption ID; the endpoint only serves tracks on videos the authenticated account can edit, and auto-generated (asr) tracks are refused with a 403. Read-only and idempotent.', idempotent: true },props: {captionId: Property.ShortText({diff --git a/packages/pieces/community/youtube/src/lib/actions/get-channel-details.ts b/packages/pieces/community/youtube/src/lib/actions/get-channel-details.tsnew file mode 100644index 00000000000..d4d27d505df--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/get-channel-details.ts@@ -0,0 +1,22 @@+import { createAction } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { getChannelOutputSchema } from '../output-schemas';+import { youtubeGetChannelAction } from './get-channel';++export const youtubeGetChannelDetailsAction = createAction({+ auth: youtubeAuth,+ outputSchema: getChannelOutputSchema,+ name: 'get_channel_details',+ classification: 'READ',+ displayName: 'Get Channel Details',+ description:+ 'Retrieve a channel by ID or handle, including its subscriber and view counts.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Fetches a YouTube channel by channel ID or @handle, returning title, description, country, subscriber count, view count and video count. Use it to resolve a channel reference into statistics or an ID; use List Channel Videos when the goal is that channel uploads. Read-only and idempotent.',+ idempotent: true,+ },+ props: youtubeGetChannelAction.props,+ run: youtubeGetChannelAction.run,+});diff --git a/packages/pieces/community/youtube/src/lib/actions/get-channel.ts b/packages/pieces/community/youtube/src/lib/actions/get-channel.tsindex 5b0962b4959..ca2e73b4816 100644--- a/packages/pieces/community/youtube/src/lib/actions/get-channel.ts+++ b/packages/pieces/community/youtube/src/lib/actions/get-channel.ts@@ -10,7 +10,7 @@ export const youtubeGetChannelAction = createAction({classification: 'READ',displayName: 'Get Channel',description: 'Retrieve a channel by ID or handle, including its subscriber and view counts.',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Fetches a YouTube channel using channels.list, by channel ID or by @handle, returning title, description, country, subscriber count, view count and video count. Use it to resolve a channel reference into its statistics or its uploads playlist ID. Read-only and idempotent.',diff --git a/packages/pieces/community/youtube/src/lib/actions/get-video-details.ts b/packages/pieces/community/youtube/src/lib/actions/get-video-details.tsnew file mode 100644index 00000000000..cb91eb25b29--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/get-video-details.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { getVideoOutputSchema } from '../output-schemas';+import { youtubeGetVideoAction } from './get-video';++export const youtubeGetVideoDetailsAction = createAction({+ auth: youtubeAuth,+ outputSchema: getVideoOutputSchema,+ name: 'get_video_details',+ classification: 'READ',+ displayName: 'Get Video Details',+ description: 'Retrieve a video by ID, including its statistics and duration.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Fetches full details for one or more YouTube videos by ID, including title, description, tags, duration, view and like counts, and privacy status. Use it after Search YouTube, List Channel Videos or List Trending Videos hand you a video ID but not its details; use Get Video Rating for the connected account own rating. Up to 50 comma-separated IDs per call. Read-only and idempotent.',+ idempotent: true,+ },+ props: youtubeGetVideoAction.props,+ run: youtubeGetVideoAction.run,+});diff --git a/packages/pieces/community/youtube/src/lib/actions/get-video-rating.ts b/packages/pieces/community/youtube/src/lib/actions/get-video-rating.tsnew file mode 100644index 00000000000..3ae4f941cfb--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/get-video-rating.ts@@ -0,0 +1,41 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { getVideoRatingOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeGetVideoRatingAction = createAction({+ auth: youtubeAuth,+ outputSchema: getVideoRatingOutputSchema,+ name: 'get_video_rating',+ classification: 'READ',+ displayName: 'Get Video Rating',+ description:+ 'Read the rating the connected account has given to one or more videos.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Reads the authenticated account own rating (like, dislike, none, or unspecified) for up to 50 videos via videos.getRating. Use it before Rate Video to avoid re-applying a rating the account already gave. It reports only the connected account rating, never the public like count, which Get Video Details returns. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ videoIds: Property.ShortText({+ displayName: 'Video IDs',+ description:+ 'A video ID, or a comma-separated list of up to 50 IDs (e.g. `dQw4w9WgXcQ,abc123`).',+ required: true,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { videoIds } = context.propsValue;++ return youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.GET,+ path: '/videos/getRating',+ operation: 'Get Video Rating',+ queryParams: { id: videoIds },+ });+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/get-video.ts b/packages/pieces/community/youtube/src/lib/actions/get-video.tsindex 7af6687c7ad..098a0f546db 100644--- a/packages/pieces/community/youtube/src/lib/actions/get-video.ts+++ b/packages/pieces/community/youtube/src/lib/actions/get-video.ts@@ -10,7 +10,7 @@ export const youtubeGetVideoAction = createAction({classification: 'READ',displayName: 'Get Video',description: 'Retrieve a video by ID, including its statistics and duration.',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Fetches full details for one or more YouTube videos by ID using videos.list, returning title, description, tags, duration, view and like counts, and privacy status. Use it after Search or New Video, which give you a video ID but none of these details. Read-only and idempotent.',diff --git a/packages/pieces/community/youtube/src/lib/actions/list-caption-tracks.ts b/packages/pieces/community/youtube/src/lib/actions/list-caption-tracks.tsnew file mode 100644index 00000000000..46a588c6f4d--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/list-caption-tracks.ts@@ -0,0 +1,22 @@+import { createAction } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { listCaptionsOutputSchema } from '../output-schemas';+import { youtubeListCaptionsAction } from './list-captions';++export const youtubeListCaptionTracksAction = createAction({+ auth: youtubeAuth,+ outputSchema: listCaptionsOutputSchema,+ name: 'list_caption_tracks',+ classification: 'SEARCH',+ displayName: 'List Caption Tracks',+ description:+ 'Returns caption tracks for a specific YouTube video using the captions.list endpoint.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the caption tracks attached to a single YouTube video and supplies the caption ID that Download Caption Track requires. Use it to find which languages a video is captioned in. The video ID is mandatory and this call is unusually expensive in YouTube quota, so avoid repeating it. Read-only and idempotent.',+ idempotent: true,+ },+ props: youtubeListCaptionsAction.props,+ run: youtubeListCaptionsAction.run,+});diff --git a/packages/pieces/community/youtube/src/lib/actions/list-captions.ts b/packages/pieces/community/youtube/src/lib/actions/list-captions.tsindex 651be2ebdbe..d91d456e5e0 100644--- a/packages/pieces/community/youtube/src/lib/actions/list-captions.ts+++ b/packages/pieces/community/youtube/src/lib/actions/list-captions.ts@@ -15,7 +15,7 @@ export const youtubeListCaptionsAction = createAction({displayName: 'List Captions',description:'Returns caption tracks for a specific YouTube video using the captions.list endpoint.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Lists the caption tracks attached to a single YouTube video, covering every track on that video or only the ones named by a comma-separated list of caption IDs. Use it to discover which languages a video is captioned in and to obtain the caption ID that the Download Caption action requires. The video ID is mandatory. Read-only and idempotent.', idempotent: true },props: {videoId: Property.ShortText({diff --git a/packages/pieces/community/youtube/src/lib/actions/list-channel-activities.ts b/packages/pieces/community/youtube/src/lib/actions/list-channel-activities.tsnew file mode 100644index 00000000000..836acd0b090--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/list-channel-activities.ts@@ -0,0 +1,110 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { listChannelActivitiesOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeListChannelActivitiesAction = createAction({+ auth: youtubeAuth,+ outputSchema: listChannelActivitiesOutputSchema,+ name: 'list_channel_activities',+ classification: 'SEARCH',+ displayName: 'List Channel Activities',+ description:+ 'List recent activity events on a channel, such as uploads and playlist additions.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists recent activity events (uploads, playlist additions and similar) for a channel via activities.list, optionally bounded by a published date range. Use List Channel Videos when only uploads are wanted; this returns the mixed activity feed. Provide a channel ID, or leave it blank to read the authenticated account own activity. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ channelId: Property.ShortText({+ displayName: 'Channel ID',+ description:+ 'Channel ID starting with `UC`. Leave blank to list the authenticated account own activity.',+ required: false,+ }),+ publishedAfter: Property.DateTime({+ displayName: 'Published After',+ description:+ 'Only include activities created at or after this datetime (RFC 3339).',+ required: false,+ }),+ publishedBefore: Property.DateTime({+ displayName: 'Published Before',+ description:+ 'Only include activities created before this datetime (RFC 3339).',+ required: false,+ }),+ regionCode: Property.ShortText({+ displayName: 'Region Code',+ description: 'ISO 3166-1 alpha-2 country code (for example: US, DE, JP).',+ required: false,+ }),+ maxResults: Property.Number({+ displayName: 'Max Results',+ description: 'Number of activities to return (0-50, default 25).',+ required: false,+ defaultValue: 25,+ }),+ pageToken: Property.ShortText({+ displayName: 'Page Token',+ description: 'Token from a previous response, to fetch the next page.',+ required: false,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const {+ channelId,+ publishedAfter,+ publishedBefore,+ regionCode,+ maxResults,+ pageToken,+ } = context.propsValue;++ if (maxResults !== undefined && maxResults !== null) {+ const maxResultsNumber = Math.trunc(Number(maxResults));+ if (+ !Number.isFinite(maxResultsNumber) ||+ maxResultsNumber < 0 ||+ maxResultsNumber > 50+ ) {+ throw new Error('Max Results must be between 0 and 50.');+ }+ }++ const queryParams: Record<string, string> = {+ part: 'snippet,contentDetails',+ maxResults: String(Math.trunc(Number(maxResults ?? 25))),+ };++ if (channelId) {+ queryParams['channelId'] = channelId;+ } else {+ queryParams['mine'] = 'true';+ }+ if (publishedAfter) {+ queryParams['publishedAfter'] = publishedAfter;+ }+ if (publishedBefore) {+ queryParams['publishedBefore'] = publishedBefore;+ }+ if (regionCode) {+ queryParams['regionCode'] = regionCode;+ }+ if (pageToken) {+ queryParams['pageToken'] = pageToken;+ }++ return youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.GET,+ path: '/activities',+ operation: 'List Channel Activities',+ queryParams,+ });+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/list-channel-playlists.ts b/packages/pieces/community/youtube/src/lib/actions/list-channel-playlists.tsnew file mode 100644index 00000000000..e17b8dfd736--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/list-channel-playlists.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { listPlaylistsOutputSchema } from '../output-schemas';+import { youtubeListPlaylistsAction } from './list-playlists';++export const youtubeListChannelPlaylistsAction = createAction({+ auth: youtubeAuth,+ outputSchema: listPlaylistsOutputSchema,+ name: 'list_channel_playlists',+ classification: 'SEARCH',+ displayName: 'List Channel Playlists',+ description: 'List the playlists on a channel.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the playlists belonging to a YouTube channel, returning each playlist title, description, item count and privacy status. Use it to discover a playlist ID before List Playlist Videos, Add Video To Playlist or Update Playlist. A channel ID starting with UC is required; resolve a handle with Get Channel Details first. Read-only and idempotent.',+ idempotent: true,+ },+ props: youtubeListPlaylistsAction.props,+ run: youtubeListPlaylistsAction.run,+});diff --git a/packages/pieces/community/youtube/src/lib/actions/list-channel-videos.ts b/packages/pieces/community/youtube/src/lib/actions/list-channel-videos.tsnew file mode 100644index 00000000000..f46e2593815--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/list-channel-videos.ts@@ -0,0 +1,128 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { listChannelVideosOutputSchema } from '../output-schemas';+import { YoutubeApiError, youtubeClient } from '../common/client';++export const youtubeListChannelVideosAction = createAction({+ auth: youtubeAuth,+ outputSchema: listChannelVideosOutputSchema,+ name: 'list_channel_videos',+ classification: 'SEARCH',+ displayName: 'List Channel Videos',+ description:+ 'List the videos uploaded by a channel, resolved from its uploads playlist.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists a channel uploads by resolving the channel to its uploads playlist and paging through it, accepting either a channel ID starting with UC or an @handle. Prefer it over Search YouTube for "what has this channel posted", which is far cheaper in quota and not capped at 500 results. A channel with no uploads returns an empty item list. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ channel: Property.ShortText({+ displayName: 'Channel ID or Handle',+ description:+ 'A channel ID starting with `UC`, or a handle such as `@GoogleDevelopers`.',+ required: true,+ }),+ maxResults: Property.Number({+ displayName: 'Max Results',+ description: 'Number of videos to return (0-50, default 25).',+ required: false,+ defaultValue: 25,+ }),+ pageToken: Property.ShortText({+ displayName: 'Page Token',+ description: 'Token from a previous response, to fetch the next page.',+ required: false,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { channel, maxResults, pageToken } = context.propsValue;++ if (maxResults !== undefined && maxResults !== null) {+ const maxResultsNumber = Math.trunc(Number(maxResults));+ if (+ !Number.isFinite(maxResultsNumber) ||+ maxResultsNumber < 0 ||+ maxResultsNumber > 50+ ) {+ throw new Error('Max Results must be between 0 and 50.');+ }+ }++ const channelQueryParams: Record<string, string> = {+ part: 'contentDetails',+ };+ if (channel.startsWith('UC')) {+ channelQueryParams['id'] = channel;+ } else {+ channelQueryParams['forHandle'] = channel.startsWith('@')+ ? channel+ : `@${channel}`;+ }++ const channelResponse = await youtubeClient.sendRequest<ChannelListResponse>(+ {+ accessToken,+ method: HttpMethod.GET,+ path: '/channels',+ operation: 'List Channel Videos (resolving the channel)',+ queryParams: channelQueryParams,+ }+ );++ const resolvedChannel = channelResponse.items?.[0];+ if (!resolvedChannel) {+ throw new Error(+ `No YouTube channel matched "${channel}". Provide a channel ID starting with "UC" or a handle such as "@GoogleDevelopers".`+ );+ }++ const uploadsPlaylistId =+ resolvedChannel.contentDetails?.relatedPlaylists?.uploads;+ if (!uploadsPlaylistId) {+ return {+ kind: 'youtube#playlistItemListResponse',+ items: [],+ pageInfo: { totalResults: 0, resultsPerPage: 0 },+ };+ }++ const playlistQueryParams: Record<string, string> = {+ part: 'snippet,contentDetails,status',+ playlistId: uploadsPlaylistId,+ maxResults: String(Math.trunc(Number(maxResults ?? 25))),+ };+ if (pageToken) {+ playlistQueryParams['pageToken'] = pageToken;+ }++ try {+ return await youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.GET,+ path: '/playlistItems',+ operation: 'List Channel Videos (reading the uploads playlist)',+ queryParams: playlistQueryParams,+ });+ } catch (error) {+ if (error instanceof YoutubeApiError && error.status === 404) {+ throw new Error(+ `Channel "${resolvedChannel.id}" reports uploads playlist "${uploadsPlaylistId}", but YouTube cannot read it. This happens on some brand accounts and on channels whose uploads are not publicly listed. Use Search YouTube with this channel ID if you accept its higher quota cost and 500-result cap.`+ );+ }+ throw error;+ }+ },+});++type ChannelListResponse = {+ items?: {+ id: string;+ contentDetails?: {+ relatedPlaylists?: { uploads?: string };+ };+ }[];+};diff --git a/packages/pieces/community/youtube/src/lib/actions/list-comment-threads.ts b/packages/pieces/community/youtube/src/lib/actions/list-comment-threads.tsnew file mode 100644index 00000000000..22fd9ccd2e7--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/list-comment-threads.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { listCommentsOutputSchema } from '../output-schemas';+import { youtubeListCommentsAction } from './list-comments';++export const youtubeListCommentThreadsAction = createAction({+ auth: youtubeAuth,+ outputSchema: listCommentsOutputSchema,+ name: 'list_comment_threads',+ classification: 'SEARCH',+ displayName: 'List Comment Threads',+ description: 'List the top-level comment threads on a video.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists top-level comment threads on a YouTube video with each comment author, text, like count and reply count, and is the source of the comment IDs that Reply To Comment, Delete Comment and Set Comment Moderation Status need. Comments must be enabled on the video, otherwise YouTube answers 403. Read-only and idempotent.',+ idempotent: true,+ },+ props: youtubeListCommentsAction.props,+ run: youtubeListCommentsAction.run,+});diff --git a/packages/pieces/community/youtube/src/lib/actions/list-comments.ts b/packages/pieces/community/youtube/src/lib/actions/list-comments.tsindex 211f615f949..713e6220017 100644--- a/packages/pieces/community/youtube/src/lib/actions/list-comments.ts+++ b/packages/pieces/community/youtube/src/lib/actions/list-comments.ts@@ -10,7 +10,7 @@ export const youtubeListCommentsAction = createAction({classification: 'SEARCH',displayName: 'List Comments',description: 'List the top-level comment threads on a video.',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Lists comment threads on a YouTube video using commentThreads.list, returning each top-level comment with its author, text, like count and reply count. Use it to read audience feedback on a video for triage, sentiment or moderation flows. Comments must be enabled on the video, otherwise YouTube answers 403. Read-only and idempotent.',diff --git a/packages/pieces/community/youtube/src/lib/actions/list-my-subscriptions.ts b/packages/pieces/community/youtube/src/lib/actions/list-my-subscriptions.tsnew file mode 100644index 00000000000..de0851f0448--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/list-my-subscriptions.ts@@ -0,0 +1,90 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { listSubscriptionsOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeListMySubscriptionsAction = createAction({+ auth: youtubeAuth,+ outputSchema: listSubscriptionsOutputSchema,+ name: 'list_my_subscriptions',+ classification: 'SEARCH',+ displayName: 'List My Subscriptions',+ description: 'List the channels the connected account is subscribed to.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the channels the authenticated account subscribes to via subscriptions.list, returning each subscribed channel title and ID. Use it to answer "who do I follow" or to feed channel IDs into List Channel Videos. Set For Channel ID to check whether one specific channel is subscribed. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ order: Property.StaticDropdown({+ displayName: 'Order',+ description: 'Ordering of the subscriptions.',+ required: false,+ options: {+ options: [+ { label: 'Alphabetical', value: 'alphabetical' },+ { label: 'Relevance', value: 'relevance' },+ { label: 'Unread', value: 'unread' },+ ],+ },+ }),+ forChannelId: Property.ShortText({+ displayName: 'For Channel ID',+ description:+ 'Only return the subscription to this channel, if one exists. Returns an empty list otherwise.',+ required: false,+ }),+ maxResults: Property.Number({+ displayName: 'Max Results',+ description: 'Number of subscriptions to return (0-50, default 25).',+ required: false,+ defaultValue: 25,+ }),+ pageToken: Property.ShortText({+ displayName: 'Page Token',+ description: 'Token from a previous response, to fetch the next page.',+ required: false,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { order, forChannelId, maxResults, pageToken } = context.propsValue;++ if (maxResults !== undefined && maxResults !== null) {+ const maxResultsNumber = Math.trunc(Number(maxResults));+ if (+ !Number.isFinite(maxResultsNumber) ||+ maxResultsNumber < 0 ||+ maxResultsNumber > 50+ ) {+ throw new Error('Max Results must be between 0 and 50.');+ }+ }++ const queryParams: Record<string, string> = {+ part: 'snippet,contentDetails',+ mine: 'true',+ maxResults: String(Math.trunc(Number(maxResults ?? 25))),+ };++ if (order) {+ queryParams['order'] = order;+ }+ if (forChannelId) {+ queryParams['forChannelId'] = forChannelId;+ }+ if (pageToken) {+ queryParams['pageToken'] = pageToken;+ }++ return youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.GET,+ path: '/subscriptions',+ operation: 'List My Subscriptions',+ queryParams,+ });+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/list-playlist-items.ts b/packages/pieces/community/youtube/src/lib/actions/list-playlist-items.tsindex 009db16c36e..0c8c18d9ec4 100644--- a/packages/pieces/community/youtube/src/lib/actions/list-playlist-items.ts+++ b/packages/pieces/community/youtube/src/lib/actions/list-playlist-items.ts@@ -12,7 +12,7 @@ export const youtubeListPlaylistItemsAction = createAction({displayName: 'List Playlist Items',description:'Returns videos in a YouTube playlist. You can filter by playlist ID or by specific item IDs.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Lists the entries of a YouTube playlist in one of two modes: pass a playlist ID to page through that whole playlist (optionally narrowed to entries containing one video ID), or pass a comma-separated list of playlist item IDs to fetch only those entries. Exactly one of the two is required, supplying both or filtering by video without a playlist ID fails validation, and Max Results is capped at 50 with further pages fetched via the page token. Run Search with type Playlist first when the playlist ID is unknown; read-only and idempotent.', idempotent: true },props: {playlistId: Property.ShortText({diff --git a/packages/pieces/community/youtube/src/lib/actions/list-playlist-videos.ts b/packages/pieces/community/youtube/src/lib/actions/list-playlist-videos.tsnew file mode 100644index 00000000000..b10499ba542--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/list-playlist-videos.ts@@ -0,0 +1,22 @@+import { createAction } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { listPlaylistItemsOutputSchema } from '../output-schemas';+import { youtubeListPlaylistItemsAction } from './list-playlist-items';++export const youtubeListPlaylistVideosAction = createAction({+ auth: youtubeAuth,+ outputSchema: listPlaylistItemsOutputSchema,+ name: 'list_playlist_videos',+ classification: 'SEARCH',+ displayName: 'List Playlist Videos',+ description:+ 'Returns videos in a YouTube playlist. You can filter by playlist ID or by specific item IDs.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the entries of a YouTube playlist, either by playlist ID or by a comma-separated list of playlist item IDs, and is the source of the playlist item ID that Remove Video From Playlist needs. Use List Channel Playlists first when the playlist ID is unknown. Exactly one of Playlist ID or Item IDs is required and Max Results is capped at 50. Read-only and idempotent.',+ idempotent: true,+ },+ props: youtubeListPlaylistItemsAction.props,+ run: youtubeListPlaylistItemsAction.run,+});diff --git a/packages/pieces/community/youtube/src/lib/actions/list-playlists.ts b/packages/pieces/community/youtube/src/lib/actions/list-playlists.tsindex 5d4f0a7c3f1..541302f5932 100644--- a/packages/pieces/community/youtube/src/lib/actions/list-playlists.ts+++ b/packages/pieces/community/youtube/src/lib/actions/list-playlists.ts@@ -10,7 +10,7 @@ export const youtubeListPlaylistsAction = createAction({classification: 'SEARCH',displayName: 'List Playlists',description: 'List the playlists on a channel.',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Lists the playlists belonging to a YouTube channel using playlists.list, returning each playlist title, description, item count and privacy status. Use it to discover a playlist ID before calling List Playlist Items. Read-only and idempotent.',diff --git a/packages/pieces/community/youtube/src/lib/actions/list-trending-videos.ts b/packages/pieces/community/youtube/src/lib/actions/list-trending-videos.tsnew file mode 100644index 00000000000..16e5fed23a3--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/list-trending-videos.ts@@ -0,0 +1,84 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { listTrendingVideosOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeListTrendingVideosAction = createAction({+ auth: youtubeAuth,+ outputSchema: listTrendingVideosOutputSchema,+ name: 'list_trending_videos',+ classification: 'SEARCH',+ displayName: 'List Trending Videos',+ description: 'List the most popular videos in a region, optionally by category.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the currently most popular YouTube videos for a region via videos.list with the mostPopular chart, returning full video details including statistics. Use it for trending discovery; use Search YouTube when a free-text query is needed, which costs far more quota. Region Code is an ISO 3166-1 alpha-2 country code and defaults to US. Read-only and idempotent.',+ idempotent: true,+ },+ props: {+ regionCode: Property.ShortText({+ displayName: 'Region Code',+ description:+ 'ISO 3166-1 alpha-2 country code (for example: US, DE, JP). Defaults to US.',+ required: false,+ defaultValue: 'US',+ }),+ videoCategoryId: Property.ShortText({+ displayName: 'Video Category ID',+ description:+ 'Restrict the chart to one video category ID (for example: 10 for Music). Leave blank for all categories.',+ required: false,+ }),+ maxResults: Property.Number({+ displayName: 'Max Results',+ description: 'Number of videos to return (1-50, default 25).',+ required: false,+ defaultValue: 25,+ }),+ pageToken: Property.ShortText({+ displayName: 'Page Token',+ description: 'Token from a previous response, to fetch the next page.',+ required: false,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { regionCode, videoCategoryId, maxResults, pageToken } =+ context.propsValue;++ if (maxResults !== undefined && maxResults !== null) {+ const maxResultsNumber = Math.trunc(Number(maxResults));+ if (+ !Number.isFinite(maxResultsNumber) ||+ maxResultsNumber < 1 ||+ maxResultsNumber > 50+ ) {+ throw new Error('Max Results must be between 1 and 50.');+ }+ }++ const queryParams: Record<string, string> = {+ part: 'snippet,contentDetails,statistics',+ chart: 'mostPopular',+ regionCode: regionCode ?? 'US',+ maxResults: String(Math.trunc(Number(maxResults ?? 25))),+ };++ if (videoCategoryId) {+ queryParams['videoCategoryId'] = videoCategoryId;+ }+ if (pageToken) {+ queryParams['pageToken'] = pageToken;+ }++ return youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.GET,+ path: '/videos',+ operation: 'List Trending Videos',+ queryParams,+ });+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/post-video-comment.ts b/packages/pieces/community/youtube/src/lib/actions/post-video-comment.tsnew file mode 100644index 00000000000..7c9ed2c06f1--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/post-video-comment.ts@@ -0,0 +1,50 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { postVideoCommentOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubePostVideoCommentAction = createAction({+ auth: youtubeAuth,+ outputSchema: postVideoCommentOutputSchema,+ name: 'post_video_comment',+ classification: 'WRITE',+ displayName: 'Post Video Comment',+ description: 'Post a new top-level comment on a video.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Posts a new top-level comment on a YouTube video via commentThreads.insert, as the authenticated account. Use Reply To Comment to answer an existing comment instead of starting a new thread. Comments must be enabled on the video, otherwise YouTube answers 403, and each call posts another comment so retries duplicate it.',+ idempotent: false,+ },+ props: {+ videoId: Property.ShortText({+ displayName: 'Video ID',+ description: 'The `v` parameter in a YouTube URL (e.g. `dQw4w9WgXcQ`).',+ required: true,+ }),+ text: Property.LongText({+ displayName: 'Comment Text',+ description: 'The comment body to post.',+ required: true,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { videoId, text } = context.propsValue;++ return youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.POST,+ path: '/commentThreads',+ operation: 'Post Video Comment',+ queryParams: { part: 'snippet' },+ body: {+ snippet: {+ videoId,+ topLevelComment: { snippet: { textOriginal: text } },+ },+ },+ });+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/rate-video.ts b/packages/pieces/community/youtube/src/lib/actions/rate-video.tsnew file mode 100644index 00000000000..b7f7d50ee46--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/rate-video.ts@@ -0,0 +1,53 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { rateVideoOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeRateVideoAction = createAction({+ auth: youtubeAuth,+ outputSchema: rateVideoOutputSchema,+ name: 'rate_video',+ classification: 'WRITE',+ displayName: 'Rate Video',+ description: 'Like, dislike, or remove the rating on a video.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Sets the authenticated account rating on a YouTube video via videos.rate, using like, dislike, or none to clear an existing rating. Use Get Video Rating to read the current rating first. The call replaces whatever rating was there, so applying the same value again changes nothing.',+ idempotent: true,+ },+ props: {+ videoId: Property.ShortText({+ displayName: 'Video ID',+ description: 'The `v` parameter in a YouTube URL (e.g. `dQw4w9WgXcQ`).',+ required: true,+ }),+ rating: Property.StaticDropdown({+ displayName: 'Rating',+ description: 'The rating to apply. None removes any existing rating.',+ required: true,+ options: {+ options: [+ { label: 'Like', value: 'like' },+ { label: 'Dislike', value: 'dislike' },+ { label: 'None (remove rating)', value: 'none' },+ ],+ },+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { videoId, rating } = context.propsValue;++ await youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.POST,+ path: '/videos/rate',+ operation: 'Rate Video',+ queryParams: { id: videoId, rating },+ });++ return { success: true, videoId, rating };+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/remove-video-from-playlist.ts b/packages/pieces/community/youtube/src/lib/actions/remove-video-from-playlist.tsnew file mode 100644index 00000000000..ddcc4efba20--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/remove-video-from-playlist.ts@@ -0,0 +1,42 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { removeVideoFromPlaylistOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeRemoveVideoFromPlaylistAction = createAction({+ auth: youtubeAuth,+ outputSchema: removeVideoFromPlaylistOutputSchema,+ name: 'remove_video_from_playlist',+ classification: 'DESTRUCTIVE',+ displayName: 'Remove Video From Playlist',+ description: 'Remove one entry from a playlist owned by the connected account.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes a single entry from a playlist via playlistItems.delete. It takes the playlist item ID, not the video ID — get it from List Playlist Videos or from the output of Add Video To Playlist. Use Delete Playlist to remove the whole playlist; a repeated call fails because the entry is gone.',+ idempotent: false,+ },+ props: {+ playlistItemId: Property.ShortText({+ displayName: 'Playlist Item ID',+ description:+ 'The playlist item ID (a long opaque string), not the video ID. Obtain it from List Playlist Videos or Add Video To Playlist.',+ required: true,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { playlistItemId } = context.propsValue;++ await youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.DELETE,+ path: '/playlistItems',+ operation: 'Remove Video From Playlist',+ queryParams: { id: playlistItemId },+ });++ return { success: true, playlistItemId };+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/reply-to-comment.ts b/packages/pieces/community/youtube/src/lib/actions/reply-to-comment.tsnew file mode 100644index 00000000000..a02a54cad9a--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/reply-to-comment.ts@@ -0,0 +1,48 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { replyToCommentOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeReplyToCommentAction = createAction({+ auth: youtubeAuth,+ outputSchema: replyToCommentOutputSchema,+ name: 'reply_to_comment',+ classification: 'WRITE',+ displayName: 'Reply To Comment',+ description: 'Reply to an existing top-level comment.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Posts a reply to an existing top-level YouTube comment via comments.insert, as the authenticated account. Use Post Video Comment to start a new thread instead. The parent must be a top-level comment ID from List Comment Threads — YouTube has no nested replies, so replying to a reply fails — and each call posts another reply.',+ idempotent: false,+ },+ props: {+ parentCommentId: Property.ShortText({+ displayName: 'Parent Comment ID',+ description:+ 'The ID of a top-level comment, from `items[].snippet.topLevelComment.id` in List Comment Threads. Reply IDs are not accepted.',+ required: true,+ }),+ text: Property.LongText({+ displayName: 'Reply Text',+ description: 'The reply body to post.',+ required: true,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { parentCommentId, text } = context.propsValue;++ return youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.POST,+ path: '/comments',+ operation: 'Reply To Comment',+ queryParams: { part: 'snippet' },+ body: {+ snippet: { parentId: parentCommentId, textOriginal: text },+ },+ });+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/search-youtube.ts b/packages/pieces/community/youtube/src/lib/actions/search-youtube.tsnew file mode 100644index 00000000000..97c805d141c--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/search-youtube.ts@@ -0,0 +1,22 @@+import { createAction } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { searchOutputSchema } from '../output-schemas';+import { youtubeSearchAction } from './search';++export const youtubeSearchYoutubeAction = createAction({+ auth: youtubeAuth,+ outputSchema: searchOutputSchema,+ name: 'search_youtube',+ classification: 'SEARCH',+ displayName: 'Search YouTube',+ description:+ 'Search YouTube videos, channels, and playlists using the YouTube Data API search.list endpoint.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Runs a free-text YouTube search across videos, channels and playlists, or restricted to one type, returning the matching IDs. Prefer List Channel Videos or List Trending Videos when either fits, because search costs a hundred times more quota and caps at 500 results. Video-only filters such as duration, definition and caption require Type to be Video. Read-only and idempotent.',+ idempotent: true,+ },+ props: youtubeSearchAction.props,+ run: youtubeSearchAction.run,+});diff --git a/packages/pieces/community/youtube/src/lib/actions/search.ts b/packages/pieces/community/youtube/src/lib/actions/search.tsindex 59f505e9ae7..4f4135415a2 100644--- a/packages/pieces/community/youtube/src/lib/actions/search.ts+++ b/packages/pieces/community/youtube/src/lib/actions/search.ts@@ -12,7 +12,7 @@ export const youtubeSearchAction = createAction({displayName: 'Search',description:'Search YouTube videos, channels, and playlists using the YouTube Data API search.list endpoint.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Runs a YouTube search.list query across videos, channels, and playlists at once or restricted to a single resource type, and can instead be scoped to uploads owned by the authenticated account (For Mine), a CMS content owner, or the developer project. Use it to turn a free-text query, channel, date range, region, or topic into video, channel, or playlist IDs for later steps; prefer List Playlist Items when the playlist ID is already known. Video-only filters such as duration, definition, caption, event type, and location require Type to be Video, and Location must be paired with Location Radius. Read-only and idempotent.', idempotent: true },props: {query: Property.ShortText({diff --git a/packages/pieces/community/youtube/src/lib/actions/set-comment-moderation-status.ts b/packages/pieces/community/youtube/src/lib/actions/set-comment-moderation-status.tsnew file mode 100644index 00000000000..4bfc3fab24a--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/set-comment-moderation-status.ts@@ -0,0 +1,82 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { setCommentModerationStatusOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++export const youtubeSetCommentModerationStatusAction = createAction({+ auth: youtubeAuth,+ outputSchema: setCommentModerationStatusOutputSchema,+ name: 'set_comment_moderation_status',+ classification: 'WRITE',+ displayName: 'Set Comment Moderation Status',+ description:+ 'Publish, hold for review, or reject comments on the connected account videos.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Sets the moderation status of one or more comments on videos the authenticated account owns via comments.setModerationStatus. Use it instead of Delete Comment when the comment should be hidden or approved rather than destroyed. Ban Author only applies with the Rejected status and permanently bars that author from the channel, so leave it off unless that is intended; re-applying the same status is a no-op.',+ idempotent: true,+ },+ props: {+ commentIds: Property.ShortText({+ displayName: 'Comment IDs',+ description:+ 'A comment ID, or a comma-separated list of comment IDs, from List Comment Threads.',+ required: true,+ }),+ moderationStatus: Property.StaticDropdown({+ displayName: 'Moderation Status',+ description: 'The status to apply to every listed comment.',+ required: true,+ options: {+ options: [+ { label: 'Published', value: 'published' },+ { label: 'Held For Review', value: 'heldForReview' },+ { label: 'Rejected', value: 'rejected' },+ ],+ },+ }),+ banAuthor: Property.StaticDropdown({+ displayName: 'Ban Author',+ description:+ 'Permanently ban the comment author from the channel. Only valid with the Rejected status and cannot be undone.',+ required: false,+ defaultValue: 'no',+ options: {+ options: [+ { label: 'No', value: 'no' },+ { label: 'Yes, ban the author', value: 'yes' },+ ],+ },+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const { commentIds, moderationStatus, banAuthor } = context.propsValue;++ if (banAuthor === 'yes' && moderationStatus !== 'rejected') {+ throw new Error(+ 'Ban Author can only be used together with the Rejected moderation status.'+ );+ }++ const queryParams: Record<string, string> = {+ id: commentIds,+ moderationStatus,+ };+ if (banAuthor === 'yes') {+ queryParams['banAuthor'] = 'true';+ }++ await youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.POST,+ path: '/comments/setModerationStatus',+ operation: 'Set Comment Moderation Status',+ queryParams,+ });++ return { success: true, commentIds, moderationStatus };+ },+});diff --git a/packages/pieces/community/youtube/src/lib/actions/update-playlist.ts b/packages/pieces/community/youtube/src/lib/actions/update-playlist.tsnew file mode 100644index 00000000000..ae054d85909--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/update-playlist.ts@@ -0,0 +1,186 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { updatePlaylistOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++function asSuppliedText(value: string | undefined): string | undefined {+ return value === undefined || value === '' ? undefined : value;+}++export const youtubeUpdatePlaylistAction = createAction({+ auth: youtubeAuth,+ outputSchema: updatePlaylistOutputSchema,+ name: 'update_playlist',+ classification: 'WRITE',+ displayName: 'Update Playlist',+ description:+ 'Update the title, description, tags or privacy of an existing playlist.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates a playlist owned by the authenticated channel via playlists.update, reading the playlist first and merging only the fields you supply so untouched fields survive. Use it to rename or re-describe an existing playlist; use Create Playlist for a new one. The playlist must belong to the connected account, and applying the same values again converges on the same state.',+ idempotent: true,+ },+ props: {+ playlistId: Property.ShortText({+ displayName: 'Playlist ID',+ description:+ 'The playlist to update. This is the `list` parameter in a playlist URL (e.g. `PLbpi6ZahtOH6Ar_3GPy3workLYfGa7mGm`).',+ required: true,+ }),+ title: Property.ShortText({+ displayName: 'Title',+ description: 'New title. Leave blank to keep the current title.',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description:+ 'New description. Leave blank to keep the current description.',+ required: false,+ }),+ tagsMode: Property.StaticDropdown({+ displayName: 'Tags Update Mode',+ description:+ 'How to treat the Tags field. Leave Unchanged keeps the existing tags.',+ required: false,+ defaultValue: 'unchanged',+ options: {+ options: [+ { label: 'Leave unchanged', value: 'unchanged' },+ { label: 'Replace with the tags below', value: 'replace' },+ { label: 'Clear all tags', value: 'clear' },+ ],+ },+ }),+ tags: Property.Array({+ displayName: 'Tags',+ description: 'Tags to set when Tags Update Mode is Replace.',+ required: false,+ }),+ privacyStatus: Property.StaticDropdown({+ displayName: 'Privacy Status',+ description: 'New privacy. Leave Unchanged keeps the current value.',+ required: false,+ defaultValue: 'unchanged',+ options: {+ options: [+ { label: 'Leave unchanged', value: 'unchanged' },+ { label: 'Private', value: 'private' },+ { label: 'Unlisted', value: 'unlisted' },+ { label: 'Public', value: 'public' },+ ],+ },+ }),+ defaultLanguage: Property.ShortText({+ displayName: 'Default Language',+ description:+ 'BCP-47 language code of the title and description. Leave blank to keep the current value.',+ required: false,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const {+ playlistId,+ title,+ description,+ tagsMode,+ tags,+ privacyStatus,+ defaultLanguage,+ } = context.propsValue;++ const existing = await youtubeClient.sendRequest<PlaylistListResponse>({+ accessToken,+ method: HttpMethod.GET,+ path: '/playlists',+ operation: 'Update Playlist (reading the current playlist)',+ queryParams: { part: 'snippet,status', id: playlistId },+ });++ const current = existing.items?.[0];+ if (!current) {+ throw new Error(+ `Playlist "${playlistId}" was not found or is not owned by the connected YouTube account.`+ );+ }++ const mergedTitle = asSuppliedText(title) ?? current.snippet?.title;+ if (!mergedTitle) {+ throw new Error(+ 'YouTube requires a playlist title. Provide a Title because the existing playlist has none.'+ );+ }++ const snippet: PlaylistSnippetPayload = { title: mergedTitle };++ const mergedDescription =+ asSuppliedText(description) ?? current.snippet?.description;+ if (mergedDescription !== undefined) {+ snippet.description = mergedDescription;+ }++ const mergedLanguage =+ asSuppliedText(defaultLanguage) ?? current.snippet?.defaultLanguage;+ if (mergedLanguage !== undefined) {+ snippet.defaultLanguage = mergedLanguage;+ }++ if (tagsMode === 'clear') {+ snippet.tags = [];+ } else if (tagsMode === 'replace') {+ snippet.tags = (tags ?? []).map((tag) => String(tag));+ } else if (current.snippet?.tags !== undefined) {+ snippet.tags = current.snippet.tags;+ }++ const mergedPrivacy =+ privacyStatus && privacyStatus !== 'unchanged'+ ? privacyStatus+ : current.status?.privacyStatus;++ const body: PlaylistUpdatePayload = { id: playlistId, snippet };+ if (mergedPrivacy !== undefined) {+ body.status = { privacyStatus: mergedPrivacy };+ }++ return youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.PUT,+ path: '/playlists',+ operation: 'Update Playlist',+ queryParams: { part: 'snippet,status' },+ body,+ ifMatch: current.etag,+ });+ },+});++type PlaylistSnippetPayload = {+ title: string;+ description?: string;+ defaultLanguage?: string;+ tags?: string[];+};++type PlaylistUpdatePayload = {+ id: string;+ snippet: PlaylistSnippetPayload;+ status?: { privacyStatus: string };+};++type PlaylistListResponse = {+ items?: {+ id: string;+ etag?: string;+ snippet?: {+ title?: string;+ description?: string;+ defaultLanguage?: string;+ tags?: string[];+ };+ status?: { privacyStatus?: string };+ }[];+};diff --git a/packages/pieces/community/youtube/src/lib/actions/update-video-metadata.ts b/packages/pieces/community/youtube/src/lib/actions/update-video-metadata.tsnew file mode 100644index 00000000000..ee432643505--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/actions/update-video-metadata.ts@@ -0,0 +1,366 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { youtubeAuth } from '../common/auth';+import { updateVideoMetadataOutputSchema } from '../output-schemas';+import { youtubeClient } from '../common/client';++const unchangedBooleanOptions = {+ options: [+ { label: 'Leave unchanged', value: 'unchanged' },+ { label: 'Yes', value: 'yes' },+ { label: 'No', value: 'no' },+ ],+};++function resolveTriState({+ selection,+ current,+}: {+ selection: string | undefined;+ current: boolean | undefined;+}): boolean | undefined {+ if (selection === 'yes') {+ return true;+ }+ if (selection === 'no') {+ return false;+ }+ return current;+}++function asSuppliedText(value: string | undefined): string | undefined {+ return value === undefined || value === '' ? undefined : value;+}++function isChosen(selection: string | undefined): boolean {+ return selection !== undefined && selection !== 'unchanged';+}++export const youtubeUpdateVideoMetadataAction = createAction({+ auth: youtubeAuth,+ outputSchema: updateVideoMetadataOutputSchema,+ name: 'update_video_metadata',+ classification: 'WRITE',+ displayName: 'Update Video Metadata',+ description:+ 'Update the title, description, tags, category or status of a video you own.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates metadata on a video owned by the authenticated channel via videos.update, reading the video first and merging only the fields you supply so untouched fields survive. Use it to retitle, re-describe, re-tag or re-categorise an upload; use Rate Video for likes and Set Comment Moderation Status for comments. The video must belong to the connected account, and applying the same values again converges on the same state.',+ idempotent: true,+ },+ props: {+ videoId: Property.ShortText({+ displayName: 'Video ID',+ description: 'The `v` parameter in a YouTube URL (e.g. `dQw4w9WgXcQ`).',+ required: true,+ }),+ title: Property.ShortText({+ displayName: 'Title',+ description: 'New title. Leave blank to keep the current title.',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description:+ 'New description. Leave blank to keep the current description.',+ required: false,+ }),+ categoryId: Property.ShortText({+ displayName: 'Category ID',+ description:+ 'New video category ID (for example: 10 for Music). Leave blank to keep the current category.',+ required: false,+ }),+ tagsMode: Property.StaticDropdown({+ displayName: 'Tags Update Mode',+ description:+ 'How to treat the Tags field. Leave Unchanged keeps the existing tags.',+ required: false,+ defaultValue: 'unchanged',+ options: {+ options: [+ { label: 'Leave unchanged', value: 'unchanged' },+ { label: 'Replace with the tags below', value: 'replace' },+ { label: 'Clear all tags', value: 'clear' },+ ],+ },+ }),+ tags: Property.Array({+ displayName: 'Tags',+ description: 'Tags to set when Tags Update Mode is Replace.',+ required: false,+ }),+ defaultLanguage: Property.ShortText({+ displayName: 'Default Language',+ description:+ 'BCP-47 language code of the title and description. Leave blank to keep the current value.',+ required: false,+ }),+ privacyStatus: Property.StaticDropdown({+ displayName: 'Privacy Status',+ description: 'New privacy. Leave Unchanged keeps the current value.',+ required: false,+ defaultValue: 'unchanged',+ options: {+ options: [+ { label: 'Leave unchanged', value: 'unchanged' },+ { label: 'Private', value: 'private' },+ { label: 'Unlisted', value: 'unlisted' },+ { label: 'Public', value: 'public' },+ ],+ },+ }),+ license: Property.StaticDropdown({+ displayName: 'License',+ description: 'New license. Leave Unchanged keeps the current value.',+ required: false,+ defaultValue: 'unchanged',+ options: {+ options: [+ { label: 'Leave unchanged', value: 'unchanged' },+ { label: 'Standard YouTube License', value: 'youtube' },+ { label: 'Creative Commons', value: 'creativeCommon' },+ ],+ },+ }),+ embeddable: Property.StaticDropdown({+ displayName: 'Embeddable',+ description:+ 'Whether the video can be embedded on other sites. Leave Unchanged keeps the current value.',+ required: false,+ defaultValue: 'unchanged',+ options: unchangedBooleanOptions,+ }),+ publicStatsViewable: Property.StaticDropdown({+ displayName: 'Public Stats Viewable',+ description:+ 'Whether the video statistics are publicly visible. Leave Unchanged keeps the current value.',+ required: false,+ defaultValue: 'unchanged',+ options: unchangedBooleanOptions,+ }),+ madeForKids: Property.StaticDropdown({+ displayName: 'Made For Kids',+ description:+ 'Self-declaration that the video is made for kids. Leave Unchanged keeps the current value.',+ required: false,+ defaultValue: 'unchanged',+ options: unchangedBooleanOptions,+ }),+ },+ async run(context) {+ const accessToken = context.auth.access_token;+ const {+ videoId,+ title,+ description,+ categoryId,+ tagsMode,+ tags,+ defaultLanguage,+ privacyStatus,+ license,+ embeddable,+ publicStatsViewable,+ madeForKids,+ } = context.propsValue;++ const snippetTouched =+ asSuppliedText(title) !== undefined ||+ asSuppliedText(description) !== undefined ||+ asSuppliedText(categoryId) !== undefined ||+ asSuppliedText(defaultLanguage) !== undefined ||+ isChosen(tagsMode);++ const statusTouched =+ isChosen(privacyStatus) ||+ isChosen(license) ||+ isChosen(embeddable) ||+ isChosen(publicStatsViewable) ||+ isChosen(madeForKids);++ if (!snippetTouched && !statusTouched) {+ throw new Error(+ 'Nothing to update. Supply at least one field to change on the video.'+ );+ }++ const existing = await youtubeClient.sendRequest<VideoListResponse>({+ accessToken,+ method: HttpMethod.GET,+ path: '/videos',+ operation: 'Update Video Metadata (reading the current video)',+ queryParams: { part: 'snippet,status', id: videoId },+ });++ const current = existing.items?.[0];+ if (!current) {+ throw new Error(+ `Video "${videoId}" was not found or is not owned by the connected YouTube account.`+ );+ }++ const parts: string[] = [];+ const body: VideoUpdatePayload = { id: videoId };++ if (snippetTouched) {+ const mergedTitle = asSuppliedText(title) ?? current.snippet?.title;+ const mergedCategoryId =+ asSuppliedText(categoryId) ?? current.snippet?.categoryId;++ if (!mergedTitle) {+ throw new Error(+ 'YouTube requires a video title on every update. Provide a Title because the existing video has none.'+ );+ }+ if (!mergedCategoryId) {+ throw new Error(+ 'YouTube requires a category ID on every update. Provide a Category ID because the existing video has none.'+ );+ }++ const snippet: VideoSnippetPayload = {+ title: mergedTitle,+ categoryId: mergedCategoryId,+ };++ const mergedDescription =+ asSuppliedText(description) ?? current.snippet?.description;+ if (mergedDescription !== undefined) {+ snippet.description = mergedDescription;+ }++ const mergedLanguage =+ asSuppliedText(defaultLanguage) ?? current.snippet?.defaultLanguage;+ if (mergedLanguage !== undefined) {+ snippet.defaultLanguage = mergedLanguage;+ }++ if (tagsMode === 'clear') {+ snippet.tags = [];+ } else if (tagsMode === 'replace') {+ snippet.tags = (tags ?? []).map((tag) => String(tag));+ } else if (current.snippet?.tags !== undefined) {+ snippet.tags = current.snippet.tags;+ }++ body.snippet = snippet;+ parts.push('snippet');+ }++ if (statusTouched) {+ const status: VideoStatusPayload = {};++ const mergedPrivacy = isChosen(privacyStatus)+ ? privacyStatus+ : current.status?.privacyStatus;+ if (mergedPrivacy !== undefined) {+ status.privacyStatus = mergedPrivacy;+ }++ const mergedLicense = isChosen(license)+ ? license+ : current.status?.license;+ if (mergedLicense !== undefined) {+ status.license = mergedLicense;+ }++ const mergedEmbeddable = resolveTriState({+ selection: embeddable,+ current: current.status?.embeddable,+ });+ if (mergedEmbeddable !== undefined) {+ status.embeddable = mergedEmbeddable;+ }++ const mergedPublicStatsViewable = resolveTriState({+ selection: publicStatsViewable,+ current: current.status?.publicStatsViewable,+ });+ if (mergedPublicStatsViewable !== undefined) {+ status.publicStatsViewable = mergedPublicStatsViewable;+ }++ const mergedMadeForKids = resolveTriState({+ selection: madeForKids,+ current: current.status?.selfDeclaredMadeForKids,+ });+ if (mergedMadeForKids !== undefined) {+ status.selfDeclaredMadeForKids = mergedMadeForKids;+ }++ if (+ current.status?.publishAt !== undefined &&+ status.privacyStatus === 'private'+ ) {+ status.publishAt = current.status.publishAt;+ }++ if (current.status?.containsSyntheticMedia !== undefined) {+ status.containsSyntheticMedia = current.status.containsSyntheticMedia;+ }++ body.status = status;+ parts.push('status');+ }++ return youtubeClient.sendRequest({+ accessToken,+ method: HttpMethod.PUT,+ path: '/videos',+ operation: 'Update Video Metadata',+ queryParams: { part: parts.join(',') },+ body,+ ifMatch: current.etag,+ });+ },+});++type VideoSnippetPayload = {+ title: string;+ categoryId: string;+ description?: string;+ defaultLanguage?: string;+ tags?: string[];+};++type VideoUpdatePayload = {+ id: string;+ snippet?: VideoSnippetPayload;+ status?: VideoStatusPayload;+};++type VideoStatusPayload = {+ privacyStatus?: string;+ license?: string;+ embeddable?: boolean;+ publicStatsViewable?: boolean;+ selfDeclaredMadeForKids?: boolean;+ publishAt?: string;+ containsSyntheticMedia?: boolean;+};++type VideoListResponse = {+ items?: {+ id: string;+ etag?: string;+ snippet?: {+ title?: string;+ description?: string;+ categoryId?: string;+ defaultLanguage?: string;+ tags?: string[];+ };+ status?: {+ privacyStatus?: string;+ license?: string;+ embeddable?: boolean;+ publicStatsViewable?: boolean;+ selfDeclaredMadeForKids?: boolean;+ publishAt?: string;+ containsSyntheticMedia?: boolean;+ };+ }[];+};diff --git a/packages/pieces/community/youtube/src/lib/common/client.ts b/packages/pieces/community/youtube/src/lib/common/client.tsnew file mode 100644index 00000000000..cc3c85c2fdf--- /dev/null+++ b/packages/pieces/community/youtube/src/lib/common/client.ts@@ -0,0 +1,93 @@+import {+ httpClient,+ HttpError,+ HttpMethod,+ QueryParams,+} from '@activepieces/pieces-common';++const YOUTUBE_API_BASE_URL = 'https://www.googleapis.com/youtube/v3';++function describeFailure({+ status,+ operation,+}: {+ status: number;+ operation: string;+}): string {+ switch (status) {+ case 401:+ return `YouTube rejected the connection while running ${operation}. Reconnect the YouTube account and try again.`;+ case 403:+ return `YouTube denied ${operation}. The connected account may not own this resource, the required permission may be missing, or the daily API quota may be exhausted.`;+ case 404:+ return `YouTube could not find the resource for ${operation}. Check the identifier and that the connected account can access it.`;+ case 409:+ case 412:+ return `YouTube refused ${operation} because the resource was modified after this step read it. Nothing was changed. Re-run the step to pick up the current values and apply the change again.`;+ case 429:+ return `YouTube rate limited ${operation}. Wait before retrying.`;+ default:+ return `YouTube returned HTTP ${status} for ${operation}.`;+ }+}++async function sendRequest<T>({+ accessToken,+ method,+ path,+ operation,+ queryParams,+ body,+ ifMatch,+}: YoutubeRequestParams): Promise<T> {+ const headers: Record<string, string> = {+ Authorization: `Bearer ${accessToken}`,+ };+ if (ifMatch !== undefined && ifMatch !== '') {+ headers['If-Match'] = ifMatch;+ }++ try {+ const response = await httpClient.sendRequest<T>({+ method,+ url: `${YOUTUBE_API_BASE_URL}${path}`,+ headers,+ queryParams,+ body,+ });+ return response.body;+ } catch (error) {+ if (error instanceof HttpError) {+ const status = error.response.status;+ throw new YoutubeApiError({+ status,+ message: `${describeFailure({ status, operation })} Details: ${JSON.stringify(+ error.response.body+ )}`,+ });+ }+ throw error;+ }+}++export class YoutubeApiError extends Error {+ public readonly status: number;++ constructor({ status, message }: { status: number; message: string }) {+ super(message);+ this.name = 'YoutubeApiError';+ this.status = status;+ }+}++export const youtubeClient = { sendRequest };++export type YoutubeRequestParams = {+ accessToken: string;+ method: HttpMethod;+ path: string;+ operation: string;+ queryParams?: QueryParams;+ body?: unknown;+ ifMatch?: string;+};diff --git a/packages/pieces/community/youtube/src/lib/output-schemas.ts b/packages/pieces/community/youtube/src/lib/output-schemas.tsindex 6a9724a8fa5..37104f57dbe 100644--- a/packages/pieces/community/youtube/src/lib/output-schemas.ts+++ b/packages/pieces/community/youtube/src/lib/output-schemas.ts@@ -125,6 +125,8 @@ const fullThumbnailSetFields: Fields = [...basicThumbnailSetFields,{ key: 'standard', label: 'Standard', children: thumbnailFields },{ key: 'maxres', label: 'Max Resolution', children: thumbnailFields },+ { key: 'fhd', label: 'Full HD', children: thumbnailFields },+ { key: 'qhd', label: 'Quad HD', children: thumbnailFields },];const pageInfoFields: Fields = [@@ -153,7 +155,7 @@ const searchItemFields: Fields = [] },];-const playlistItemFields: Fields = [+const playlistItemSnippetFields: Fields = [{ key: 'kind', label: 'Kind' },{ key: 'etag', label: 'ETag' },{ key: 'id', label: 'Playlist Item ID' },@@ -173,6 +175,10 @@ const playlistItemFields: Fields = [] },{ key: 'thumbnails', label: 'Thumbnails', children: fullThumbnailSetFields },] },+];++const playlistItemFields: Fields = [+ ...playlistItemSnippetFields,{ key: 'contentDetails', label: 'Content Details', children: [{ key: 'videoId', label: 'Video ID' },{ key: 'videoPublishedAt', label: 'Video Published At', format: 'datetime' },@@ -203,10 +209,13 @@ const captionItemFields: Fields = [];-const videoItemFields: Fields = [+const videoIdentityFields: Fields = [{ key: 'kind', label: 'Kind' },{ key: 'etag', label: 'ETag' },{ key: 'id', label: 'Video ID' },+];++const videoSnippetField: Fields = [{ key: 'snippet', label: 'Snippet', children: [{ key: 'publishedAt', label: 'Published At', format: 'datetime' },{ key: 'channelId', label: 'Channel ID' },@@ -224,6 +233,9 @@ const videoItemFields: Fields = [] },{ key: 'thumbnails', label: 'Thumbnails', children: fullThumbnailSetFields },] },+];++const videoContentDetailsField: Fields = [{ key: 'contentDetails', label: 'Content Details', children: [{ key: 'duration', label: 'Duration (ISO 8601)' },{ key: 'dimension', label: 'Dimension' },@@ -232,12 +244,18 @@ const videoItemFields: Fields = [{ key: 'licensedContent', label: 'Licensed Content', format: 'boolean' },{ key: 'projection', label: 'Projection' },] },+];++const videoStatisticsField: Fields = [{ key: 'statistics', label: 'Statistics', children: [{ key: 'viewCount', label: 'View Count' },{ key: 'likeCount', label: 'Like Count' },{ key: 'favoriteCount', label: 'Favorite Count' },{ key: 'commentCount', label: 'Comment Count' },] },+];++const videoStatusField: Fields = [{ key: 'status', label: 'Status', children: [{ key: 'uploadStatus', label: 'Upload Status' },{ key: 'privacyStatus', label: 'Privacy Status' },@@ -245,9 +263,31 @@ const videoItemFields: Fields = [{ key: 'embeddable', label: 'Embeddable', format: 'boolean' },{ key: 'publicStatsViewable', label: 'Public Stats Viewable', format: 'boolean' },{ key: 'madeForKids', label: 'Made For Kids', format: 'boolean' },+ { key: 'selfDeclaredMadeForKids', label: 'Self-Declared Made For Kids', format: 'boolean' },] },];+const videoItemFields: Fields = [+ ...videoIdentityFields,+ ...videoSnippetField,+ ...videoContentDetailsField,+ ...videoStatisticsField,+ ...videoStatusField,+];++const videoSnippetStatusFields: Fields = [+ ...videoIdentityFields,+ ...videoSnippetField,+ ...videoStatusField,+];++const videoChartItemFields: Fields = [+ ...videoIdentityFields,+ ...videoSnippetField,+ ...videoContentDetailsField,+ ...videoStatisticsField,+];+const channelItemFields: Fields = [{ key: 'kind', label: 'Kind' },{ key: 'etag', label: 'ETag' },@@ -278,7 +318,7 @@ const channelItemFields: Fields = [] },];-const playlistFields: Fields = [+const playlistSnippetStatusFields: Fields = [{ key: 'kind', label: 'Kind' },{ key: 'etag', label: 'ETag' },{ key: 'id', label: 'Playlist ID' },@@ -294,17 +334,19 @@ const playlistFields: Fields = [] },{ key: 'thumbnails', label: 'Thumbnails', children: fullThumbnailSetFields },] },- { key: 'contentDetails', label: 'Content Details', children: [- { key: 'itemCount', label: 'Item Count', format: 'number' },- ] },{ key: 'status', label: 'Status', children: [{ key: 'privacyStatus', label: 'Privacy Status' },] },];-const commentSnippetFields: Fields = [- { key: 'channelId', label: 'Channel ID' },- { key: 'videoId', label: 'Video ID' },+const playlistFields: Fields = [+ ...playlistSnippetStatusFields,+ { key: 'contentDetails', label: 'Content Details', children: [+ { key: 'itemCount', label: 'Item Count', format: 'number' },+ ] },+];++const commentBodySnippetFields: Fields = [{ key: 'textDisplay', label: 'Text (HTML)', format: 'html' },{ key: 'textOriginal', label: 'Text' },{ key: 'authorDisplayName', label: 'Author' },@@ -318,6 +360,23 @@ const commentSnippetFields: Fields = [{ key: 'updatedAt', label: 'Updated At', format: 'datetime' },];+const commentSnippetFields: Fields = [+ { key: 'channelId', label: 'Channel ID' },+ { key: 'videoId', label: 'Video ID' },+ ...commentBodySnippetFields,+];++const replyCommentSnippetFields: Fields = [+ { key: 'parentId', label: 'Parent Comment ID' },+ ...commentSnippetFields,+];++const replyInsertSnippetFields: Fields = [+ { key: 'parentId', label: 'Parent Comment ID' },+ { key: 'channelId', label: 'Channel ID' },+ ...commentBodySnippetFields,+];+const commentResourceFields: Fields = [{ key: 'kind', label: 'Kind' },{ key: 'etag', label: 'ETag' },@@ -325,7 +384,21 @@ const commentResourceFields: Fields = [{ key: 'snippet', label: 'Snippet', children: commentSnippetFields },];-const commentThreadFields: Fields = [+const replyCommentResourceFields: Fields = [+ { key: 'kind', label: 'Kind' },+ { key: 'etag', label: 'ETag' },+ { key: 'id', label: 'Comment ID' },+ { key: 'snippet', label: 'Snippet', children: replyCommentSnippetFields },+];++const replyInsertResourceFields: Fields = [+ { key: 'kind', label: 'Kind' },+ { key: 'etag', label: 'ETag' },+ { key: 'id', label: 'Comment ID' },+ { key: 'snippet', label: 'Snippet', children: replyInsertSnippetFields },+];++const commentThreadInsertFields: Fields = [{ key: 'kind', label: 'Kind' },{ key: 'etag', label: 'ETag' },{ key: 'id', label: 'Thread ID' },@@ -337,11 +410,30 @@ const commentThreadFields: Fields = [{ key: 'totalReplyCount', label: 'Reply Count', format: 'number' },{ key: 'topLevelComment', label: 'Top Level Comment', children: commentResourceFields },] },+];++const commentThreadFields: Fields = [+ ...commentThreadInsertFields,{ key: 'replies', label: 'Replies', children: [- { key: 'comments', label: 'Comments', listItems: commentResourceFields, labelKey: 'id' },+ { key: 'comments', label: 'Comments', listItems: replyCommentResourceFields, labelKey: 'id' },] },];+const videoRatingItemFields: Fields = [+ { key: 'videoId', label: 'Video ID' },+ { key: 'rating', label: 'Rating' },+];++const undescribedItemsEnvelope = ({ label }: { label: string }): OutputSchema => ({+ fields: [+ { key: 'kind', label: 'Kind' },+ { key: 'etag', label: 'ETag' },+ { key: 'nextPageToken', label: 'Next Page Token' },+ { key: 'pageInfo', label: 'Page Info', children: pageInfoFields },+ { key: 'items', label },+ ],+});+const listEnvelope = ({label,itemFields,@@ -424,3 +516,97 @@ export const listCommentsOutputSchema: OutputSchema = listEnvelope({itemLabelKey: 'id',withPrevPageToken: false,});++export const createPlaylistOutputSchema: OutputSchema = {+ fields: playlistSnippetStatusFields,+};++export const updatePlaylistOutputSchema: OutputSchema = {+ fields: playlistSnippetStatusFields,+};++export const addVideoToPlaylistOutputSchema: OutputSchema = {+ fields: playlistItemSnippetFields,+};++export const updateVideoMetadataOutputSchema: OutputSchema = {+ fields: videoSnippetStatusFields,+};++export const postVideoCommentOutputSchema: OutputSchema = {+ fields: commentThreadInsertFields,+};++export const replyToCommentOutputSchema: OutputSchema = {+ fields: replyInsertResourceFields,+};++export const getVideoRatingOutputSchema: OutputSchema = listEnvelope({+ label: 'Ratings',+ itemFields: videoRatingItemFields,+ itemLabelKey: 'videoId',+ withPageInfo: false,+ withNextPageToken: false,+ withPrevPageToken: false,+});++export const listTrendingVideosOutputSchema: OutputSchema = listEnvelope({+ label: 'Videos',+ itemFields: videoChartItemFields,+ itemLabelKey: 'id',+ withPrevPageToken: false,+});++export const listChannelVideosOutputSchema: OutputSchema = listEnvelope({+ label: 'Channel Videos',+ itemFields: playlistItemFields,+ itemLabelKey: 'id',+ withPrevPageToken: false,+});++export const listChannelActivitiesOutputSchema: OutputSchema =+ undescribedItemsEnvelope({ label: 'Activities' });++export const listSubscriptionsOutputSchema: OutputSchema =+ undescribedItemsEnvelope({ label: 'Subscriptions' });++export const deletePlaylistOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'playlistId', label: 'Playlist ID' },+ ],+};++export const removeVideoFromPlaylistOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'playlistItemId', label: 'Playlist Item ID' },+ ],+};++export const deleteCommentOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'commentId', label: 'Comment ID' },+ ],+};++export const downloadCaptionTrackOutputSchema: OutputSchema = {+ fields: [{ key: 'caption', label: 'Caption Text' }],+};++export const rateVideoOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'videoId', label: 'Video ID' },+ { key: 'rating', label: 'Rating' },+ ],+};++export const setCommentModerationStatusOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'commentIds', label: 'Comment IDs' },+ { key: 'moderationStatus', label: 'Moderation Status' },+ ],+};