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 to wordpress, woocommerce, imap and google-my-business (#15722)
Odai Ahmad9af61b9fbe44
diff --git a/bun.lock b/bun.lockindex 21147384caa..7a7ceaab3ac 100644--- a/bun.lock+++ b/bun.lock@@ -3886,7 +3886,7 @@},"packages/pieces/community/google-my-business": {"name": "@activepieces/piece-google-my-business",- "version": "0.3.0",+ "version": "0.4.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -4457,7 +4457,7 @@},"packages/pieces/community/imap": {"name": "@activepieces/piece-imap",- "version": "0.4.9",+ "version": "0.5.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -9859,7 +9859,7 @@},"packages/pieces/community/woocommerce": {"name": "@activepieces/piece-woocommerce",- "version": "0.3.0",+ "version": "0.4.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -9899,7 +9899,7 @@},"packages/pieces/community/wordpress": {"name": "@activepieces/piece-wordpress",- "version": "0.5.0",+ "version": "0.7.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/community/google-my-business/package.json b/packages/pieces/community/google-my-business/package.jsonindex da8e0f2927a..61647d729d7 100644--- a/packages/pieces/community/google-my-business/package.json+++ b/packages/pieces/community/google-my-business/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-google-my-business",- "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/google-my-business/src/i18n/translation.json b/packages/pieces/community/google-my-business/src/i18n/translation.jsonindex 3864bed725d..dd7937609e8 100644--- a/packages/pieces/community/google-my-business/src/i18n/translation.json+++ b/packages/pieces/community/google-my-business/src/i18n/translation.json@@ -32,5 +32,50 @@"New Review": "New Review","Triggers when there is new review": "Triggers when there is new review","Account": "Account",- "Location": "Location"-}\ No newline at end of file+ "Location": "Location",+ "List Accounts": "List Accounts",+ "Lists the Business Profile accounts the connected user can access.": "Lists the Business Profile accounts the connected user can access.",+ "List Locations": "List Locations",+ "Lists the business locations of an account.": "Lists the business locations of an account.",+ "Get Location": "Get Location",+ "Gets the details of a business location.": "Gets the details of a business location.",+ "Update Location": "Update Location",+ "Updates the website, labels or store code of a business location.": "Updates the website, labels or store code of a business location.",+ "Website": "Website",+ "The public website URL of the business.": "The public website URL of the business.",+ "Labels": "Labels",+ "Store Code": "Store Code",+ "Your internal identifier for the location.": "Your internal identifier for the location.",+ "List Reviews": "List Reviews",+ "Lists the customer reviews of a location.": "Lists the customer reviews of a location.",+ "Order By": "Order By",+ "Sort order. Google defaults to newest first when unset.": "Sort order. Google defaults to newest first when unset.",+ "Newest first": "Newest first",+ "Lowest rating first": "Lowest rating first",+ "Highest rating first": "Highest rating first",+ "Get Location Verification State": "Get Location Verification State",+ "Gets whether a location is verified and can publish changes.": "Gets whether a location is verified and can publish changes.",+ "List Media": "List Media",+ "Lists the photos and videos of a location.": "Lists the photos and videos of a location.",+ "Get Media": "Get Media",+ "Gets one photo or video of a location.": "Gets one photo or video of a location.",+ "Media ID": "Media ID",+ "The media key: the last segment of the name field returned by List Media (list-media).": "The media key: the last segment of the name field returned by List Media (list-media).",+ "Get Review": "Get Review",+ "Gets one customer review of a location.": "Gets one customer review of a location.",+ "Reply to Review": "Reply to Review",+ "Creates or replaces the owner reply to a review.": "Creates or replaces the owner reply to a review.",+ "The reply text.": "The reply text.",+ "Delete Review Reply": "Delete Review Reply",+ "Deletes the owner reply to a review.": "Deletes the owner reply to a review.",+ "Account ID": "Account ID",+ "The account id, e.g. 123 or accounts/123. Get it from the name field returned by List Accounts (list-accounts).": "The account id, e.g. 123 or accounts/123. Get it from the name field returned by List Accounts (list-accounts).",+ "Location ID": "Location ID",+ "The location id, e.g. 456 or locations/456. Get it from the name field returned by List Locations (list-locations).": "The location id, e.g. 456 or locations/456. Get it from the name field returned by List Locations (list-locations).",+ "Review ID": "Review ID",+ "The reviewId field returned by List Reviews (list-reviews), or the full review name.": "The reviewId field returned by List Reviews (list-reviews), or the full review name.",+ "Maximum Results": "Maximum Results",+ "Stop after this many items. Larger values are fetched over several requests.": "Stop after this many items. Larger values are fetched over several requests.",+ "Internal labels for the location. Replaces the existing labels. Leave empty to keep the current labels; this action cannot clear them.": "Internal labels for the location. Replaces the existing labels. Leave empty to keep the current labels; this action cannot clear them.",+ "Updates selected fields of a Google Business Profile location; only the fields you supply are changed and everything else is left untouched. Website is public and appears on Google Maps and Search, so change it only when the user explicitly asks. Labels replaces the whole label set, so include every label you want to keep; an empty list is ignored and cannot clear them. Store Code is internal. Empty text fields are ignored. Description, phone, hours, address and categories cannot be edited here. Safe to repeat with the same values.": "Updates selected fields of a Google Business Profile location; only the fields you supply are changed and everything else is left untouched. Website is public and appears on Google Maps and Search, so change it only when the user explicitly asks. Labels replaces the whole label set, so include every label you want to keep; an empty list is ignored and cannot clear them. Store Code is internal. Empty text fields are ignored. Description, phone, hours, address and categories cannot be edited here. Safe to repeat with the same values."+}diff --git a/packages/pieces/community/google-my-business/src/index.ts b/packages/pieces/community/google-my-business/src/index.tsindex f27174a6547..b4e5f18d5e7 100644--- a/packages/pieces/community/google-my-business/src/index.ts+++ b/packages/pieces/community/google-my-business/src/index.ts@@ -11,6 +11,17 @@ import { deletePost } from './lib/actions/delete-post';import { getPost } from './lib/actions/get-post';import { listPosts } from './lib/actions/list-posts';import { updatePost } from './lib/actions/update-post';+import { deleteReviewReply } from './lib/actions/delete-review-reply';+import { getLocation } from './lib/actions/get-location';+import { getLocationVerificationState } from './lib/actions/get-location-verification-state';+import { getMedia } from './lib/actions/get-media';+import { getReview } from './lib/actions/get-review';+import { listAccounts } from './lib/actions/list-accounts';+import { listLocations } from './lib/actions/list-locations';+import { listMedia } from './lib/actions/list-media';+import { listReviews } from './lib/actions/list-reviews';+import { replyToReview } from './lib/actions/reply-to-review';+import { updateLocation } from './lib/actions/update-location';import { newReview } from './lib/triggers/new-review';export const googleAuth = PieceAuth.OAuth2({@@ -28,6 +39,7 @@ export const googleBusiness = createPiece({logoUrl: 'https://cdn.activepieces.com/pieces/google-business.png',authors: ["kishanprmr","MoShizzle","abuaboud"],categories: [PieceCategory.MARKETING],+ minimumSupportedRelease: '0.88.2',actions: [createPost,listPosts,@@ -35,6 +47,17 @@ export const googleBusiness = createPiece({updatePost,deletePost,createReply,+ listAccounts,+ listLocations,+ getLocation,+ updateLocation,+ listReviews,+ getLocationVerificationState,+ listMedia,+ getMedia,+ getReview,+ replyToReview,+ deleteReviewReply,createCustomApiCallAction({baseUrl: () => {return 'https://mybusiness.googleapis.com/v4';diff --git a/packages/pieces/community/google-my-business/src/lib/actions/create-reply.ts b/packages/pieces/community/google-my-business/src/lib/actions/create-reply.tsindex 6b20c219a54..2ef5c1cdafd 100644--- a/packages/pieces/community/google-my-business/src/lib/actions/create-reply.ts+++ b/packages/pieces/community/google-my-business/src/lib/actions/create-reply.ts@@ -11,7 +11,7 @@ export const createReply = createAction({classification: 'WRITE',displayName: 'Create or Update Reply',description: 'Create or update a reply to a review if it already exists',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Posts the business owner\'s reply to a specific Google Business Profile review, or overwrites the existing reply if one is already present. Use to respond to customer reviews; safe to repeat since it upserts on the review name. Requires the full review resource name in the form accounts/{account}/locations/{location}/reviews/{review}.', idempotent: true },props: {reviewName: Property.ShortText({diff --git a/packages/pieces/community/google-my-business/src/lib/actions/delete-review-reply.ts b/packages/pieces/community/google-my-business/src/lib/actions/delete-review-reply.tsnew file mode 100644index 00000000000..49aa6a9104c--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/delete-review-reply.ts@@ -0,0 +1,33 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { deleteReviewReplyActionOutputSchema } from '../output-schemas';++export const deleteReviewReply = createAction({+ name: 'delete-review-reply',+ outputSchema: deleteReviewReplyActionOutputSchema,+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Review Reply',+ description: 'Deletes the owner reply to a review.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes the business owner reply from a customer review of a Google Business Profile location. The review itself is not deleted. Use only when the user asks to take a reply down.',+ idempotent: false,+ },+ auth: googleAuth,+ props: {+ account_id: gmbApi.props.accountId(),+ location_id: gmbApi.props.locationId(),+ review_id: gmbApi.props.reviewId(),+ },+ async run(ctx) {+ await gmbApi.request<unknown>({+ accessToken: ctx.auth.access_token,+ method: HttpMethod.DELETE,+ url: `${gmbApi.resourceNames.reviewUrl(ctx.propsValue)}/reply`,+ });+ return { success: true };+ },+});diff --git a/packages/pieces/community/google-my-business/src/lib/actions/get-location-verification-state.ts b/packages/pieces/community/google-my-business/src/lib/actions/get-location-verification-state.tsnew file mode 100644index 00000000000..3302d9ba17a--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/get-location-verification-state.ts@@ -0,0 +1,31 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { getLocationVerificationStateActionOutputSchema } from '../output-schemas';++export const getLocationVerificationState = createAction({+ name: 'get-location-verification-state',+ outputSchema: getLocationVerificationStateActionOutputSchema,+ classification: 'READ',+ displayName: 'Get Location Verification State',+ description: 'Gets whether a location is verified and can publish changes.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the Voice of Merchant state of a Google Business Profile location: whether the owner has control (hasVoiceOfMerchant), whether a verification is pending, and what to do otherwise. Use to explain why edits, posts or metrics fail on an unverified location. Read-only and safe to repeat.',+ idempotent: true,+ },+ auth: googleAuth,+ props: {+ location_id: gmbApi.props.locationId(),+ },+ async run(ctx) {+ const location = gmbApi.resourceNames.v1Location(ctx.propsValue.location_id);+ return gmbApi.request<Record<string, unknown>>({+ accessToken: ctx.auth.access_token,+ method: HttpMethod.GET,+ url: `${gmbApi.hosts.verifications}/${location}/VoiceOfMerchantState`,+ });+ },+});diff --git a/packages/pieces/community/google-my-business/src/lib/actions/get-location.ts b/packages/pieces/community/google-my-business/src/lib/actions/get-location.tsnew file mode 100644index 00000000000..a05c7c0df86--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/get-location.ts@@ -0,0 +1,32 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { getLocationActionOutputSchema } from '../output-schemas';++export const getLocation = createAction({+ name: 'get-location',+ outputSchema: getLocationActionOutputSchema,+ classification: 'READ',+ displayName: 'Get Location',+ description: 'Gets the details of a business location.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one Google Business Profile location: title, store code, address, phone numbers, website, regular and special hours, categories, labels, description and metadata (placeId, Maps URL). Use to read the current listing before editing it. Read-only and safe to repeat.',+ idempotent: true,+ },+ auth: googleAuth,+ props: {+ location_id: gmbApi.props.locationId(),+ },+ async run(ctx) {+ const location = gmbApi.resourceNames.v1Location(ctx.propsValue.location_id);+ return gmbApi.request<Record<string, unknown>>({+ accessToken: ctx.auth.access_token,+ method: HttpMethod.GET,+ url: `${gmbApi.hosts.businessInformation}/${location}`,+ query: new URLSearchParams({ readMask: gmbApi.locationReadMask }),+ });+ },+});diff --git a/packages/pieces/community/google-my-business/src/lib/actions/get-media.ts b/packages/pieces/community/google-my-business/src/lib/actions/get-media.tsnew file mode 100644index 00000000000..39e74290d0b--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/get-media.ts@@ -0,0 +1,39 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { getMediaActionOutputSchema } from '../output-schemas';++export const getMedia = createAction({+ name: 'get-media',+ outputSchema: getMediaActionOutputSchema,+ classification: 'READ',+ displayName: 'Get Media',+ description: 'Gets one photo or video of a location.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one photo or video of a Google Business Profile location with its format, Google URL, thumbnail, category and view count. Read-only and safe to repeat.',+ idempotent: true,+ },+ auth: googleAuth,+ props: {+ account_id: gmbApi.props.accountId(),+ location_id: gmbApi.props.locationId(),+ media_id: Property.ShortText({+ displayName: 'Media ID',+ description: 'The media key: the last segment of the name field returned by List Media (list-media).',+ required: true,+ }),+ },+ async run(ctx) {+ const { account_id, location_id, media_id } = ctx.propsValue;+ const parent = gmbApi.resourceNames.v4Location({ account: account_id, location: location_id });+ const media = gmbApi.resourceNames.childId({ value: media_id, marker: 'media' });+ return gmbApi.request<Record<string, unknown>>({+ accessToken: ctx.auth.access_token,+ method: HttpMethod.GET,+ url: `${gmbApi.hosts.v4}/${parent}/media/${encodeURIComponent(media)}`,+ });+ },+});diff --git a/packages/pieces/community/google-my-business/src/lib/actions/get-review.ts b/packages/pieces/community/google-my-business/src/lib/actions/get-review.tsnew file mode 100644index 00000000000..3f348033daa--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/get-review.ts@@ -0,0 +1,32 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { getReviewActionOutputSchema } from '../output-schemas';++export const getReview = createAction({+ name: 'get-review',+ outputSchema: getReviewActionOutputSchema,+ classification: 'READ',+ displayName: 'Get Review',+ description: 'Gets one customer review of a location.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one customer review of a Google Business Profile location with reviewer, star rating, comment, timestamps and the current owner reply if any. Use to check a review before or after replying. Read-only and safe to repeat.',+ idempotent: true,+ },+ auth: googleAuth,+ props: {+ account_id: gmbApi.props.accountId(),+ location_id: gmbApi.props.locationId(),+ review_id: gmbApi.props.reviewId(),+ },+ async run(ctx) {+ return gmbApi.request<Record<string, unknown>>({+ accessToken: ctx.auth.access_token,+ method: HttpMethod.GET,+ url: gmbApi.resourceNames.reviewUrl(ctx.propsValue),+ });+ },+});diff --git a/packages/pieces/community/google-my-business/src/lib/actions/list-accounts.ts b/packages/pieces/community/google-my-business/src/lib/actions/list-accounts.tsnew file mode 100644index 00000000000..144589cae8f--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/list-accounts.ts@@ -0,0 +1,41 @@+import { propsValidation } from '@activepieces/pieces-common';+import { createAction, isNil } from '@activepieces/pieces-framework';+import * as z from 'zod/mini';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { listAccountsActionOutputSchema } from '../output-schemas';++export const listAccounts = createAction({+ name: 'list-accounts',+ outputSchema: listAccountsActionOutputSchema,+ classification: 'SEARCH',+ displayName: 'List Accounts',+ description: 'Lists the Business Profile accounts the connected user can access.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the Google Business Profile accounts the connected Google user can manage. Each account name has the form accounts/{id}; pass it (or the bare id) as Account ID to List Locations and the review or media actions. Call this first when no account id is known. Read-only and safe to repeat.',+ idempotent: true,+ },+ auth: googleAuth,+ props: {+ max_results: gmbApi.props.maxResults(),+ },+ async run(ctx) {+ await propsValidation.validateZod(ctx.propsValue, {+ max_results: z.optional(z.number().check(z.gte(1))),+ });+ const { items, nextPageToken } = await gmbApi.paginate({+ accessToken: ctx.auth.access_token,+ url: `${gmbApi.hosts.accountManagement}/accounts`,+ itemsKey: 'accounts',+ pageSize: 20,+ maxResults: ctx.propsValue.max_results ?? 100,+ });+ return {+ accounts: items,+ count: items.length,+ ...(isNil(nextPageToken) ? {} : { next_page_token: nextPageToken }),+ };+ },+});diff --git a/packages/pieces/community/google-my-business/src/lib/actions/list-locations.ts b/packages/pieces/community/google-my-business/src/lib/actions/list-locations.tsnew file mode 100644index 00000000000..8e0ac6cc159--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/list-locations.ts@@ -0,0 +1,44 @@+import { propsValidation } from '@activepieces/pieces-common';+import { createAction, isNil } from '@activepieces/pieces-framework';+import * as z from 'zod/mini';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { listLocationsActionOutputSchema } from '../output-schemas';++export const listLocations = createAction({+ name: 'list-locations',+ outputSchema: listLocationsActionOutputSchema,+ classification: 'SEARCH',+ displayName: 'List Locations',+ description: 'Lists the business locations of an account.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the business locations under a Google Business Profile account, with title, address, phone, website, hours, categories, description and placeId. Each location name has the form locations/{id}; pass it (or the bare id) as Location ID to the location, review, media and post actions. Read-only and safe to repeat.',+ idempotent: true,+ },+ auth: googleAuth,+ props: {+ account_id: gmbApi.props.accountId(),+ max_results: gmbApi.props.maxResults(),+ },+ async run(ctx) {+ await propsValidation.validateZod(ctx.propsValue, {+ max_results: z.optional(z.number().check(z.gte(1))),+ });+ const account = gmbApi.resourceNames.accountName(ctx.propsValue.account_id);+ const { items, nextPageToken } = await gmbApi.paginate({+ accessToken: ctx.auth.access_token,+ url: `${gmbApi.hosts.businessInformation}/${account}/locations`,+ query: new URLSearchParams({ readMask: gmbApi.locationReadMask }),+ itemsKey: 'locations',+ pageSize: 100,+ maxResults: ctx.propsValue.max_results ?? 100,+ });+ return {+ locations: items,+ count: items.length,+ ...(isNil(nextPageToken) ? {} : { next_page_token: nextPageToken }),+ };+ },+});diff --git a/packages/pieces/community/google-my-business/src/lib/actions/list-media.ts b/packages/pieces/community/google-my-business/src/lib/actions/list-media.tsnew file mode 100644index 00000000000..45478f88e6b--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/list-media.ts@@ -0,0 +1,46 @@+import { propsValidation } from '@activepieces/pieces-common';+import { createAction, isNil } from '@activepieces/pieces-framework';+import * as z from 'zod/mini';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { listMediaActionOutputSchema } from '../output-schemas';++export const listMedia = createAction({+ name: 'list-media',+ outputSchema: listMediaActionOutputSchema,+ classification: 'SEARCH',+ displayName: 'List Media',+ description: 'Lists the photos and videos of a location.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the photos and videos attached to a Google Business Profile location with format, Google URL, category and view count, plus the total media count. The last segment of each media name is the Media ID for Get Media. Read-only and safe to repeat.',+ idempotent: true,+ },+ auth: googleAuth,+ props: {+ account_id: gmbApi.props.accountId(),+ location_id: gmbApi.props.locationId(),+ max_results: gmbApi.props.maxResults(),+ },+ async run(ctx) {+ await propsValidation.validateZod(ctx.propsValue, {+ max_results: z.optional(z.number().check(z.gte(1))),+ });+ const { account_id, location_id, max_results } = ctx.propsValue;+ const parent = gmbApi.resourceNames.v4Location({ account: account_id, location: location_id });+ const { items, nextPageToken, lastPage } = await gmbApi.paginate({+ accessToken: ctx.auth.access_token,+ url: `${gmbApi.hosts.v4}/${parent}/media`,+ itemsKey: 'mediaItems',+ pageSize: 100,+ maxResults: max_results ?? 100,+ });+ return {+ media_items: items,+ count: items.length,+ total_media_item_count: lastPage['totalMediaItemCount'] ?? 0,+ ...(isNil(nextPageToken) ? {} : { next_page_token: nextPageToken }),+ };+ },+});diff --git a/packages/pieces/community/google-my-business/src/lib/actions/list-reviews.ts b/packages/pieces/community/google-my-business/src/lib/actions/list-reviews.tsnew file mode 100644index 00000000000..b76812d86cf--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/list-reviews.ts@@ -0,0 +1,60 @@+import { propsValidation } from '@activepieces/pieces-common';+import { createAction, isNil, Property } from '@activepieces/pieces-framework';+import * as z from 'zod/mini';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { listReviewsActionOutputSchema } from '../output-schemas';++export const listReviews = createAction({+ name: 'list-reviews',+ outputSchema: listReviewsActionOutputSchema,+ classification: 'SEARCH',+ displayName: 'List Reviews',+ description: 'Lists the customer reviews of a location.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists customer reviews of a Google Business Profile location with reviewer, star rating (ONE to FIVE), comment, timestamps and any existing owner reply, plus the location average rating and total review count. Each review has a reviewId to pass to Get Review, Reply to Review or Delete Review Reply. Read-only and safe to repeat.',+ idempotent: true,+ },+ auth: googleAuth,+ props: {+ account_id: gmbApi.props.accountId(),+ location_id: gmbApi.props.locationId(),+ order_by: Property.StaticDropdown({+ displayName: 'Order By',+ description: 'Sort order. Google defaults to newest first when unset.',+ required: false,+ options: {+ options: [+ { label: 'Newest first', value: 'updateTime desc' },+ { label: 'Lowest rating first', value: 'rating' },+ { label: 'Highest rating first', value: 'rating desc' },+ ],+ },+ }),+ max_results: gmbApi.props.maxResults(),+ },+ async run(ctx) {+ await propsValidation.validateZod(ctx.propsValue, {+ max_results: z.optional(z.number().check(z.gte(1))),+ });+ const { account_id, location_id, order_by, max_results } = ctx.propsValue;+ const parent = gmbApi.resourceNames.v4Location({ account: account_id, location: location_id });+ const { items, nextPageToken, lastPage } = await gmbApi.paginate({+ accessToken: ctx.auth.access_token,+ url: `${gmbApi.hosts.v4}/${parent}/reviews`,+ query: new URLSearchParams(isNil(order_by) ? {} : { orderBy: order_by }),+ itemsKey: 'reviews',+ pageSize: 50,+ maxResults: max_results ?? 100,+ });+ return {+ reviews: items,+ count: items.length,+ average_rating: lastPage['averageRating'] ?? null,+ total_review_count: lastPage['totalReviewCount'] ?? 0,+ ...(isNil(nextPageToken) ? {} : { next_page_token: nextPageToken }),+ };+ },+});diff --git a/packages/pieces/community/google-my-business/src/lib/actions/reply-to-review.ts b/packages/pieces/community/google-my-business/src/lib/actions/reply-to-review.tsnew file mode 100644index 00000000000..20414bfbfc9--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/reply-to-review.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { replyToReviewActionOutputSchema } from '../output-schemas';++export const replyToReview = createAction({+ name: 'reply-to-review',+ outputSchema: replyToReviewActionOutputSchema,+ classification: 'WRITE',+ displayName: 'Reply to Review',+ description: 'Creates or replaces the owner reply to a review.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Posts the business owner reply to a customer review of a Google Business Profile location, replacing any existing reply. The reply is public on Google Maps and Search. Safe to repeat with the same comment since it upserts.',+ idempotent: true,+ },+ auth: googleAuth,+ props: {+ account_id: gmbApi.props.accountId(),+ location_id: gmbApi.props.locationId(),+ review_id: gmbApi.props.reviewId(),+ comment: Property.LongText({+ displayName: 'Comment',+ description: 'The reply text.',+ required: true,+ }),+ },+ async run(ctx) {+ return gmbApi.request<Record<string, unknown>>({+ accessToken: ctx.auth.access_token,+ method: HttpMethod.PUT,+ url: `${gmbApi.resourceNames.reviewUrl(ctx.propsValue)}/reply`,+ body: { comment: ctx.propsValue.comment },+ });+ },+});diff --git a/packages/pieces/community/google-my-business/src/lib/actions/update-location.ts b/packages/pieces/community/google-my-business/src/lib/actions/update-location.tsnew file mode 100644index 00000000000..265f3a487e5--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/actions/update-location.ts@@ -0,0 +1,72 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, isNil, Property } from '@activepieces/pieces-framework';+import { googleAuth } from '../..';+import { gmbApi } from '../common/client';+import { updateLocationActionOutputSchema } from '../output-schemas';++export const updateLocation = createAction({+ name: 'update-location',+ outputSchema: updateLocationActionOutputSchema,+ classification: 'WRITE',+ displayName: 'Update Location',+ description: 'Updates the website, labels or store code of a business location.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates selected fields of a Google Business Profile location; only the fields you supply are changed and everything else is left untouched. Website is public and appears on Google Maps and Search, so change it only when the user explicitly asks. Labels replaces the whole label set, so include every label you want to keep; an empty list is ignored and cannot clear them. Store Code is internal. Empty text fields are ignored. Description, phone, hours, address and categories cannot be edited here. Safe to repeat with the same values.',+ idempotent: true,+ },+ auth: googleAuth,+ props: {+ location_id: gmbApi.props.locationId(),+ website_uri: Property.ShortText({+ displayName: 'Website',+ description: 'The public website URL of the business.',+ required: false,+ }),+ labels: Property.Array({+ displayName: 'Labels',+ description: 'Internal labels for the location. Replaces the existing labels. Leave empty to keep the current labels; this action cannot clear them.',+ required: false,+ }),+ store_code: Property.ShortText({+ displayName: 'Store Code',+ description: 'Your internal identifier for the location.',+ required: false,+ }),+ },+ async run(ctx) {+ const { location_id, website_uri, labels, store_code } = ctx.propsValue;+ const websiteValue = nonBlank(website_uri);+ const storeCodeValue = nonBlank(store_code);+ const suppliedLabels = isNil(labels)+ ? []+ : labels.filter((label): label is string => typeof label === 'string' && label.trim().length > 0);+ const labelValues = suppliedLabels.length === 0 ? undefined : suppliedLabels;+ const patches: Patch[] = [+ ...(isNil(websiteValue) ? [] : [{ mask: 'websiteUri', body: { websiteUri: websiteValue } }]),+ ...(isNil(labelValues) ? [] : [{ mask: 'labels', body: { labels: labelValues } }]),+ ...(isNil(storeCodeValue) ? [] : [{ mask: 'storeCode', body: { storeCode: storeCodeValue } }]),+ ];+ if (patches.length === 0) {+ throw new Error('Provide at least one field to update: website_uri, labels or store_code.');+ }+ const location = gmbApi.resourceNames.v1Location(location_id);+ return gmbApi.request<Record<string, unknown>>({+ accessToken: ctx.auth.access_token,+ method: HttpMethod.PATCH,+ url: `${gmbApi.hosts.businessInformation}/${location}`,+ query: new URLSearchParams({ updateMask: patches.map((patch) => patch.mask).join(',') }),+ body: patches.reduce<Record<string, unknown>>((acc, patch) => ({ ...acc, ...patch.body }), {}),+ });+ },+});++function nonBlank(value: string | undefined): string | undefined {+ return isNil(value) || value.trim().length === 0 ? undefined : value;+}++type Patch = {+ mask: string;+ body: Record<string, unknown>;+};diff --git a/packages/pieces/community/google-my-business/src/lib/common/client.ts b/packages/pieces/community/google-my-business/src/lib/common/client.tsnew file mode 100644index 00000000000..829d4e9e88b--- /dev/null+++ b/packages/pieces/community/google-my-business/src/lib/common/client.ts@@ -0,0 +1,192 @@+import { HttpError, HttpMethod, httpClient } from '@activepieces/pieces-common';+import { isNil, Property } from '@activepieces/pieces-framework';++export const gmbApi = {+ request,+ paginate,+ locationReadMask:+ 'name,title,storeCode,languageCode,phoneNumbers,categories,storefrontAddress,websiteUri,regularHours,specialHours,serviceArea,labels,latlng,openInfo,metadata,profile',+ resourceNames: { accountName, v1Location, v4Location, childId, reviewUrl },+ props: {+ accountId: () =>+ Property.ShortText({+ displayName: 'Account ID',+ description: 'The account id, e.g. 123 or accounts/123. Get it from the name field returned by List Accounts (list-accounts).',+ required: true,+ }),+ locationId: () =>+ Property.ShortText({+ displayName: 'Location ID',+ description: 'The location id, e.g. 456 or locations/456. Get it from the name field returned by List Locations (list-locations).',+ required: true,+ }),+ reviewId: () =>+ Property.ShortText({+ displayName: 'Review ID',+ description: 'The reviewId field returned by List Reviews (list-reviews), or the full review name.',+ required: true,+ }),+ maxResults: () =>+ Property.Number({+ displayName: 'Maximum Results',+ description: 'Stop after this many items. Larger values are fetched over several requests.',+ required: false,+ defaultValue: 100,+ }),+ },+ hosts: {+ accountManagement: 'https://mybusinessaccountmanagement.googleapis.com/v1',+ businessInformation: 'https://mybusinessbusinessinformation.googleapis.com/v1',+ v4: 'https://mybusiness.googleapis.com/v4',+ verifications: 'https://mybusinessverifications.googleapis.com/v1',+ },+};+++async function request<T>({ accessToken, method, url, query, body }: RequestParams): Promise<T> {+ const queryString = isNil(query) ? '' : query.toString();+ try {+ const response = await httpClient.sendRequest<T>({+ method,+ url: queryString.length > 0 ? `${url}?${queryString}` : url,+ headers: { Authorization: `Bearer ${accessToken}` },+ ...(isNil(body) ? {} : { body }),+ });+ return response.body;+ } catch (error) {+ if (error instanceof HttpError) {+ throw new Error(buildErrorMessage({ status: error.response.status, body: error.response.body }));+ }+ throw error;+ }+}++async function paginate({ accessToken, url, query, itemsKey, pageSize, maxResults }: PaginateParams): Promise<PaginateResult> {+ const items: unknown[] = [];+ let pageToken: string | undefined;+ let lastPage: Record<string, unknown> = {};+ do {+ const params = new URLSearchParams(query);+ params.set('pageSize', String(Math.min(maxResults - items.length, pageSize)));+ if (!isNil(pageToken)) {+ params.set('pageToken', pageToken);+ }+ lastPage = await request<Record<string, unknown>>({ accessToken, method: HttpMethod.GET, url, query: params });+ const pageItems = lastPage[itemsKey];+ if (Array.isArray(pageItems)) {+ items.push(...pageItems);+ }+ const next = lastPage['nextPageToken'];+ pageToken = typeof next === 'string' && next.length > 0 ? next : undefined;+ } while (!isNil(pageToken) && items.length < maxResults);+ return { items: items.slice(0, maxResults), nextPageToken: pageToken, lastPage };+}++function buildErrorMessage({ status, body }: { status: number; body: unknown }): string {+ const vendor = readVendorError(body);+ const vendorMessage = vendor.message ?? 'Unknown error';+ const suffix = `(status ${status}${isNil(vendor.status) ? '' : ` ${vendor.status}`}): ${vendorMessage}`;+ if (status === 403) {+ const disabled = vendor.reasons.some((reason) => reason === 'SERVICE_DISABLED' || reason === 'accessNotConfigured');+ if (disabled) {+ return `This Business Profile API is not enabled for the connection's Google project ${suffix}`;+ }+ return `The connected Google account does not manage this account or location ${suffix}`;+ }+ if (status === 404) {+ return `Not found; check the account, location or resource id format ${suffix}`;+ }+ if (status === 429) {+ return `Google Business Profile API quota exceeded; retry later ${suffix}`;+ }+ if (status === 400 && vendor.status === 'FAILED_PRECONDITION') {+ return `Precondition failed; the location may be unverified ${suffix}`;+ }+ return `Google Business Profile request failed ${suffix}`;+}++function readVendorError(body: unknown): VendorError {+ const empty: VendorError = { message: undefined, status: undefined, reasons: [] };+ if (!isRecord(body) || !isRecord(body['error'])) {+ return empty;+ }+ const error = body['error'];+ const details = Array.isArray(error['details']) ? error['details'] : [];+ const errors = Array.isArray(error['errors']) ? error['errors'] : [];+ const reasons = [...details, ...errors]+ .filter(isRecord)+ .map((item) => item['reason'])+ .filter((reason): reason is string => typeof reason === 'string');+ return {+ message: typeof error['message'] === 'string' ? error['message'] : undefined,+ status: typeof error['status'] === 'string' ? error['status'] : undefined,+ reasons,+ };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function lastSegment({ value, marker }: { value: string; marker: string }): string {+ const trimmed = value.trim().replace(/^\/+|\/+$/g, '');+ const parts = trimmed.split('/');+ const index = parts.lastIndexOf(marker);+ if (index >= 0 && index + 1 < parts.length) {+ return parts[index + 1];+ }+ return parts[parts.length - 1];+}++function accountName(account: string): string {+ return `accounts/${lastSegment({ value: account, marker: 'accounts' })}`;+}++function v1Location(location: string): string {+ return `locations/${lastSegment({ value: location, marker: 'locations' })}`;+}++function v4Location({ account, location }: { account: string; location: string }): string {+ return `${accountName(account)}/${v1Location(location)}`;+}++function childId({ value, marker }: { value: string; marker: string }): string {+ return lastSegment({ value, marker });+}++function reviewUrl({ account_id, location_id, review_id }: { account_id: string; location_id: string; review_id: string }): string {+ const parent = v4Location({ account: account_id, location: location_id });+ const review = childId({ value: review_id, marker: 'reviews' });+ return `https://mybusiness.googleapis.com/v4/${parent}/reviews/${encodeURIComponent(review)}`;+}+++type RequestParams = {+ accessToken: string;+ method: HttpMethod;+ url: string;+ query?: URLSearchParams;+ body?: Record<string, unknown>;+};++type PaginateParams = {+ accessToken: string;+ url: string;+ query?: URLSearchParams;+ itemsKey: string;+ pageSize: number;+ maxResults: number;+};++type PaginateResult = {+ items: unknown[];+ nextPageToken: string | undefined;+ lastPage: Record<string, unknown>;+};++type VendorError = {+ message: string | undefined;+ status: string | undefined;+ reasons: string[];+};+diff --git a/packages/pieces/community/google-my-business/src/lib/output-schemas.ts b/packages/pieces/community/google-my-business/src/lib/output-schemas.tsindex bb18579d60f..7bdbe7cbca2 100644--- a/packages/pieces/community/google-my-business/src/lib/output-schemas.ts+++ b/packages/pieces/community/google-my-business/src/lib/output-schemas.ts@@ -58,6 +58,146 @@ const localPostFields: OutputSchema['fields'] = [},];+const accountFields: OutputSchema['fields'] = [+ { key: 'name', label: 'Account Name' },+ { key: 'accountName', label: 'Display Name' },+ { key: 'type', label: 'Account Type' },+ { key: 'role', label: 'Role' },+ { key: 'verificationState', label: 'Verification State' },+ { key: 'vettedState', label: 'Vetted State' },+];++const locationFields: OutputSchema['fields'] = [+ { key: 'name', label: 'Location Name' },+ { key: 'title', label: 'Title' },+ { key: 'storeCode', label: 'Store Code' },+ { key: 'languageCode', label: 'Language Code' },+ { key: 'websiteUri', label: 'Website', format: 'url' },+ { key: 'labels', label: 'Labels' },+ {+ key: 'regularHours',+ label: 'Regular Hours',+ children: [+ {+ key: 'periods',+ label: 'Periods',+ listItems: [+ { key: 'openDay', label: 'Open Day' },+ { key: 'openTime', label: 'Open Time', children: [{ key: 'hours', label: 'Hours', format: 'number' }] },+ { key: 'closeDay', label: 'Close Day' },+ { key: 'closeTime', label: 'Close Time', children: [{ key: 'hours', label: 'Hours', format: 'number' }] },+ ],+ },+ ],+ },+ { key: 'phoneNumbers', label: 'Phone Numbers', children: [{ key: 'primaryPhone', label: 'Primary Phone' }] },+ {+ key: 'categories',+ label: 'Categories',+ children: [+ {+ key: 'primaryCategory',+ label: 'Primary Category',+ children: [+ { key: 'name', label: 'Category Id' },+ { key: 'displayName', label: 'Category' },+ {+ key: 'serviceTypes',+ label: 'Service Types',+ labelKey: 'displayName',+ listItems: [+ { key: 'serviceTypeId', label: 'Service Type Id' },+ { key: 'displayName', label: 'Service Type' },+ ],+ },+ ],+ },+ ],+ },+ {+ key: 'storefrontAddress',+ label: 'Address',+ children: [+ { key: 'regionCode', label: 'Region Code' },+ { key: 'languageCode', label: 'Language Code' },+ { key: 'addressLines', label: 'Address Lines' },+ { key: 'postalCode', label: 'Postal Code' },+ { key: 'administrativeArea', label: 'Administrative Area' },+ { key: 'locality', label: 'Locality' },+ ],+ },+ {+ key: 'latlng',+ label: 'Coordinates',+ children: [+ { key: 'latitude', label: 'Latitude', format: 'number' },+ { key: 'longitude', label: 'Longitude', format: 'number' },+ ],+ },+ { key: 'openInfo', label: 'Open Info', children: [+ { key: 'status', label: 'Status' },+ { key: 'canReopen', label: 'Can Reopen', format: 'boolean' },+ ] },+ {+ key: 'metadata',+ label: 'Metadata',+ children: [+ { key: 'placeId', label: 'Place Id' },+ { key: 'mapsUri', label: 'Maps URL', format: 'url' },+ { key: 'newReviewUri', label: 'New Review URL', format: 'url' },+ { key: 'hasVoiceOfMerchant', label: 'Has Voice Of Merchant', format: 'boolean' },+ { key: 'canDelete', label: 'Can Delete', format: 'boolean' },+ { key: 'canModifyServiceList', label: 'Can Modify Service List', format: 'boolean' },+ ],+ },+ { key: 'profile', label: 'Profile', children: [{ key: 'description', label: 'Description' }] },+];++const reviewFields: OutputSchema['fields'] = [+ { key: 'name', label: 'Review Name' },+ { key: 'reviewId', label: 'Review Id' },+ { key: 'reviewReplyUrl', label: 'Review Reply URL', format: 'url' },+ {+ key: 'reviewer',+ label: 'Reviewer',+ children: [+ { key: 'displayName', label: 'Display Name' },+ { key: 'profilePhotoUrl', label: 'Profile Photo', format: 'url' },+ ],+ },+ { key: 'starRating', label: 'Star Rating' },+ { key: 'comment', label: 'Comment' },+ { key: 'createTime', label: 'Created At', format: 'datetime' },+ { key: 'updateTime', label: 'Updated At', format: 'datetime' },+ {+ key: 'reviewReply',+ label: 'Reply',+ children: [+ { key: 'comment', label: 'Reply Comment' },+ { key: 'updateTime', label: 'Reply Updated At', format: 'datetime' },+ ],+ },+];++const mediaFields: OutputSchema['fields'] = [+ { key: 'name', label: 'Media Name' },+ { key: 'mediaFormat', label: 'Media Format' },+ { key: 'googleUrl', label: 'Google URL', format: 'url' },+ { key: 'thumbnailUrl', label: 'Thumbnail URL', format: 'url' },+ {+ key: 'dimensions',+ label: 'Dimensions',+ children: [+ { key: 'widthPixels', label: 'Width Pixels', format: 'number' },+ { key: 'heightPixels', label: 'Height Pixels', format: 'number' },+ ],+ },+ { key: 'createTime', label: 'Created At', format: 'datetime' },+ { key: 'description', label: 'Description' },+ { key: 'locationAssociation', label: 'Location Association', children: [{ key: 'category', label: 'Category' }] },+ { key: 'insights', label: 'Insights', children: [{ key: 'viewCount', label: 'View Count' }] },+];+export const createPostActionOutputSchema: OutputSchema = { fields: localPostFields };export const getPostActionOutputSchema: OutputSchema = { fields: localPostFields };export const updatePostActionOutputSchema: OutputSchema = { fields: localPostFields };@@ -67,3 +207,63 @@ export const listPostsActionOutputSchema: OutputSchema = {{ key: 'nextPageToken', label: 'Next Page Token' },],};+export const listAccountsActionOutputSchema: OutputSchema = {+ fields: [+ { key: 'accounts', label: 'Accounts', labelKey: 'accountName', listItems: accountFields },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'next_page_token', label: 'Next Page Token' },+ ],+};+export const listLocationsActionOutputSchema: OutputSchema = {+ fields: [+ { key: 'locations', label: 'Locations', labelKey: 'title', listItems: locationFields },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'next_page_token', label: 'Next Page Token' },+ ],+};+export const getLocationActionOutputSchema: OutputSchema = { fields: locationFields };+export const updateLocationActionOutputSchema: OutputSchema = { fields: locationFields };+export const listReviewsActionOutputSchema: OutputSchema = {+ fields: [+ { key: 'reviews', label: 'Reviews', labelKey: 'comment', listItems: reviewFields },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'average_rating', label: 'Average Rating', format: 'number' },+ { key: 'total_review_count', label: 'Total Review Count', format: 'number' },+ { key: 'next_page_token', label: 'Next Page Token' },+ ],+};+export const getReviewActionOutputSchema: OutputSchema = { fields: reviewFields };+export const replyToReviewActionOutputSchema: OutputSchema = {+ fields: [+ { key: 'comment', label: 'Reply Comment' },+ { key: 'updateTime', label: 'Updated At', format: 'datetime' },+ ],+};+export const deleteReviewReplyActionOutputSchema: OutputSchema = {+ fields: [{ key: 'success', label: 'Success', format: 'boolean' }],+};+export const getLocationVerificationStateActionOutputSchema: OutputSchema = {+ fields: [+ { key: 'hasVoiceOfMerchant', label: 'Has Voice Of Merchant', format: 'boolean' },+ { key: 'hasBusinessAuthority', label: 'Has Business Authority', format: 'boolean' },+ {+ key: 'verify',+ label: 'Verify',+ children: [{ key: 'hasPendingVerification', label: 'Has Pending Verification', format: 'boolean' }],+ },+ {+ key: 'complyWithGuidelines',+ label: 'Comply With Guidelines',+ children: [{ key: 'recommendationReason', label: 'Recommendation Reason' }],+ },+ ],+};+export const listMediaActionOutputSchema: OutputSchema = {+ fields: [+ { key: 'media_items', label: 'Media Items', labelKey: 'name', listItems: mediaFields },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'total_media_item_count', label: 'Total Media Item Count', format: 'number' },+ { key: 'next_page_token', label: 'Next Page Token' },+ ],+};+export const getMediaActionOutputSchema: OutputSchema = { fields: mediaFields };diff --git a/packages/pieces/community/google-my-business/src/lib/triggers/new-review.ts b/packages/pieces/community/google-my-business/src/lib/triggers/new-review.tsindex fe027c12791..9130f579bb5 100644--- a/packages/pieces/community/google-my-business/src/lib/triggers/new-review.ts+++ b/packages/pieces/community/google-my-business/src/lib/triggers/new-review.ts@@ -34,18 +34,10 @@ export const newReview = createTrigger({return await pollingHelper.test(polling, ctx);},async onEnable(ctx) {- await pollingHelper.onEnable(polling, {- auth: ctx.auth,- store: ctx.store,- propsValue: ctx.propsValue,- });+ await pollingHelper.onEnable(polling, ctx);},async onDisable(ctx) {- await pollingHelper.onDisable(polling, {- auth: ctx.auth,- store: ctx.store,- propsValue: ctx.propsValue,- });+ await pollingHelper.onDisable(polling, ctx);},async run(ctx) {return await pollingHelper.poll(polling, ctx);@@ -84,7 +76,7 @@ const getResponse = async (Authorization: `Bearer ${authentication.access_token}`,},queryParams: {- pageSize: '100',+ pageSize: '50',orderBy: 'updateTime desc',},});diff --git a/packages/pieces/community/imap/package.json b/packages/pieces/community/imap/package.jsonindex c139c20b9d9..e8afe53f125 100644--- a/packages/pieces/community/imap/package.json+++ b/packages/pieces/community/imap/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-imap",- "version": "0.4.9",+ "version": "0.5.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/imap/src/i18n/translation.json b/packages/pieces/community/imap/src/i18n/translation.jsonindex 2b4fee9bad4..1cbbf78ed95 100644--- a/packages/pieces/community/imap/src/i18n/translation.json+++ b/packages/pieces/community/imap/src/i18n/translation.json@@ -38,5 +38,108 @@"Trigger when a new email is received": "Trigger when a new email is received","Mailbox": "Mailbox","Select the mailbox to search.": "Select the mailbox to search.",- "\n**Emails Filtering:**\n\nAdd a Router Piece to filter emails based on the subject, to, from, cc or other fields.\n": "\n**Emails Filtering:**\n\nAdd a Router Piece to filter emails based on the subject, to, from, cc or other fields.\n"-}\ No newline at end of file+ "\n**Emails Filtering:**\n\nAdd a Router Piece to filter emails based on the subject, to, from, cc or other fields.\n": "\n**Emails Filtering:**\n\nAdd a Router Piece to filter emails based on the subject, to, from, cc or other fields.\n",+ "List Folders": "List Folders",+ "Lists every folder in the mailbox.": "Lists every folder in the mailbox.",+ "Include Message Counts": "Include Message Counts",+ "Also return the total and unread message count of each folder. Slower on accounts with many folders.": "Also return the total and unread message count of each folder. Slower on accounts with many folders.",+ "Get Folder Status": "Get Folder Status",+ "Gets message counts and UID information for a folder.": "Gets message counts and UID information for a folder.",+ "Folder": "Folder",+ "Folder path from list_folders.": "Folder path from list_folders.",+ "Create Folder": "Create Folder",+ "Creates a folder, optionally inside a parent folder.": "Creates a folder, optionally inside a parent folder.",+ "Folder Name": "Folder Name",+ "Name of the new folder. Must not contain the server folder separator; use Parent Folder for nesting.": "Name of the new folder. Must not contain the server folder separator; use Parent Folder for nesting.",+ "Optional existing folder path from list_folders to create the folder inside.": "Optional existing folder path from list_folders to create the folder inside.",+ "Rename Folder": "Rename Folder",+ "Renames or moves a folder to a new path.": "Renames or moves a folder to a new path.",+ "Current folder path from list_folders.": "Current folder path from list_folders.",+ "New Path": "New Path",+ "Full new path, using the folder separator from list_folders for nesting (for example \"Projects/2026\").": "Full new path, using the folder separator from list_folders for nesting (for example \"Projects/2026\").",+ "Delete Folder": "Delete Folder",+ "Permanently deletes a folder and the emails in it.": "Permanently deletes a folder and the emails in it.",+ "Get Quota": "Get Quota",+ "Gets the storage and message quota for a folder.": "Gets the storage and message quota for a folder.",+ "Search Emails": "Search Emails",+ "Searches a folder and returns matching email summaries, newest first.": "Searches a folder and returns matching email summaries, newest first.",+ "From": "From",+ "Text contained in the From header.": "Text contained in the From header.",+ "To": "To",+ "Text contained in the To header.": "Text contained in the To header.",+ "Subject": "Subject",+ "Text contained in the subject.": "Text contained in the subject.",+ "Body": "Body",+ "Text contained in the message body.": "Text contained in the message body.",+ "Text": "Text",+ "Text contained anywhere in the headers or body.": "Text contained anywhere in the headers or body.",+ "Message-ID": "Message-ID",+ "Exact Message-ID header value, for example <[email protected]>.": "Exact Message-ID header value, for example <[email protected]>.",+ "Received Since": "Received Since",+ "Only messages received on or after this date. Day granularity on most servers (time of day is ignored).": "Only messages received on or after this date. Day granularity on most servers (time of day is ignored).",+ "Received Before": "Received Before",+ "Only messages received before this date. Day granularity on most servers (time of day is ignored).": "Only messages received before this date. Day granularity on most servers (time of day is ignored).",+ "Read Status": "Read Status",+ "Filter by read state. Leave empty for both.": "Filter by read state. Leave empty for both.",+ "Read": "Read",+ "Unread": "Unread",+ "Flagged": "Flagged",+ "Filter by the flagged (starred) state. Leave empty for both.": "Filter by the flagged (starred) state. Leave empty for both.",+ "Not Flagged": "Not Flagged",+ "Keyword": "Keyword",+ "Only messages carrying this custom keyword (IMAP flag).": "Only messages carrying this custom keyword (IMAP flag).",+ "Limit": "Limit",+ "Maximum number of emails to return (1-100).": "Maximum number of emails to return (1-100).",+ "Get Email": "Get Email",+ "Gets the full content of one email, including attachments.": "Gets the full content of one email, including attachments.",+ "Folder path from list_folders that contains the email.": "Folder path from list_folders that contains the email.",+ "UID from search_emails in the same folder.": "UID from search_emails in the same folder.",+ "UID Validity": "UID Validity",+ "Optional uid_validity returned by search_emails. When set and the folder has changed, the call fails instead of acting on stale UIDs.": "Optional uid_validity returned by search_emails. When set and the folder has changed, the call fails instead of acting on stale UIDs.",+ "Update Email Flags": "Update Email Flags",+ "Marks emails read or unread, flagged or unflagged, answered, and adds or removes keywords.": "Marks emails read or unread, flagged or unflagged, answered, and adds or removes keywords.",+ "Folder path from list_folders that contains the emails.": "Folder path from list_folders that contains the emails.",+ "Message UIDs": "Message UIDs",+ "UIDs from search_emails in the same folder (up to 500). UIDs that no longer exist are reported in not_found_uids.": "UIDs from search_emails in the same folder (up to 500). UIDs that no longer exist are reported in not_found_uids.",+ "Leave empty to keep the current read status.": "Leave empty to keep the current read status.",+ "Mark as Unread": "Mark as Unread",+ "Leave empty to keep the current flagged status.": "Leave empty to keep the current flagged status.",+ "Flag": "Flag",+ "Unflag": "Unflag",+ "Answered": "Answered",+ "Leave empty to keep the current answered status.": "Leave empty to keep the current answered status.",+ "Mark as Answered": "Mark as Answered",+ "Mark as Not Answered": "Mark as Not Answered",+ "Add Keywords": "Add Keywords",+ "Custom keywords to add, for example \"invoice\".": "Custom keywords to add, for example \"invoice\".",+ "Remove Keywords": "Remove Keywords",+ "Custom keywords to remove.": "Custom keywords to remove.",+ "Move Emails": "Move Emails",+ "Moves emails from one folder to another.": "Moves emails from one folder to another.",+ "Existing folder path from list_folders to move the emails into.": "Existing folder path from list_folders to move the emails into.",+ "Copy Emails": "Copy Emails",+ "Copies emails into another folder, keeping the originals.": "Copies emails into another folder, keeping the originals.",+ "Existing folder path from list_folders to copy the emails into.": "Existing folder path from list_folders to copy the emails into.",+ "Move Emails to Trash": "Move Emails to Trash",+ "Moves emails to the Trash folder.": "Moves emails to the Trash folder.",+ "Archive Emails": "Archive Emails",+ "Moves emails to the Archive folder.": "Moves emails to the Archive folder.",+ "Delete Emails Permanently": "Delete Emails Permanently",+ "Permanently deletes emails. This cannot be undone.": "Permanently deletes emails. This cannot be undone.",+ "Create Draft": "Create Draft",+ "Saves a new draft email in the Drafts folder.": "Saves a new draft email in the Drafts folder.",+ "Recipients, each \"[email protected]\" or \"Name <[email protected]>\".": "Recipients, each \"[email protected]\" or \"Name <[email protected]>\".",+ "Cc": "Cc",+ "Cc recipients.": "Cc recipients.",+ "Bcc": "Bcc",+ "Bcc recipients.": "Bcc recipients.",+ "Text Body": "Text Body",+ "Plain-text body. Provide this, an HTML body, or both.": "Plain-text body. Provide this, an HTML body, or both.",+ "HTML Body": "HTML Body",+ "HTML body. Provide this, a text body, or both.": "HTML body. Provide this, a text body, or both.",+ "Sender address. Defaults to the connection username when it is an email address.": "Sender address. Defaults to the connection username when it is an email address.",+ "In Reply To": "In Reply To",+ "Message-ID of the email being answered, for example <[email protected]>.": "Message-ID of the email being answered, for example <[email protected]>.",+ "Drafts Folder": "Drafts Folder",+ "Folder path to save the draft in. Leave empty to use the Drafts folder.": "Folder path to save the draft in. Leave empty to use the Drafts folder."+}diff --git a/packages/pieces/community/imap/src/index.ts b/packages/pieces/community/imap/src/index.tsindex ce37e06509f..4fcdcac967f 100644--- a/packages/pieces/community/imap/src/index.ts+++ b/packages/pieces/community/imap/src/index.ts@@ -6,11 +6,26 @@ import { markEmailAsRead } from './lib/actions/mark-email-read';import { copyEmail } from './lib/actions/copy-email';import { deleteEmail } from './lib/actions/delete-email';import { moveEmail } from './lib/actions/move-email';+import { listFolders } from './lib/actions/list-folders';+import { getFolderStatus } from './lib/actions/get-folder-status';+import { createFolder } from './lib/actions/create-folder';+import { renameFolder } from './lib/actions/rename-folder';+import { deleteFolder } from './lib/actions/delete-folder';+import { getQuota } from './lib/actions/get-quota';+import { searchEmails } from './lib/actions/search-emails';+import { getEmail } from './lib/actions/get-email';+import { updateEmailFlags } from './lib/actions/update-email-flags';+import { moveEmails } from './lib/actions/move-emails';+import { copyEmails } from './lib/actions/copy-emails';+import { trashEmails } from './lib/actions/trash-emails';+import { archiveEmails } from './lib/actions/archive-emails';+import { deleteEmails } from './lib/actions/delete-emails';+import { createDraft } from './lib/actions/create-draft';export const imapPiece = createPiece({displayName: 'IMAP',description: 'Receive new email trigger',- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/imap.png',categories: [PieceCategory.BUSINESS_INTELLIGENCE],authors: ['kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud', 'simonc'],@@ -20,6 +35,21 @@ export const imapPiece = createPiece({copyEmail,moveEmail,deleteEmail,+ listFolders,+ getFolderStatus,+ createFolder,+ renameFolder,+ deleteFolder,+ getQuota,+ searchEmails,+ getEmail,+ updateEmailFlags,+ moveEmails,+ copyEmails,+ trashEmails,+ archiveEmails,+ deleteEmails,+ createDraft,],triggers: [newEmail],});diff --git a/packages/pieces/community/imap/src/lib/actions/archive-emails.ts b/packages/pieces/community/imap/src/lib/actions/archive-emails.tsnew file mode 100644index 00000000000..e9b6a381f5a--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/archive-emails.ts@@ -0,0 +1,65 @@+import { createAction } from '@activepieces/pieces-framework';+import {+ imapAuth,+ performImapOperation,+ transferInFolder,+ resolveSpecialFolder,+ parseUids,+ samePath,+ folderProp,+ uidsProp,+ uidValidityProp,+ ImapError,+} from '../common';+import { archiveEmailsOutputSchema } from '../output-schemas';++export const archiveEmails = createAction({+ auth: imapAuth,+ name: 'archive_emails',+ classification: 'WRITE',+ displayName: 'Archive Emails',+ description: 'Moves emails to the Archive folder.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Moves one or more emails by UID out of a folder into the mailbox Archive folder, found automatically (on Gmail, All Mail). When special_use_source is "name", the Archive folder was guessed from its name. Fails, naming move_emails, if no Archive folder exists. uid_validity is required and must come from the search_emails call that produced these UIDs; a mismatch fails the call so stale UIDs cannot archive the wrong emails. Not idempotent: archived UIDs are gone from the source.',+ idempotent: false,+ },+ props: {+ folder: folderProp({+ displayName: 'Folder',+ description: 'Folder path from list_folders that contains the emails.',+ }),+ uids: uidsProp(),+ uid_validity: uidValidityProp({ required: true }),+ },+ outputSchema: archiveEmailsOutputSchema,+ async run({ auth, propsValue }) {+ const uids = parseUids({ uids: propsValue.uids });+ const sourceFolder = propsValue.folder.trim();+ return performImapOperation(auth, async (client) => {+ const archive = await resolveSpecialFolder({ client, role: 'archive' });+ if (!archive) {+ throw new ImapError(+ 'No Archive folder was found on this server. Use move_emails with an explicit target folder.'+ );+ }+ if (samePath({ a: sourceFolder, b: archive.path })) {+ throw new ImapError('These emails are already in the Archive folder.');+ }+ const result = await transferInFolder({+ client,+ sourceFolder,+ targetFolder: archive.path,+ uids,+ uidValidity: propsValue.uid_validity,+ mode: 'move',+ });+ return {+ ...result,+ destination_folder: archive.path,+ special_use_source: archive.special_use_source,+ };+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/copy-email.ts b/packages/pieces/community/imap/src/lib/actions/copy-email.tsindex bea77f86274..946162f3259 100644--- a/packages/pieces/community/imap/src/lib/actions/copy-email.ts+++ b/packages/pieces/community/imap/src/lib/actions/copy-email.ts@@ -31,7 +31,7 @@ export const copyEmail = createAction({displayName: 'Copy Email',description: 'Copy an email to another mailbox',outputSchema: copyEmailActionOutputSchema,- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Copies an email (by message UID) from a source IMAP folder into a target folder, leaving the original in place. Use to duplicate a message into another mailbox without removing it from the source. Requires the source folder, target folder, and the UID; not idempotent since each call appends another copy with a new UID.', idempotent: false },props,async run({ auth, propsValue }) {diff --git a/packages/pieces/community/imap/src/lib/actions/copy-emails.ts b/packages/pieces/community/imap/src/lib/actions/copy-emails.tsnew file mode 100644index 00000000000..f96ca490b87--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/copy-emails.ts@@ -0,0 +1,55 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import {+ imapAuth,+ performImapOperation,+ transferInFolder,+ parseUids,+ folderProp,+ uidsProp,+ uidValidityProp,+} from '../common';+import { copyEmailsOutputSchema } from '../output-schemas';++export const copyEmails = createAction({+ auth: imapAuth,+ name: 'copy_emails',+ classification: 'WRITE',+ displayName: 'Copy Emails',+ description: 'Copies emails into another folder, keeping the originals.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Copies one or more emails by UID from a source folder into an existing target folder, leaving the originals in place. Use move_emails to relocate instead of duplicate. uid_validity is required and must come from the search_emails call that produced these UIDs; a mismatch fails the call so stale UIDs cannot copy the wrong emails. UIDs that no longer exist are reported, not failed. Not idempotent: every call adds another copy.',+ idempotent: false,+ },+ props: {+ source_folder: folderProp({+ displayName: 'Source Folder',+ description: 'Folder path from list_folders that contains the emails.',+ }),+ uids: uidsProp(),+ target_folder: Property.ShortText({+ displayName: 'Target Folder',+ description: 'Existing folder path from list_folders to copy the emails into.',+ required: true,+ }),+ uid_validity: uidValidityProp({ required: true }),+ },+ outputSchema: copyEmailsOutputSchema,+ async run({ auth, propsValue }) {+ const uids = parseUids({ uids: propsValue.uids });+ const sourceFolder = propsValue.source_folder.trim();+ const targetFolder = propsValue.target_folder.trim();+ return performImapOperation(auth, async (client) => {+ const result = await transferInFolder({+ client,+ sourceFolder,+ targetFolder,+ uids,+ uidValidity: propsValue.uid_validity,+ mode: 'copy',+ });+ return { ...result, target_folder: targetFolder };+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/create-draft.ts b/packages/pieces/community/imap/src/lib/actions/create-draft.tsnew file mode 100644index 00000000000..a02d42795c4--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/create-draft.ts@@ -0,0 +1,120 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import {+ imapAuth,+ performImapOperation,+ withMailboxLock,+ selectedMailbox,+ resolveSpecialFolder,+ buildDraftMessage,+ assertHeaderSafe,+ ImapError,+} from '../common';+import { createDraftOutputSchema } from '../output-schemas';++function toStringList(values: unknown[] | undefined): string[] {+ return (values ?? []).map((value) => String(value)).filter((value) => value.trim().length > 0);+}++export const createDraft = createAction({+ auth: imapAuth,+ name: 'create_draft',+ classification: 'WRITE',+ displayName: 'Create Draft',+ description: 'Saves a new draft email in the Drafts folder.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Saves a new draft (not sent) to the mailbox Drafts folder, found automatically, or to a folder you name. IMAP cannot send mail; use an SMTP or Gmail tool to send. Set in_reply_to to a Message-ID from get_email to thread the draft as a reply (only that one Message-ID is referenced). Not idempotent: every call saves another draft.',+ idempotent: false,+ },+ props: {+ to: Property.Array({+ displayName: 'To',+ description: 'Recipients, each "[email protected]" or "Name <[email protected]>".',+ required: true,+ }),+ cc: Property.Array({ displayName: 'Cc', description: 'Cc recipients.', required: false }),+ bcc: Property.Array({ displayName: 'Bcc', description: 'Bcc recipients.', required: false }),+ subject: Property.ShortText({ displayName: 'Subject', required: false }),+ text: Property.LongText({+ displayName: 'Text Body',+ description: 'Plain-text body. Provide this, an HTML body, or both.',+ required: false,+ }),+ html: Property.LongText({+ displayName: 'HTML Body',+ description: 'HTML body. Provide this, a text body, or both.',+ required: false,+ }),+ from: Property.ShortText({+ displayName: 'From',+ description:+ 'Sender address. Defaults to the connection username when it is an email address.',+ required: false,+ }),+ in_reply_to: Property.ShortText({+ displayName: 'In Reply To',+ description: 'Message-ID of the email being answered, for example <[email protected]>.',+ required: false,+ }),+ folder: Property.ShortText({+ displayName: 'Drafts Folder',+ description: 'Folder path to save the draft in. Leave empty to use the Drafts folder.',+ required: false,+ }),+ },+ outputSchema: createDraftOutputSchema,+ async run({ auth, propsValue }) {+ const fromInput = propsValue.from?.trim();+ const username = auth.props.username;+ const from = fromInput ? fromInput : username.includes('@') ? username : '';+ if (!from) {+ throw new ImapError('Provide a From address; the connection username is not an email address.');+ }+ const folderInput = propsValue.folder?.trim();+ if (folderInput) {+ assertHeaderSafe({ field: 'Drafts folder', value: folderInput });+ }+ const date = new Date();+ const { raw, messageId } = buildDraftMessage({+ from,+ to: toStringList(propsValue.to),+ cc: toStringList(propsValue.cc),+ bcc: toStringList(propsValue.bcc),+ subject: propsValue.subject ?? '',+ text: propsValue.text ?? undefined,+ html: propsValue.html ?? undefined,+ inReplyTo: propsValue.in_reply_to ?? undefined,+ date,+ });++ return performImapOperation(auth, async (client) => {+ const drafts = folderInput+ ? folderInput+ : (await resolveSpecialFolder({ client, role: 'drafts' }))?.path;+ if (!drafts) {+ throw new ImapError(+ 'No Drafts folder was found on this server. Set Drafts Folder, or create one with create_folder.'+ );+ }+ return withMailboxLock({+ client,+ folder: drafts,+ readOnly: false,+ run: async () => {+ const result = await client.append(drafts, raw, ['\\Draft', '\\Seen'], date);+ if (!result) {+ throw new ImapError(`The server refused to save the draft in "${drafts}".`);+ }+ const mailbox = selectedMailbox({ client });+ return {+ folder: mailbox.path,+ ...(result.uid === undefined ? {} : { uid: result.uid }),+ uid_validity: (result.uidValidity ?? mailbox.uidValidity).toString(),+ message_id: messageId,+ };+ },+ });+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/create-folder.ts b/packages/pieces/community/imap/src/lib/actions/create-folder.tsnew file mode 100644index 00000000000..27984ee5dc0--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/create-folder.ts@@ -0,0 +1,69 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { imapAuth, performImapOperation, ImapError, assertHeaderSafe } from '../common';+import { createFolderOutputSchema } from '../output-schemas';++export const createFolder = createAction({+ auth: imapAuth,+ name: 'create_folder',+ classification: 'WRITE',+ displayName: 'Create Folder',+ description: 'Creates a folder, optionally inside a parent folder.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates an IMAP folder, optionally nested under an existing parent path from list_folders. Use before move_emails or copy_emails when the target folder does not exist yet. If the folder already exists it returns created=false instead of failing, so it is safe to retry.',+ idempotent: true,+ },+ props: {+ name: Property.ShortText({+ displayName: 'Folder Name',+ description:+ 'Name of the new folder. Must not contain the server folder separator; use Parent Folder for nesting.',+ required: true,+ }),+ parent_folder: Property.ShortText({+ displayName: 'Parent Folder',+ description: 'Optional existing folder path from list_folders to create the folder inside.',+ required: false,+ }),+ },+ outputSchema: createFolderOutputSchema,+ async run({ auth, propsValue }) {+ const name = propsValue.name.trim();+ const parent = propsValue.parent_folder?.trim() ?? '';+ if (!name) {+ throw new ImapError('Folder name must not be empty.');+ }+ assertHeaderSafe({ field: 'Folder name', value: name });+ return performImapOperation(auth, async (client) => {+ const folders = await client.list();+ const delimiter = folders.find((entry) => entry.delimiter)?.delimiter ?? '/';+ if (name.includes(delimiter)) {+ throw new ImapError(+ `Folder name must not contain the separator "${delimiter}"; use Parent Folder for nesting.`+ );+ }+ if (parent && !folders.some((entry) => entry.path === parent)) {+ throw new ImapError(+ `Parent folder "${parent}" does not exist; pick a path from list_folders.`+ );+ }+ const expectedPath = parent ? `${parent}${delimiter}${name}` : name;+ const existing = folders.find((entry) => entry.path === expectedPath);+ if (existing) {+ return { path: existing.path, created: false };+ }+ try {+ const result = await client.mailboxCreate(parent ? [parent, name] : name);+ return { path: result.path, created: result.created };+ } catch (error) {+ const after = await client.list();+ const match = after.find((entry) => entry.path === expectedPath);+ if (match) {+ return { path: match.path, created: false };+ }+ throw error;+ }+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/delete-email.ts b/packages/pieces/community/imap/src/lib/actions/delete-email.tsindex c44aa3b8693..001701a1363 100644--- a/packages/pieces/community/imap/src/lib/actions/delete-email.ts+++ b/packages/pieces/community/imap/src/lib/actions/delete-email.ts@@ -1,5 +1,6 @@import { createAction, Property } from '@activepieces/pieces-framework';import { imapAuth, deleteEmail as deleteImapEmail, mailboxDropdown } from '../common';+import { deleteEmailActionOutputSchema } from '../output-schemas';const permanentDeletionNotice = `**Permanent Deletion:**@@ -29,7 +30,8 @@ export const deleteEmail = createAction({classification: 'DESTRUCTIVE',displayName: 'Delete Email',description: 'Permanently delete an email',- audience: 'both',+ outputSchema: deleteEmailActionOutputSchema,+ audience: 'human',aiMetadata: { description: 'Permanently deletes an email (by message UID) from an IMAP folder; this cannot be undone and does not move the message to Trash (use Move Email for that). Use only when irreversible removal is intended. Requires the folder and the UID; destructive and not idempotent since a repeat call cannot find the already-deleted message.', idempotent: false },props,async run({ auth, propsValue }) {diff --git a/packages/pieces/community/imap/src/lib/actions/delete-emails.ts b/packages/pieces/community/imap/src/lib/actions/delete-emails.tsnew file mode 100644index 00000000000..dd6d9c76f3e--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/delete-emails.ts@@ -0,0 +1,77 @@+import { createAction } from '@activepieces/pieces-framework';+import {+ imapAuth,+ performImapOperation,+ withMailboxLock,+ selectedMailbox,+ assertUidValidity,+ assertUidPlusForDelete,+ partitionExistingUids,+ parseUids,+ folderProp,+ uidsProp,+ uidValidityProp,+ ImapError,+} from '../common';+import { deleteEmailsOutputSchema } from '../output-schemas';++export const deleteEmails = createAction({+ auth: imapAuth,+ name: 'delete_emails',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Emails Permanently',+ description: 'Permanently deletes emails. This cannot be undone.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes (expunges) one or more emails by UID; this cannot be undone. Prefer trash_emails unless permanent removal is explicitly wanted, for example emptying mail that is already in Trash. On Gmail, deleting from a label folder only removes that label. Refuses on servers without UIDPLUS, where it would expunge other messages too. uid_validity is required and must come from the search_emails call that produced these UIDs; a mismatch fails the call so stale UIDs cannot delete the wrong emails. Not idempotent: a repeat call reports the UIDs as not found.',+ idempotent: false,+ },+ props: {+ folder: folderProp({+ displayName: 'Folder',+ description: 'Folder path from list_folders that contains the emails.',+ }),+ uids: uidsProp(),+ uid_validity: uidValidityProp({ required: true }),+ },+ outputSchema: deleteEmailsOutputSchema,+ async run({ auth, propsValue }) {+ const uids = parseUids({ uids: propsValue.uids });+ const folder = propsValue.folder.trim();+ return performImapOperation(auth, async (client) => {+ assertUidPlusForDelete({ client });+ return withMailboxLock({+ client,+ folder,+ readOnly: false,+ run: async () => {+ assertUidValidity({ client, expected: propsValue.uid_validity });+ const mailbox = selectedMailbox({ client });+ const { found, notFound } = await partitionExistingUids({ client, uids });+ const range = found.join(',');+ const ok = await client.messageDelete(range, { uid: true });+ if (!ok) {+ throw new ImapError('The server refused to delete the emails.');+ }+ const remaining = await client.search({ uid: range }, { uid: true });+ if (remaining === false) {+ throw new ImapError('The delete ran, but the server rejected the follow-up check.');+ }+ const stillPresent = new Set(remaining);+ const deleted = found.filter((uid) => !stillPresent.has(uid));+ const notDeleted = found.filter((uid) => stillPresent.has(uid));+ if (deleted.length === 0) {+ throw new ImapError('The server did not delete any of the emails.');+ }+ return {+ folder: mailbox.path,+ deleted_uids: deleted,+ not_deleted_uids: notDeleted,+ not_found_uids: notFound,+ };+ },+ });+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/delete-folder.ts b/packages/pieces/community/imap/src/lib/actions/delete-folder.tsnew file mode 100644index 00000000000..9c0af13e2b0--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/delete-folder.ts@@ -0,0 +1,61 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import {+ imapAuth,+ performImapOperation,+ ImapError,+ ImapMailboxNotFoundError,+ isInbox,+} from '../common';+import { deleteFolderOutputSchema } from '../output-schemas';++export const deleteFolder = createAction({+ auth: imapAuth,+ name: 'delete_folder',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Folder',+ description: 'Permanently deletes a folder and the emails in it.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes an IMAP folder. On most servers every message inside is destroyed; on Gmail only the label is removed. Refuses INBOX, folders that have child folders, and any folder with a special-use role (Trash, Sent, Drafts, Junk, Archive, All), including roles guessed from the folder name. Not idempotent: a repeat call fails because the folder is gone.',+ idempotent: false,+ },+ props: {+ folder: Property.ShortText({+ displayName: 'Folder',+ description: 'Folder path from list_folders.',+ required: true,+ }),+ },+ outputSchema: deleteFolderOutputSchema,+ async run({ auth, propsValue }) {+ const folder = propsValue.folder.trim();+ if (!folder || isInbox({ path: folder })) {+ throw new ImapError('INBOX cannot be deleted.');+ }+ return performImapOperation(auth, async (client) => {+ const folders = await client.list();+ const current = folders.find((entry) => entry.path === folder);+ if (!current) {+ throw new ImapMailboxNotFoundError();+ }+ if (current.specialUse) {+ const guessed =+ current.specialUseSource === 'name'+ ? ' (the role was guessed from the folder name)'+ : '';+ throw new ImapError(+ `"${folder}" is a ${current.specialUse} folder${guessed} and will not be deleted.`+ );+ }+ const children = folders.filter((entry) => entry.parentPath === folder);+ if (children.length > 0) {+ throw new ImapError(+ `"${folder}" has ${children.length} child folder(s); delete or move them first.`+ );+ }+ const result = await client.mailboxDelete(folder);+ return { path: result.path, deleted: true };+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/get-email.ts b/packages/pieces/community/imap/src/lib/actions/get-email.tsnew file mode 100644index 00000000000..56a663cef7c--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/get-email.ts@@ -0,0 +1,112 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { simpleParser } from 'mailparser';+import {+ imapAuth,+ performImapOperation,+ withMailboxLock,+ selectedMailbox,+ assertOptionalUidValidity,+ parseSingleUid,+ flagsToArray,+ mapParsedAddresses,+ writeAttachments,+ toIsoDate,+ folderProp,+ uidValidityProp,+ ImapEmailNotFoundError,+ ImapError,+} from '../common';+import { getEmailOutputSchema } from '../output-schemas';++const MAX_MESSAGE_BYTES = 25 * 1024 * 1024;++export const getEmail = createAction({+ auth: imapAuth,+ name: 'get_email',+ classification: 'READ',+ displayName: 'Get Email',+ description: 'Gets the full content of one email, including attachments.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Fetches and parses one email by UID: headers, text and HTML bodies, flags, and attachments saved as files. Use after search_emails to read a specific message. The message is not marked as read. Pass the uid_validity from the same search_emails call so a stale UID is reported instead of returning an unrelated email. Messages over 25 MB are refused. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ folder: folderProp({+ displayName: 'Folder',+ description: 'Folder path from list_folders that contains the email.',+ }),+ uid: Property.Number({+ displayName: 'Message UID',+ description: 'UID from search_emails in the same folder.',+ required: true,+ }),+ uid_validity: uidValidityProp({ required: false }),+ },+ outputSchema: getEmailOutputSchema,+ async run({ auth, propsValue, files }) {+ const folder = propsValue.folder.trim();+ const uid = parseSingleUid({ uid: propsValue.uid });+ return performImapOperation(auth, async (client) =>+ withMailboxLock({+ client,+ folder,+ readOnly: true,+ run: async () => {+ assertOptionalUidValidity({ client, expected: propsValue.uid_validity });+ const mailbox = selectedMailbox({ client });+ const meta = await client.fetchOne(+ String(uid),+ { uid: true, size: true },+ { uid: true }+ );+ if (!meta) {+ throw new ImapEmailNotFoundError();+ }+ if ((meta.size ?? 0) > MAX_MESSAGE_BYTES) {+ throw new ImapError(+ `The email is ${meta.size} bytes, above the 25 MB limit for get_email.`+ );+ }+ const message = await client.fetchOne(+ String(uid),+ { uid: true, source: true, flags: true, size: true, internalDate: true },+ { uid: true }+ );+ if (!message || !message.source) {+ throw new ImapEmailNotFoundError();+ }+ const parsed = await simpleParser(message.source);+ const from = mapParsedAddresses(parsed.from);+ const flags = flagsToArray(message.flags);+ const references = parsed.references;+ return {+ folder: mailbox.path,+ uid: message.uid,+ uid_validity: mailbox.uidValidity.toString(),+ message_id: parsed.messageId ?? null,+ in_reply_to: parsed.inReplyTo ?? null,+ references: references === undefined ? [] : Array.isArray(references) ? references : [references],+ subject: parsed.subject ?? '',+ date: toIsoDate(parsed.date),+ internal_date: toIsoDate(message.internalDate),+ from_name: from[0]?.name ?? '',+ from_address: from[0]?.address ?? '',+ to: mapParsedAddresses(parsed.to),+ cc: mapParsedAddresses(parsed.cc),+ bcc: mapParsedAddresses(parsed.bcc),+ reply_to: mapParsedAddresses(parsed.replyTo),+ text: parsed.text ?? null,+ html: parsed.html === false ? null : parsed.html,+ flags,+ seen: flags.includes('\\Seen'),+ flagged: flags.includes('\\Flagged'),+ size: message.size ?? null,+ attachments: await writeAttachments({ attachments: parsed.attachments, files }),+ };+ },+ })+ );+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/get-folder-status.ts b/packages/pieces/community/imap/src/lib/actions/get-folder-status.tsnew file mode 100644index 00000000000..f179ca2bd02--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/get-folder-status.ts@@ -0,0 +1,56 @@+import { createAction } from '@activepieces/pieces-framework';+import {+ imapAuth,+ performImapOperation,+ bigintToString,+ folderProp,+ ImapError,+} from '../common';+import { getFolderStatusOutputSchema } from '../output-schemas';++export const getFolderStatus = createAction({+ auth: imapAuth,+ name: 'get_folder_status',+ classification: 'READ',+ displayName: 'Get Folder Status',+ description: 'Gets message counts and UID information for a folder.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the total, unread and recent message counts plus uid_next and uid_validity of one IMAP folder without opening it. Use for a quick unread count or to check whether UIDs from an earlier search are still valid; use search_emails to list the messages themselves. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ folder: folderProp({+ displayName: 'Folder',+ description: 'Folder path from list_folders.',+ }),+ },+ outputSchema: getFolderStatusOutputSchema,+ async run({ auth, propsValue }) {+ const folder = propsValue.folder.trim();+ return performImapOperation(auth, async (client) => {+ const status = await client.status(folder, {+ messages: true,+ unseen: true,+ recent: true,+ uidNext: true,+ uidValidity: true,+ highestModseq: true,+ });+ if (!status) {+ throw new ImapError(`Could not read the status of "${folder}".`);+ }+ const highestModseq = bigintToString(status.highestModseq);+ return {+ path: status.path,+ messages: status.messages ?? null,+ unseen: status.unseen ?? null,+ recent: status.recent ?? null,+ uid_next: status.uidNext ?? null,+ uid_validity: bigintToString(status.uidValidity) ?? null,+ ...(highestModseq ? { highest_modseq: highestModseq } : {}),+ };+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/get-quota.ts b/packages/pieces/community/imap/src/lib/actions/get-quota.tsnew file mode 100644index 00000000000..eab40d15ab7--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/get-quota.ts@@ -0,0 +1,70 @@+import { createAction } from '@activepieces/pieces-framework';+import { imapAuth, performImapOperation, folderProp, ImapError } from '../common';+import { getQuotaOutputSchema } from '../output-schemas';++function readResource({+ source,+ resource,+}: {+ source: unknown;+ resource: string;+}): { used: number | null; limit: number | null } | null {+ if (typeof source !== 'object' || source === null || !(resource in source)) {+ return null;+ }+ const entry: unknown = Reflect.get(source, resource);+ if (typeof entry !== 'object' || entry === null) {+ return null;+ }+ const used: unknown = Reflect.get(entry, 'usage') ?? Reflect.get(entry, 'used');+ const limit: unknown = Reflect.get(entry, 'limit');+ return {+ used: typeof used === 'number' ? used : null,+ limit: typeof limit === 'number' ? limit : null,+ };+}++export const getQuota = createAction({+ auth: imapAuth,+ name: 'get_quota',+ classification: 'READ',+ displayName: 'Get Quota',+ description: 'Gets the storage and message quota for a folder.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the storage (in bytes) and message-count usage and limits of the quota root that applies to a folder, via the IMAP QUOTA extension. Use to check whether the mailbox is near full. has_quota=false means the server reports no quota for that folder. Fails with a clear message when the server lacks QUOTA. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ folder: folderProp({+ displayName: 'Folder',+ description: 'Folder path from list_folders.',+ }),+ },+ outputSchema: getQuotaOutputSchema,+ async run({ auth, propsValue }) {+ const folder = propsValue.folder.trim();+ return performImapOperation(auth, async (client) => {+ if (!client.capabilities.has('QUOTA')) {+ throw new ImapError('The server does not support the QUOTA extension.');+ }+ const result = await client.getQuota(folder);+ if (!result) {+ throw new ImapError(`The server returned no quota information for "${folder}".`);+ }+ const storage = readResource({ source: result, resource: 'storage' });+ const messages =+ readResource({ source: result, resource: 'message' }) ??+ readResource({ source: result, resource: 'messages' });+ return {+ path: result.path,+ has_quota: storage !== null || messages !== null,+ storage_used_bytes: storage?.used ?? null,+ storage_limit_bytes: storage?.limit ?? null,+ messages_used: messages?.used ?? null,+ messages_limit: messages?.limit ?? null,+ };+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/list-folders.ts b/packages/pieces/community/imap/src/lib/actions/list-folders.tsnew file mode 100644index 00000000000..e2450369035--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/list-folders.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { imapAuth, performImapOperation, flagsToArray } from '../common';+import { listFoldersOutputSchema } from '../output-schemas';++export const listFolders = createAction({+ auth: imapAuth,+ name: 'list_folders',+ classification: 'SEARCH',+ displayName: 'List Folders',+ description: 'Lists every folder in the mailbox.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists all IMAP folders with their full path, delimiter, parent and detected special-use role (Trash, Drafts, Sent, Junk, Archive, All). Call first to learn exact folder paths for every other IMAP tool. special_use_source "name" means the role was guessed from the folder name. Set include_counts only when counts are needed: it costs one STATUS per folder. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ include_counts: Property.Checkbox({+ displayName: 'Include Message Counts',+ description:+ 'Also return the total and unread message count of each folder. Slower on accounts with many folders.',+ required: false,+ defaultValue: false,+ }),+ },+ outputSchema: listFoldersOutputSchema,+ async run({ auth, propsValue }) {+ const includeCounts = propsValue.include_counts === true;+ return performImapOperation(auth, async (client) => {+ const entries = await client.list(+ includeCounts ? { statusQuery: { messages: true, unseen: true } } : {}+ );+ const folders = entries.map((entry) => {+ const status = entry.status;+ const hasCounts =+ includeCounts && status !== undefined && typeof status.messages === 'number';+ return {+ path: entry.path,+ name: entry.name,+ delimiter: entry.delimiter,+ parent_path: entry.parentPath,+ special_use: entry.specialUse ?? null,+ special_use_source: entry.specialUseSource ?? null,+ flags: flagsToArray(entry.flags),+ subscribed: entry.subscribed,+ ...(hasCounts ? { messages: status.messages, unseen: status.unseen ?? null } : {}),+ };+ });+ return { folders, count: folders.length };+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/mark-email-read.ts b/packages/pieces/community/imap/src/lib/actions/mark-email-read.tsindex d080e8082ab..d7afa8f37d4 100644--- a/packages/pieces/community/imap/src/lib/actions/mark-email-read.ts+++ b/packages/pieces/community/imap/src/lib/actions/mark-email-read.ts@@ -1,5 +1,6 @@import { createAction, Property } from '@activepieces/pieces-framework';import { imapAuth, setEmailReadStatus, mailboxDropdown } from '../common';+import { markEmailReadActionOutputSchema } from '../output-schemas';const props = {mailbox: mailboxDropdown({@@ -26,7 +27,8 @@ export const markEmailAsRead = createAction({classification: 'WRITE',displayName: 'Mark Email as Read/Unread',description: 'Sets the read status of an email',- audience: 'both',+ outputSchema: markEmailReadActionOutputSchema,+ audience: 'human',aiMetadata: { description: 'Sets the read/unread (\\Seen) flag on a specific email in an IMAP mailbox, identified by its message UID. Use to mark a message as read after processing it or to flag one as unread. Requires the exact mailbox folder and UID; this is idempotent since it sets the flag to the chosen target state.', idempotent: true },props,async run({ auth, propsValue }) {diff --git a/packages/pieces/community/imap/src/lib/actions/move-email.ts b/packages/pieces/community/imap/src/lib/actions/move-email.tsindex 19f84ddbd15..e0f5077fc0e 100644--- a/packages/pieces/community/imap/src/lib/actions/move-email.ts+++ b/packages/pieces/community/imap/src/lib/actions/move-email.ts@@ -27,7 +27,7 @@ export const moveEmail = createAction({displayName: 'Move Email',description: 'Move an email to another mailbox',outputSchema: moveEmailActionOutputSchema,- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Moves an email (by message UID) from a source IMAP folder to a target folder, removing it from the source. Use to file, archive, or send a message to a Trash folder. Requires the source folder, target folder, and the UID; not idempotent since after the move the message no longer exists at the source UID and a repeat call cannot find it.', idempotent: false },props,async run({ auth, propsValue }) {diff --git a/packages/pieces/community/imap/src/lib/actions/move-emails.ts b/packages/pieces/community/imap/src/lib/actions/move-emails.tsnew file mode 100644index 00000000000..8de097c2206--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/move-emails.ts@@ -0,0 +1,55 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import {+ imapAuth,+ performImapOperation,+ transferInFolder,+ parseUids,+ folderProp,+ uidsProp,+ uidValidityProp,+} from '../common';+import { moveEmailsOutputSchema } from '../output-schemas';++export const moveEmails = createAction({+ auth: imapAuth,+ name: 'move_emails',+ classification: 'WRITE',+ displayName: 'Move Emails',+ description: 'Moves emails from one folder to another.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Moves one or more emails by UID from a source folder to an existing target folder. Use trash_emails or archive_emails when the destination is the Trash or Archive folder, and create_folder first if the target does not exist. UIDs that no longer exist are reported, not failed. uid_validity is required and must come from the search_emails call that produced these UIDs; a mismatch fails the call so stale UIDs cannot move the wrong emails. Refuses on servers that support neither MOVE nor UIDPLUS. Not idempotent: moved UIDs are gone from the source.',+ idempotent: false,+ },+ props: {+ source_folder: folderProp({+ displayName: 'Source Folder',+ description: 'Folder path from list_folders that contains the emails.',+ }),+ uids: uidsProp(),+ target_folder: Property.ShortText({+ displayName: 'Target Folder',+ description: 'Existing folder path from list_folders to move the emails into.',+ required: true,+ }),+ uid_validity: uidValidityProp({ required: true }),+ },+ outputSchema: moveEmailsOutputSchema,+ async run({ auth, propsValue }) {+ const uids = parseUids({ uids: propsValue.uids });+ const sourceFolder = propsValue.source_folder.trim();+ const targetFolder = propsValue.target_folder.trim();+ return performImapOperation(auth, async (client) => {+ const result = await transferInFolder({+ client,+ sourceFolder,+ targetFolder,+ uids,+ uidValidity: propsValue.uid_validity,+ mode: 'move',+ });+ return { ...result, target_folder: targetFolder };+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/rename-folder.ts b/packages/pieces/community/imap/src/lib/actions/rename-folder.tsnew file mode 100644index 00000000000..be090aeaaab--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/rename-folder.ts@@ -0,0 +1,69 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import {+ imapAuth,+ performImapOperation,+ ImapError,+ ImapMailboxNotFoundError,+ isInbox,+ assertHeaderSafe,+} from '../common';+import { renameFolderOutputSchema } from '../output-schemas';++export const renameFolder = createAction({+ auth: imapAuth,+ name: 'rename_folder',+ classification: 'WRITE',+ displayName: 'Rename Folder',+ description: 'Renames or moves a folder to a new path.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Renames an IMAP folder, or moves it under another parent, by giving its full new path. INBOX and folders the server flags as special-use (Trash, Sent, Drafts and so on) cannot be renamed. Not idempotent: a repeat call fails because the old path no longer exists.',+ idempotent: false,+ },+ props: {+ folder: Property.ShortText({+ displayName: 'Folder',+ description: 'Current folder path from list_folders.',+ required: true,+ }),+ new_path: Property.ShortText({+ displayName: 'New Path',+ description:+ 'Full new path, using the folder separator from list_folders for nesting (for example "Projects/2026").',+ required: true,+ }),+ },+ outputSchema: renameFolderOutputSchema,+ async run({ auth, propsValue }) {+ const folder = propsValue.folder.trim();+ const newPath = propsValue.new_path.trim();+ assertHeaderSafe({ field: 'New path', value: newPath });+ if (!folder || !newPath) {+ throw new ImapError('Both the folder and the new path are required.');+ }+ if (isInbox({ path: folder }) || isInbox({ path: newPath })) {+ throw new ImapError('INBOX cannot be renamed, and no folder can be renamed to INBOX.');+ }+ if (folder === newPath) {+ throw new ImapError('The new path is the same as the current path.');+ }+ return performImapOperation(auth, async (client) => {+ const folders = await client.list();+ const current = folders.find((entry) => entry.path === folder);+ if (!current) {+ throw new ImapMailboxNotFoundError();+ }+ if (current.specialUse && current.specialUseSource === 'extension') {+ throw new ImapError(+ `"${folder}" is the server's ${current.specialUse} folder and cannot be renamed.`+ );+ }+ if (folders.some((entry) => entry.path === newPath)) {+ throw new ImapError(`A folder named "${newPath}" already exists.`);+ }+ const result = await client.mailboxRename(folder, newPath);+ return { path: result.path, new_path: result.newPath };+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/search-emails.ts b/packages/pieces/community/imap/src/lib/actions/search-emails.tsnew file mode 100644index 00000000000..d2af5d4f0e4--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/search-emails.ts@@ -0,0 +1,169 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { type SearchObject } from 'imapflow';+import {+ imapAuth,+ performImapOperation,+ withMailboxLock,+ selectedMailbox,+ summarizeMessage,+ folderProp,+ ImapError,+ type EmailSummary,+} from '../common';+import { searchEmailsOutputSchema } from '../output-schemas';++function optionalText(value: string | undefined): string | undefined {+ const trimmed = value?.trim();+ return trimmed ? trimmed : undefined;+}++export const searchEmails = createAction({+ auth: imapAuth,+ name: 'search_emails',+ classification: 'SEARCH',+ displayName: 'Search Emails',+ description: 'Searches a folder and returns matching email summaries, newest first.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Searches one IMAP folder and returns envelope summaries (uid, subject, from, to, date, flags, size) newest first, without bodies. This is the source of message UIDs for every other IMAP email tool; pass the returned uid_validity along to detect stale UIDs. All filters are combined with AND; with no filters it lists the newest messages. Use get_email to read a full message. Read-only, safe to retry.',+ idempotent: true,+ },+ props: {+ folder: folderProp({+ displayName: 'Folder',+ description: 'Folder path from list_folders.',+ }),+ from: Property.ShortText({ displayName: 'From', description: 'Text contained in the From header.', required: false }),+ to: Property.ShortText({ displayName: 'To', description: 'Text contained in the To header.', required: false }),+ subject: Property.ShortText({ displayName: 'Subject', description: 'Text contained in the subject.', required: false }),+ body: Property.ShortText({ displayName: 'Body', description: 'Text contained in the message body.', required: false }),+ text: Property.ShortText({+ displayName: 'Text',+ description: 'Text contained anywhere in the headers or body.',+ required: false,+ }),+ message_id: Property.ShortText({+ displayName: 'Message-ID',+ description: 'Exact Message-ID header value, for example <[email protected]>.',+ required: false,+ }),+ since: Property.DateTime({+ displayName: 'Received Since',+ description:+ 'Only messages received on or after this date. Day granularity on most servers (time of day is ignored).',+ required: false,+ }),+ before: Property.DateTime({+ displayName: 'Received Before',+ description:+ 'Only messages received before this date. Day granularity on most servers (time of day is ignored).',+ required: false,+ }),+ read_status: Property.StaticDropdown({+ displayName: 'Read Status',+ description: 'Filter by read state. Leave empty for both.',+ required: false,+ options: {+ options: [+ { label: 'Read', value: 'read' },+ { label: 'Unread', value: 'unread' },+ ],+ },+ }),+ flagged: Property.StaticDropdown({+ displayName: 'Flagged',+ description: 'Filter by the flagged (starred) state. Leave empty for both.',+ required: false,+ options: {+ options: [+ { label: 'Flagged', value: 'flagged' },+ { label: 'Not Flagged', value: 'unflagged' },+ ],+ },+ }),+ keyword: Property.ShortText({+ displayName: 'Keyword',+ description: 'Only messages carrying this custom keyword (IMAP flag).',+ required: false,+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: 'Maximum number of emails to return (1-100).',+ required: false,+ defaultValue: 25,+ }),+ },+ outputSchema: searchEmailsOutputSchema,+ async run({ auth, propsValue }) {+ const folder = propsValue.folder.trim();+ const limit = propsValue.limit ?? 25;+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {+ throw new ImapError('Limit must be a whole number between 1 and 100.');+ }+ const criteria: SearchObject = {};+ const from = optionalText(propsValue.from);+ const to = optionalText(propsValue.to);+ const subject = optionalText(propsValue.subject);+ const body = optionalText(propsValue.body);+ const text = optionalText(propsValue.text);+ const messageId = optionalText(propsValue.message_id);+ const keyword = optionalText(propsValue.keyword);+ if (from) criteria.from = from;+ if (to) criteria.to = to;+ if (subject) criteria.subject = subject;+ if (body) criteria.body = body;+ if (text) criteria.text = text;+ if (messageId) criteria.header = { 'message-id': messageId };+ if (propsValue.since) criteria.since = new Date(propsValue.since);+ if (propsValue.before) criteria.before = new Date(propsValue.before);+ if (propsValue.read_status === 'read') criteria.seen = true;+ if (propsValue.read_status === 'unread') criteria.seen = false;+ if (propsValue.flagged === 'flagged') criteria.flagged = true;+ if (propsValue.flagged === 'unflagged') criteria.flagged = false;+ if (keyword) criteria.keyword = keyword;+ if (Object.keys(criteria).length === 0) criteria.all = true;++ return performImapOperation(auth, async (client) =>+ withMailboxLock({+ client,+ folder,+ readOnly: true,+ run: async () => {+ const mailbox = selectedMailbox({ client });+ const base = {+ folder: mailbox.path,+ uid_validity: mailbox.uidValidity.toString(),+ };+ const permanent = mailbox.permanentFlags;+ const keywordDropped =+ keyword !== undefined &&+ !mailbox.flags.has(keyword) &&+ permanent !== undefined &&+ !permanent.has('\\*') &&+ !permanent.has(keyword);+ if (keywordDropped) {+ return { ...base, total_matches: 0, count: 0, emails: [] };+ }+ const matches = await client.search(criteria, { uid: true });+ if (matches === false) {+ throw new ImapError('The server rejected the search.');+ }+ const top = [...matches].sort((a, b) => b - a).slice(0, limit);+ const emails: EmailSummary[] = [];+ if (top.length > 0) {+ for await (const message of client.fetch(+ top.join(','),+ { uid: true, envelope: true, flags: true, size: true, internalDate: true },+ { uid: true }+ )) {+ emails.push(summarizeMessage({ message }));+ }+ }+ emails.sort((a, b) => b.uid - a.uid);+ return { ...base, total_matches: matches.length, count: emails.length, emails };+ },+ })+ );+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/trash-emails.ts b/packages/pieces/community/imap/src/lib/actions/trash-emails.tsnew file mode 100644index 00000000000..de88fd2fe3f--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/trash-emails.ts@@ -0,0 +1,67 @@+import { createAction } from '@activepieces/pieces-framework';+import {+ imapAuth,+ performImapOperation,+ transferInFolder,+ resolveSpecialFolder,+ parseUids,+ samePath,+ folderProp,+ uidsProp,+ uidValidityProp,+ ImapError,+} from '../common';+import { trashEmailsOutputSchema } from '../output-schemas';++export const trashEmails = createAction({+ auth: imapAuth,+ name: 'trash_emails',+ classification: 'WRITE',+ displayName: 'Move Emails to Trash',+ description: 'Moves emails to the Trash folder.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Moves one or more emails by UID to the mailbox Trash folder, found automatically. This is the recoverable way to remove mail; prefer it over delete_emails. When special_use_source is "name", the Trash folder was guessed from its name. Fails, naming move_emails, if no Trash folder exists; use delete_emails for mail already in Trash. uid_validity is required and must come from the search_emails call that produced these UIDs; a mismatch fails the call so stale UIDs cannot trash the wrong emails. Not idempotent: trashed UIDs are gone from the source.',+ idempotent: false,+ },+ props: {+ folder: folderProp({+ displayName: 'Folder',+ description: 'Folder path from list_folders that contains the emails.',+ }),+ uids: uidsProp(),+ uid_validity: uidValidityProp({ required: true }),+ },+ outputSchema: trashEmailsOutputSchema,+ async run({ auth, propsValue }) {+ const uids = parseUids({ uids: propsValue.uids });+ const sourceFolder = propsValue.folder.trim();+ return performImapOperation(auth, async (client) => {+ const trash = await resolveSpecialFolder({ client, role: 'trash' });+ if (!trash) {+ throw new ImapError(+ 'No Trash folder was found on this server. Use move_emails with an explicit target folder.'+ );+ }+ if (samePath({ a: sourceFolder, b: trash.path })) {+ throw new ImapError(+ 'These emails are already in the Trash folder. Use delete_emails to remove them permanently.'+ );+ }+ const result = await transferInFolder({+ client,+ sourceFolder,+ targetFolder: trash.path,+ uids,+ uidValidity: propsValue.uid_validity,+ mode: 'move',+ });+ return {+ ...result,+ destination_folder: trash.path,+ special_use_source: trash.special_use_source,+ };+ });+ },+});diff --git a/packages/pieces/community/imap/src/lib/actions/update-email-flags.ts b/packages/pieces/community/imap/src/lib/actions/update-email-flags.tsnew file mode 100644index 00000000000..64af53b3ced--- /dev/null+++ b/packages/pieces/community/imap/src/lib/actions/update-email-flags.ts@@ -0,0 +1,207 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import {+ imapAuth,+ performImapOperation,+ withMailboxLock,+ selectedMailbox,+ assertUidValidity,+ partitionExistingUids,+ parseUids,+ flagsToArray,+ folderProp,+ uidsProp,+ uidValidityProp,+ ImapError,+} from '../common';+import { updateEmailFlagsOutputSchema } from '../output-schemas';++const KEYWORD_ATOM = /^[\x21-\x7e]+$/;+const KEYWORD_FORBIDDEN = /[(){%*"\\\]]/;++function parseKeywords({ values }: { values: unknown[] | undefined }): string[] {+ const keywords = (values ?? [])+ .map((value) => String(value).trim())+ .filter((value) => value.length > 0);+ for (const keyword of keywords) {+ if (!KEYWORD_ATOM.test(keyword) || KEYWORD_FORBIDDEN.test(keyword)) {+ throw new ImapError(+ `"${keyword}" is not a valid keyword: use printable ASCII without spaces or any of ( ) { % * " \\ ].`+ );+ }+ if (keyword.startsWith('\\')) {+ throw new ImapError(`"${keyword}" is a system flag, not a keyword.`);+ }+ }+ return [...new Set(keywords)];+}++function toggleOption({+ on,+ off,+}: {+ on: { label: string; value: string };+ off: { label: string; value: string };+}) {+ return { options: [on, off] };+}++export const updateEmailFlags = createAction({+ auth: imapAuth,+ name: 'update_email_flags',+ classification: 'WRITE',+ displayName: 'Update Email Flags',+ description: 'Marks emails read or unread, flagged or unflagged, answered, and adds or removes keywords.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes flags on one or more emails in a folder: read/unread, flagged/unflagged, answered, and custom keywords (labels). Only the options you set are changed; everything else is left untouched. Use trash_emails or delete_emails to remove messages instead. uid_validity is required and must come from the search_emails call that produced these UIDs; a mismatch fails the call so stale UIDs cannot re-flag the wrong emails. Sets a target state, so it is safe to retry.',+ idempotent: true,+ },+ props: {+ folder: folderProp({+ displayName: 'Folder',+ description: 'Folder path from list_folders that contains the emails.',+ }),+ uids: uidsProp(),+ uid_validity: uidValidityProp({ required: true }),+ read: Property.StaticDropdown({+ displayName: 'Read Status',+ description: 'Leave empty to keep the current read status.',+ required: false,+ options: toggleOption({+ on: { label: 'Mark as Read', value: 'mark_read' },+ off: { label: 'Mark as Unread', value: 'mark_unread' },+ }),+ }),+ flagged: Property.StaticDropdown({+ displayName: 'Flagged',+ description: 'Leave empty to keep the current flagged status.',+ required: false,+ options: toggleOption({+ on: { label: 'Flag', value: 'flag' },+ off: { label: 'Unflag', value: 'unflag' },+ }),+ }),+ answered: Property.StaticDropdown({+ displayName: 'Answered',+ description: 'Leave empty to keep the current answered status.',+ required: false,+ options: toggleOption({+ on: { label: 'Mark as Answered', value: 'mark_answered' },+ off: { label: 'Mark as Not Answered', value: 'unmark_answered' },+ }),+ }),+ add_keywords: Property.Array({+ displayName: 'Add Keywords',+ description: 'Custom keywords to add, for example "invoice".',+ required: false,+ }),+ remove_keywords: Property.Array({+ displayName: 'Remove Keywords',+ description: 'Custom keywords to remove.',+ required: false,+ }),+ },+ outputSchema: updateEmailFlagsOutputSchema,+ async run({ auth, propsValue }) {+ const folder = propsValue.folder.trim();+ const uids = parseUids({ uids: propsValue.uids });+ const add: string[] = [];+ const remove: string[] = [];+ const toggles = [+ { choice: propsValue.read, on: 'mark_read', off: 'mark_unread', flag: '\\Seen' },+ { choice: propsValue.flagged, on: 'flag', off: 'unflag', flag: '\\Flagged' },+ {+ choice: propsValue.answered,+ on: 'mark_answered',+ off: 'unmark_answered',+ flag: '\\Answered',+ },+ ];+ for (const { choice, on, off, flag } of toggles) {+ if (choice === on) {+ add.push(flag);+ } else if (choice === off) {+ remove.push(flag);+ }+ }+ const addKeywords = parseKeywords({ values: propsValue.add_keywords });+ const removeKeywords = parseKeywords({ values: propsValue.remove_keywords });+ const overlap = addKeywords.filter((keyword) => removeKeywords.includes(keyword));+ if (overlap.length > 0) {+ throw new ImapError(`Keyword "${overlap[0]}" cannot be both added and removed.`);+ }+ add.push(...addKeywords);+ remove.push(...removeKeywords);+ if (add.length === 0 && remove.length === 0) {+ throw new ImapError('Choose at least one flag or keyword to change.');+ }++ return performImapOperation(auth, async (client) =>+ withMailboxLock({+ client,+ folder,+ readOnly: false,+ run: async () => {+ assertUidValidity({ client, expected: propsValue.uid_validity });+ const mailbox = selectedMailbox({ client });+ const permanent = mailbox.permanentFlags;+ const keywords = [...addKeywords, ...removeKeywords];+ if (+ keywords.length > 0 &&+ permanent &&+ !permanent.has('\\*') &&+ !keywords.every((keyword) => permanent.has(keyword))+ ) {+ throw new ImapError('This folder does not accept custom keywords.');+ }+ const { found, notFound } = await partitionExistingUids({ client, uids });+ const range = found.join(',');+ if (add.length > 0) {+ const ok = await client.messageFlagsAdd(range, add, { uid: true });+ if (!ok) {+ throw new ImapError(`The server refused to add ${add.join(', ')}.`);+ }+ }+ if (remove.length > 0) {+ const ok = await client.messageFlagsRemove(range, remove, { uid: true });+ if (!ok) {+ throw new ImapError(`The server refused to remove ${remove.join(', ')}.`);+ }+ }+ const emails: Array<{+ uid: number;+ flags: string[];+ seen: boolean;+ flagged: boolean;+ answered: boolean;+ }> = [];+ for await (const message of client.fetch(range, { uid: true, flags: true }, { uid: true })) {+ const flags = flagsToArray(message.flags);+ const missing = add.find((flag) => !flags.includes(flag));+ const lingering = remove.find((flag) => flags.includes(flag));+ if (missing || lingering) {+ throw new ImapError(+ `The server did not apply ${missing ?? lingering} to UID ${message.uid}; the folder may not allow it.`+ );+ }+ emails.push({+ uid: message.uid,+ flags,+ seen: flags.includes('\\Seen'),+ flagged: flags.includes('\\Flagged'),+ answered: flags.includes('\\Answered'),+ });+ }+ emails.sort((a, b) => a.uid - b.uid);+ return {+ folder: mailbox.path,+ uid_validity: mailbox.uidValidity.toString(),+ emails,+ not_found_uids: notFound,+ };+ },+ })+ );+ },+});diff --git a/packages/pieces/community/imap/src/lib/common/imap.ts b/packages/pieces/community/imap/src/lib/common/imap.tsindex 1d25ab471d1..504f71fe79a 100644--- a/packages/pieces/community/imap/src/lib/common/imap.ts+++ b/packages/pieces/community/imap/src/lib/common/imap.ts@@ -23,6 +23,11 @@ import {ImapConnectionLostError,ImapEmailNotFoundError,} from './errors';+import {+ assertFolderExists,+ assertUidPlusForDelete,+ transferMessages,+} from './message';type Message = {data: ParsedMail & { uid: number };@@ -50,7 +55,11 @@ async function confirmEmailExists({ uid: true });- if (!searchResult || searchResult.length === 0) {+ if (searchResult === false) {+ throw new ImapError('The server rejected the search for the email.');+ }++ if (searchResult.length === 0) {throw new ImapEmailNotFoundError();}}@@ -81,6 +90,7 @@ async function copyEmail<T extends { success: boolean; newUid?: number }>({auth,sourceMailbox,async (imapClient) => {+ await assertFolderExists({ client: imapClient, path: targetMailbox });await confirmEmailExists(imapClient, uid);const result: false | CopyResponseObject = await imapClient.messageCopy(@@ -108,12 +118,31 @@ async function deleteEmail<T extends { success: boolean }>({mailbox: string;uid: number;}): Promise<T> {- return (await performMailboxOperation(auth, mailbox, async (imapClient) => {- await confirmEmailExists(imapClient, uid);- await imapClient.messageDelete({ uid: uid.toString() }, { uid: true });+ return (await performMailboxOperation(+ auth,+ mailbox,+ async (imapClient) => {+ assertUidPlusForDelete({ client: imapClient });+ await confirmEmailExists(imapClient, uid);+ const deleted = await imapClient.messageDelete(+ { uid: uid.toString() },+ { uid: true }+ );+ if (!deleted) {+ throw new ImapError('The server refused to delete the email.');+ }+ const remaining = await imapClient.search(+ { uid: uid.toString() },+ { uid: true }+ );+ if (remaining === false || remaining.length > 0) {+ throw new ImapError('The email is still present after the delete.');+ }- return { success: true };- })) as T;+ return { success: true };+ },+ { readOnly: false }+ )) as T;}async function fetchEmails<T extends Message[]>({@@ -169,21 +198,20 @@ async function moveEmail<T extends { success: boolean; newUid?: number }>({auth,sourceMailbox,async (imapClient) => {+ await assertFolderExists({ client: imapClient, path: targetMailbox });await confirmEmailExists(imapClient, uid);- const result: false | CopyResponseObject = await imapClient.messageMove(- { uid: uid.toString() },- targetMailbox,- { uid: true }- );-- if (result) {- const newUid = result.uidMap?.get(uid);- return { success: true, newUid };- }+ const result = await transferMessages({+ client: imapClient,+ uids: [uid],+ target: targetMailbox,+ mode: 'move',+ });- return { success: false };- }+ const newUid = result.uidMap?.get(uid);+ return { success: true, newUid };+ },+ { readOnly: false })) as T;}@@ -199,10 +227,10 @@ async function parseStream(stream: Readable) {});}-async function performImapOperation(+async function performImapOperation<T>(auth: ImapAuth,- callback: (imapClient: ImapFlow) => Promise<unknown>-) {+ callback: (imapClient: ImapFlow) => Promise<T>+): Promise<T> {let imapClient: ImapFlow | null = null;try {@@ -220,7 +248,10 @@ async function performImapOperation(throw new ImapConnectionTimeoutError();} else if (imapError.code === 'ERR_SSL_PACKET_LENGTH_TOO_LONG') {throw new ImapSslPacketLengthTooLongError();- } else if (imapError.responseText?.includes('AUTH')) {+ } else if (+ imapError.responseText?.includes('AUTH') ||+ ('authenticationFailed' in imapError && imapError.authenticationFailed === true)+ ) {throw new ImapAuthenticationError();} else if (imapError.message?.includes('IMAP connection')) {throw new ImapConnectionLostError();@@ -228,10 +259,17 @@ async function performImapOperation(throw new ImapCertificateError();} else if (imapError instanceof ImapError) {throw imapError;+ } else if (+ imapError.code === 'NotFound' ||+ ('mailboxMissing' in imapError && imapError.mailboxMissing === true)+ ) {+ throw new ImapMailboxNotFoundError();}throw new ImapError(- imapError.message || 'Failed to perform IMAP operation'+ imapError.responseText ||+ imapError.message ||+ 'Failed to perform IMAP operation');} finally {try {diff --git a/packages/pieces/community/imap/src/lib/common/index.ts b/packages/pieces/community/imap/src/lib/common/index.tsindex d19d3691966..e1cad987be5 100644--- a/packages/pieces/community/imap/src/lib/common/index.ts+++ b/packages/pieces/community/imap/src/lib/common/index.ts@@ -3,3 +3,6 @@ export * from './constants';export * from './errors';export * from './imap';export * from './props';+export * from './message';+export * from './special-use';+export * from './mime';diff --git a/packages/pieces/community/imap/src/lib/common/message.ts b/packages/pieces/community/imap/src/lib/common/message.tsnew file mode 100644index 00000000000..544b4454b3a--- /dev/null+++ b/packages/pieces/community/imap/src/lib/common/message.ts@@ -0,0 +1,451 @@+import { FilesService, Property } from '@activepieces/pieces-framework';+import {+ type CopyResponseObject,+ type FetchMessageObject,+ type ImapFlow,+ type MailboxObject,+ type MessageAddressObject,+} from 'imapflow';+import { type AddressObject, type Attachment } from 'mailparser';+import { ImapEmailNotFoundError, ImapError } from './errors';++const MAX_UIDS = 500;++function flagsToArray(flags: Set<string> | undefined): string[] {+ return flags ? [...flags].sort() : [];+}++function bigintToString(value: bigint | undefined): string | undefined {+ return value === undefined ? undefined : value.toString();+}++function toIsoDate(value: Date | string | undefined): string | null {+ if (value === undefined) {+ return null;+ }+ const date = value instanceof Date ? value : new Date(value);+ return Number.isNaN(date.getTime()) ? null : date.toISOString();+}++function mapEnvelopeAddresses(+ addresses: MessageAddressObject[] | undefined+): EmailAddress[] {+ return (addresses ?? []).map((entry) => ({+ name: entry.name ?? '',+ address: entry.address ?? '',+ }));+}++function mapParsedAddresses(+ value: AddressObject | AddressObject[] | undefined+): EmailAddress[] {+ if (!value) {+ return [];+ }+ const objects = Array.isArray(value) ? value : [value];+ const result: EmailAddress[] = [];+ for (const object of objects) {+ for (const entry of object.value) {+ if (entry.group && entry.group.length > 0) {+ for (const member of entry.group) {+ result.push({ name: member.name ?? '', address: member.address ?? '' });+ }+ } else {+ result.push({ name: entry.name ?? '', address: entry.address ?? '' });+ }+ }+ }+ return result;+}++function summarizeMessage({+ message,+}: {+ message: FetchMessageObject;+}): EmailSummary {+ const envelope = message.envelope;+ const from = mapEnvelopeAddresses(envelope?.from);+ const flags = flagsToArray(message.flags);+ return {+ uid: message.uid,+ message_id: envelope?.messageId ?? null,+ in_reply_to: envelope?.inReplyTo ?? null,+ subject: envelope?.subject ?? '',+ date: toIsoDate(envelope?.date),+ internal_date: toIsoDate(message.internalDate),+ from_name: from[0]?.name ?? '',+ from_address: from[0]?.address ?? '',+ to: mapEnvelopeAddresses(envelope?.to),+ cc: mapEnvelopeAddresses(envelope?.cc),+ flags,+ seen: flags.includes('\\Seen'),+ flagged: flags.includes('\\Flagged'),+ answered: flags.includes('\\Answered'),+ size: message.size ?? null,+ };+}++function parseUids({ uids }: { uids: unknown[] | undefined }): number[] {+ if (!uids || uids.length === 0) {+ throw new ImapError('Provide at least one message UID.');+ }+ const parsed = new Set<number>();+ for (const raw of uids) {+ const text = String(raw).trim();+ if (!/^[1-9]\d*$/.test(text)) {+ throw new ImapError(+ `"${text}" is not a valid message UID; UIDs are positive integers from search_emails.`+ );+ }+ parsed.add(Number(text));+ }+ if (parsed.size > MAX_UIDS) {+ throw new ImapError(`At most ${MAX_UIDS} UIDs can be processed per call.`);+ }+ return [...parsed].sort((a, b) => a - b);+}++function parseSingleUid({ uid }: { uid: unknown }): number {+ const [value] = parseUids({ uids: [uid] });+ return value;+}++function selectedMailbox({ client }: { client: ImapFlow }): MailboxObject {+ const mailbox = client.mailbox;+ if (!mailbox) {+ throw new ImapError('No folder is open on the IMAP connection.');+ }+ return mailbox;+}++function assertUidValidity({+ client,+ expected,+}: {+ client: ImapFlow;+ expected: string;+}): void {+ const trimmed = expected.trim();+ if (!trimmed) {+ throw new ImapError(+ 'uid_validity is required so stale UIDs cannot target the wrong emails. Re-run search_emails on this folder and pass the uid_validity it returns.'+ );+ }+ const actual = selectedMailbox({ client }).uidValidity.toString();+ if (actual !== trimmed) {+ throw new ImapError(+ `The folder UIDVALIDITY changed from ${trimmed} to ${actual}, so the supplied UIDs are stale and may now identify different emails. Nothing was changed. Re-run search_emails on this folder to get fresh UIDs and uid_validity, then retry.`+ );+ }+}++function assertOptionalUidValidity({+ client,+ expected,+}: {+ client: ImapFlow;+ expected: string | undefined;+}): void {+ if (!expected?.trim()) {+ return;+ }+ assertUidValidity({ client, expected });+}++async function partitionExistingUids({+ client,+ uids,+}: {+ client: ImapFlow;+ uids: number[];+}): Promise<{ found: number[]; notFound: number[] }> {+ const result = await client.search({ uid: uids.join(',') }, { uid: true });+ if (result === false) {+ throw new ImapError('The server rejected the UID search.');+ }+ const existing = new Set(result);+ const found = uids.filter((uid) => existing.has(uid));+ const notFound = uids.filter((uid) => !existing.has(uid));+ if (found.length === 0) {+ throw new ImapEmailNotFoundError();+ }+ return { found, notFound };+}++async function assertFolderExists({+ client,+ path,+}: {+ client: ImapFlow;+ path: string;+}): Promise<void> {+ try {+ const status = await client.status(path, { messages: true });+ if (!status) {+ throw new ImapError(`Could not read the target folder "${path}".`);+ }+ } catch (error) {+ if (error instanceof ImapError) {+ throw error;+ }+ if (hasCode({ error, code: 'NotFound' })) {+ throw new ImapError(+ `Target folder "${path}" does not exist; create it with create_folder or pick a path from list_folders.`+ );+ }+ throw error;+ }+}++function assertUidPlusForDelete({ client }: { client: ImapFlow }): void {+ if (!client.capabilities.has('UIDPLUS')) {+ throw new ImapError(+ 'The server does not support UIDPLUS, so deleting would expunge every message marked \\Deleted in the folder. Use trash_emails instead.'+ );+ }+}++async function transferMessages({+ client,+ uids,+ target,+ mode,+}: {+ client: ImapFlow;+ uids: number[];+ target: string;+ mode: 'move' | 'copy';+}): Promise<CopyResponseObject> {+ const range = uids.join(',');+ if (mode === 'copy') {+ const copied = await client.messageCopy(range, target, { uid: true });+ if (!copied) {+ throw new ImapError(`The server refused to copy the emails to "${target}".`);+ }+ return copied;+ }+ if (client.capabilities.has('MOVE')) {+ const moved = await client.messageMove(range, target, { uid: true });+ if (!moved) {+ throw new ImapError(`The server refused to move the emails to "${target}".`);+ }+ return moved;+ }+ if (client.capabilities.has('UIDPLUS')) {+ const copied = await client.messageCopy(range, target, { uid: true });+ if (!copied) {+ throw new ImapError(`The server refused to copy the emails to "${target}"; nothing was removed.`);+ }+ const deleted = await client.messageDelete(range, { uid: true });+ if (!deleted) {+ throw new ImapError(+ `The emails were copied to "${target}" but could not be removed from the source folder.`+ );+ }+ return copied;+ }+ throw new ImapError(+ 'The server supports neither MOVE nor UIDPLUS, so a safe move is not possible. Use copy_emails instead.'+ );+}++async function transferInFolder({+ client,+ sourceFolder,+ targetFolder,+ uids,+ uidValidity,+ mode,+}: {+ client: ImapFlow;+ sourceFolder: string;+ targetFolder: string;+ uids: number[];+ uidValidity: string;+ mode: 'move' | 'copy';+}): Promise<TransferOutput> {+ if (samePath({ a: sourceFolder, b: targetFolder })) {+ throw new ImapError('The source and target folders must be different.');+ }+ await assertFolderExists({ client, path: targetFolder });+ return withMailboxLock({+ client,+ folder: sourceFolder,+ readOnly: false,+ run: async () => {+ assertUidValidity({ client, expected: uidValidity });+ const mailbox = selectedMailbox({ client });+ const { found, notFound } = await partitionExistingUids({ client, uids });+ const response = await transferMessages({ client, uids: found, target: targetFolder, mode });+ const results = found.map((uid) => {+ const newUid = response.uidMap?.get(uid);+ return newUid === undefined ? { uid } : { uid, new_uid: newUid };+ });+ const targetUidValidity = bigintToString(response.uidValidity);+ return {+ source_folder: mailbox.path,+ source_uid_validity: mailbox.uidValidity.toString(),+ ...(targetUidValidity ? { target_uid_validity: targetUidValidity } : {}),+ results,+ count: results.length,+ not_found_uids: notFound,+ };+ },+ });+}++async function withMailboxLock<T>({+ client,+ folder,+ readOnly,+ run,+}: {+ client: ImapFlow;+ folder: string;+ readOnly: boolean;+ run: () => Promise<T>;+}): Promise<T> {+ const lock = await client.getMailboxLock(folder, { readOnly });+ try {+ return await run();+ } finally {+ lock.release();+ }+}++async function writeAttachments({+ attachments,+ files,+}: {+ attachments: Attachment[];+ files: FilesService;+}): Promise<AttachmentOutput[]> {+ return Promise.all(+ attachments.map(async (attachment, index) => {+ const filename = attachment.filename ?? `attachment-${index + 1}`;+ const file = await files.write({ fileName: filename, data: attachment.content });+ return {+ filename,+ content_type: attachment.contentType,+ size: attachment.size,+ file,+ };+ })+ );+}++function isInbox({ path }: { path: string }): boolean {+ return path.trim().toUpperCase() === 'INBOX';+}++function samePath({ a, b }: { a: string; b: string }): boolean {+ return isInbox({ path: a }) && isInbox({ path: b }) ? true : a === b;+}++function hasCode({ error, code }: { error: unknown; code: string }): boolean {+ return (+ typeof error === 'object' &&+ error !== null &&+ 'code' in error &&+ error.code === code+ );+}++const folderProp = ({+ displayName,+ description,+}: {+ displayName: string;+ description: string;+}) =>+ Property.ShortText({+ displayName,+ description,+ required: true,+ defaultValue: 'INBOX',+ });++const uidsProp = () =>+ Property.Array({+ displayName: 'Message UIDs',+ description:+ 'UIDs from search_emails in the same folder (up to 500). UIDs that no longer exist are reported in not_found_uids.',+ required: true,+ });++const uidValidityProp = <T extends boolean>({ required }: { required: T }) =>+ Property.ShortText({+ displayName: 'UID Validity',+ description: required+ ? 'The uid_validity returned by the search_emails call that produced these UIDs. If the folder UIDVALIDITY has changed the UIDs are stale and the call fails instead of acting on unrelated emails.'+ : 'The uid_validity returned by search_emails. When set and the folder has changed, the call fails instead of reading a stale UID.',+ required,+ });++type EmailAddress = { name: string; address: string };++type EmailSummary = {+ uid: number;+ message_id: string | null;+ in_reply_to: string | null;+ subject: string;+ date: string | null;+ internal_date: string | null;+ from_name: string;+ from_address: string;+ to: EmailAddress[];+ cc: EmailAddress[];+ flags: string[];+ seen: boolean;+ flagged: boolean;+ answered: boolean;+ size: number | null;+};++type TransferOutput = {+ source_folder: string;+ source_uid_validity: string;+ target_uid_validity?: string;+ results: Array<{ uid: number; new_uid?: number }>;+ count: number;+ not_found_uids: number[];+};++type AttachmentOutput = {+ filename: string;+ content_type: string;+ size: number;+ file: string;+};++export {+ type EmailAddress,+ type EmailSummary,+ type AttachmentOutput,+ type TransferOutput,+ MAX_UIDS,+ transferInFolder,+ flagsToArray,+ bigintToString,+ toIsoDate,+ mapEnvelopeAddresses,+ mapParsedAddresses,+ summarizeMessage,+ parseUids,+ parseSingleUid,+ selectedMailbox,+ assertUidValidity,+ assertOptionalUidValidity,+ partitionExistingUids,+ assertFolderExists,+ assertUidPlusForDelete,+ transferMessages,+ withMailboxLock,+ writeAttachments,+ isInbox,+ samePath,+ hasCode,+ folderProp,+ uidsProp,+ uidValidityProp,+};diff --git a/packages/pieces/community/imap/src/lib/common/mime.ts b/packages/pieces/community/imap/src/lib/common/mime.tsnew file mode 100644index 00000000000..21a56a1fd73--- /dev/null+++ b/packages/pieces/community/imap/src/lib/common/mime.ts@@ -0,0 +1,198 @@+import { randomBytes } from 'crypto';+import { ImapError } from './errors';++const CRLF = '\r\n';+const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];+const ADDR_SPEC = /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/;+const MESSAGE_ID = /^<[\x21-\x3b\x3d\x3f-\x7e]+@[\x21-\x3b\x3d\x3f-\x7e]+>$/;+const ASCII_PRINTABLE = /^[\x20-\x7e]*$/;+const NEEDS_QUOTING = /[()<>[\]:;@\\,."]/;+const MAX_ENCODED_BYTES = 45;++function assertHeaderSafe({ field, value }: { field: string; value: string }): void {+ if (/[\r\n\0]/.test(value)) {+ throw new ImapError(`${field} must not contain line breaks or NUL characters.`);+ }+}++function encodeWords({ value }: { value: string }): string[] {+ const words: string[] = [];+ let chunk = '';+ for (const char of value) {+ if (Buffer.byteLength(chunk + char, 'utf8') > MAX_ENCODED_BYTES) {+ words.push(chunk);+ chunk = '';+ }+ chunk += char;+ }+ if (chunk.length > 0) {+ words.push(chunk);+ }+ return words.map((word) => `=?UTF-8?B?${Buffer.from(word, 'utf8').toString('base64')}?=`);+}++function encodeText({ value }: { value: string }): string {+ if (ASCII_PRINTABLE.test(value) && value.length <= 900) {+ return value;+ }+ return encodeWords({ value }).join(`${CRLF} `);+}++function formatDisplayName({ name }: { name: string }): string {+ if (!ASCII_PRINTABLE.test(name)) {+ return encodeWords({ value: name }).join(`${CRLF} `);+ }+ if (NEEDS_QUOTING.test(name)) {+ return `"${name.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;+ }+ return name;+}++function parseAddress({ field, value }: { field: string; value: string }): ParsedAddress {+ assertHeaderSafe({ field, value });+ const trimmed = value.trim();+ const angle = /^(.*)<([^<>]+)>$/.exec(trimmed);+ const rawName = angle ? angle[1].trim().replace(/^"(.*)"$/, '$1') : '';+ const address = angle ? angle[2].trim() : trimmed;+ if (!ADDR_SPEC.test(address)) {+ throw new ImapError(+ `${field} "${trimmed}" is not a valid email address; use "[email protected]" or "Name <[email protected]>" with an ASCII address.`+ );+ }+ return { name: rawName, address };+}++function formatAddress({ address }: { address: ParsedAddress }): string {+ if (!address.name) {+ return address.address;+ }+ return `${formatDisplayName({ name: address.name })} <${address.address}>`;+}++function formatAddressList({+ field,+ values,+}: {+ field: string;+ values: string[];+}): string | null {+ const cleaned = values.map((value) => value.trim()).filter((value) => value.length > 0);+ if (cleaned.length === 0) {+ return null;+ }+ return cleaned+ .map((value) => formatAddress({ address: parseAddress({ field, value }) }))+ .join(`,${CRLF} `);+}++function formatDate({ date }: { date: Date }): string {+ const pad = (n: number) => String(n).padStart(2, '0');+ const offsetMinutes = -date.getTimezoneOffset();+ const sign = offsetMinutes >= 0 ? '+' : '-';+ const abs = Math.abs(offsetMinutes);+ return `${DAYS[date.getDay()]}, ${pad(date.getDate())} ${MONTHS[date.getMonth()]} ${date.getFullYear()} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())} ${sign}${pad(Math.floor(abs / 60))}${pad(abs % 60)}`;+}++function base64Body({ content }: { content: string }): string {+ const encoded = Buffer.from(content, 'utf8').toString('base64');+ const lines = encoded.match(/.{1,76}/g) ?? [];+ return lines.join(CRLF);+}++function textPart({ subtype, content }: { subtype: 'plain' | 'html'; content: string }): string {+ return [+ `Content-Type: text/${subtype}; charset=UTF-8`,+ 'Content-Transfer-Encoding: base64',+ '',+ base64Body({ content }),+ ].join(CRLF);+}++function buildDraftMessage({+ from,+ to,+ cc,+ bcc,+ subject,+ text,+ html,+ inReplyTo,+ date,+}: {+ from: string;+ to: string[];+ cc: string[];+ bcc: string[];+ subject: string;+ text: string | undefined;+ html: string | undefined;+ inReplyTo: string | undefined;+ date: Date;+}): { raw: string; messageId: string } {+ const fromAddress = parseAddress({ field: 'From', value: from });+ const toHeader = formatAddressList({ field: 'To', values: to });+ if (!toHeader) {+ throw new ImapError('Provide at least one recipient in To.');+ }+ const ccHeader = formatAddressList({ field: 'Cc', values: cc });+ const bccHeader = formatAddressList({ field: 'Bcc', values: bcc });+ assertHeaderSafe({ field: 'Subject', value: subject });+ const replyTo = inReplyTo?.trim();+ if (replyTo) {+ assertHeaderSafe({ field: 'In-Reply-To', value: replyTo });+ if (!MESSAGE_ID.test(replyTo)) {+ throw new ImapError('In-Reply-To must be a Message-ID in the form <id@domain>.');+ }+ }+ if (!text && !html) {+ throw new ImapError('Provide a text body, an HTML body, or both.');+ }+ const domain = fromAddress.address.split('@')[1];+ const messageId = `<${randomBytes(12).toString('hex')}.${date.getTime()}@${domain}>`;+ const headers = [+ `From: ${formatAddress({ address: fromAddress })}`,+ `To: ${toHeader}`,+ ];+ if (ccHeader) {+ headers.push(`Cc: ${ccHeader}`);+ }+ if (bccHeader) {+ headers.push(`Bcc: ${bccHeader}`);+ }+ headers.push(`Subject: ${encodeText({ value: subject })}`);+ headers.push(`Date: ${formatDate({ date })}`);+ headers.push(`Message-ID: ${messageId}`);+ if (replyTo) {+ headers.push(`In-Reply-To: ${replyTo}`);+ headers.push(`References: ${replyTo}`);+ }+ headers.push('MIME-Version: 1.0');++ let body: string;+ if (text && html) {+ const boundary = `----=_ap_${randomBytes(12).toString('hex')}`;+ headers.push(`Content-Type: multipart/alternative; boundary="${boundary}"`);+ body = [+ `--${boundary}`,+ textPart({ subtype: 'plain', content: text }),+ `--${boundary}`,+ textPart({ subtype: 'html', content: html }),+ `--${boundary}--`,+ '',+ ].join(CRLF);+ } else {+ const subtype = text ? 'plain' : 'html';+ headers.push(+ `Content-Type: text/${subtype}; charset=UTF-8`,+ 'Content-Transfer-Encoding: base64'+ );+ body = `${base64Body({ content: text ? text : html ?? '' })}${CRLF}`;+ }++ return { raw: `${headers.join(CRLF)}${CRLF}${CRLF}${body}`, messageId };+}++type ParsedAddress = { name: string; address: string };++export { assertHeaderSafe, parseAddress, buildDraftMessage };diff --git a/packages/pieces/community/imap/src/lib/common/special-use.ts b/packages/pieces/community/imap/src/lib/common/special-use.tsnew file mode 100644index 00000000000..f77fbae8a34--- /dev/null+++ b/packages/pieces/community/imap/src/lib/common/special-use.ts@@ -0,0 +1,56 @@+import { type ImapFlow, type ListResponse } from 'imapflow';++async function resolveSpecialFolder({+ client,+ role,+}: {+ client: ImapFlow;+ role: SpecialFolderRole;+}): Promise<ResolvedSpecialFolder | null> {+ const folders = await client.list();+ const match = findSpecialFolder({ folders, role });+ if (!match) {+ return null;+ }+ return {+ path: match.path,+ special_use: match.specialUse ?? '',+ special_use_source: match.specialUseSource ?? null,+ };+}++function findSpecialFolder({+ folders,+ role,+}: {+ folders: ListResponse[];+ role: SpecialFolderRole;+}): ListResponse | undefined {+ const selectable = folders.filter((folder) => !folder.flags.has('\\Noselect'));+ if (role === 'archive') {+ return (+ selectable.find((folder) => folder.specialUse === '\\Archive') ??+ selectable.find(+ (folder) =>+ folder.specialUse === '\\All' && folder.specialUseSource === 'extension'+ )+ );+ }+ const flag = role === 'trash' ? '\\Trash' : '\\Drafts';+ return selectable.find((folder) => folder.specialUse === flag);+}++type SpecialFolderRole = 'trash' | 'drafts' | 'archive';++type ResolvedSpecialFolder = {+ path: string;+ special_use: string;+ special_use_source: 'user' | 'extension' | 'name' | null;+};++export {+ type SpecialFolderRole,+ type ResolvedSpecialFolder,+ resolveSpecialFolder,+ findSpecialFolder,+};diff --git a/packages/pieces/community/imap/src/lib/output-schemas.ts b/packages/pieces/community/imap/src/lib/output-schemas.tsindex 6e1e2802a54..a3ad2d59ecd 100644--- a/packages/pieces/community/imap/src/lib/output-schemas.ts+++ b/packages/pieces/community/imap/src/lib/output-schemas.ts@@ -13,6 +13,65 @@ const addressFields: OutputSchema['fields'] = [},];+const recipientListItems: OutputSchema['fields'] = [+ { key: 'address', label: 'Email', format: 'email' },+ { key: 'name', label: 'Name' },+];++const emailSummaryFields: OutputSchema['fields'] = [+ { key: 'uid', label: 'Message UID', format: 'number' },+ { key: 'message_id', label: 'Message-ID' },+ { key: 'in_reply_to', label: 'In Reply To' },+ { key: 'subject', label: 'Subject' },+ { key: 'date', label: 'Date', format: 'datetime' },+ { key: 'internal_date', label: 'Received At', format: 'datetime' },+ { key: 'from_name', label: 'From Name' },+ { key: 'from_address', label: 'From Email', format: 'email' },+ { key: 'to', label: 'To', labelKey: 'address', listItems: recipientListItems },+ { key: 'cc', label: 'Cc', labelKey: 'address', listItems: recipientListItems },+ { key: 'flags', label: 'Flags' },+ { key: 'seen', label: 'Read', format: 'boolean' },+ { key: 'flagged', label: 'Flagged', format: 'boolean' },+ { key: 'answered', label: 'Answered', format: 'boolean' },+ { key: 'size', label: 'Size', format: 'filesize' },+];++const transferFields: OutputSchema['fields'] = [+ { key: 'source_folder', label: 'Source Folder' },+ { key: 'source_uid_validity', label: 'Source UID Validity' },+ {+ key: 'target_uid_validity',+ label: 'Target UID Validity',+ description: 'Present only when the server supports UIDPLUS.',+ },+ {+ key: 'results',+ label: 'Results',+ labelKey: 'uid',+ listItems: [+ { key: 'uid', label: 'Original UID', format: 'number' },+ {+ key: 'new_uid',+ label: 'New UID',+ format: 'number',+ description: 'UID in the target folder. Present only when the server supports UIDPLUS.',+ },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'not_found_uids', label: 'UIDs Not Found' },+];++const specialDestinationFields: OutputSchema['fields'] = [+ { key: 'destination_folder', label: 'Destination Folder' },+ {+ key: 'special_use_source',+ label: 'Special-Use Source',+ description:+ 'extension when the server flags the folder, name when the role was guessed from the folder name.',+ },+];+export const newEmailTriggerOutputSchema: OutputSchema = {fields: [{ key: 'subject', label: 'Subject' },@@ -63,7 +122,215 @@ export const moveEmailActionOutputSchema: OutputSchema = {label: 'New Message UID',format: 'number',description:- 'UID of the message in the target folder. Absent when the server reports no new UID, in which case Success is false.',+ 'UID of the message in the target folder. Absent when the server does not report a new UID.',+ },+ ],+};++export const markEmailReadActionOutputSchema: OutputSchema = {+ fields: [{ key: 'success', label: 'Success', format: 'boolean' }],+};++export const deleteEmailActionOutputSchema: OutputSchema = {+ fields: [{ key: 'success', label: 'Success', format: 'boolean' }],+};++export const listFoldersOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'folders',+ label: 'Folders',+ labelKey: 'path',+ listItems: [+ { key: 'path', label: 'Path' },+ { key: 'name', label: 'Name' },+ { key: 'delimiter', label: 'Delimiter' },+ { key: 'parent_path', label: 'Parent Path' },+ { key: 'special_use', label: 'Special Use' },+ { key: 'special_use_source', label: 'Special-Use Source' },+ { key: 'flags', label: 'Flags' },+ { key: 'subscribed', label: 'Subscribed', format: 'boolean' },+ {+ key: 'messages',+ label: 'Messages',+ format: 'number',+ description: 'Present only when Include Message Counts is on.',+ },+ {+ key: 'unseen',+ label: 'Unread',+ format: 'number',+ description: 'Present only when Include Message Counts is on.',+ },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const getFolderStatusOutputSchema: OutputSchema = {+ fields: [+ { key: 'path', label: 'Path' },+ { key: 'messages', label: 'Messages', format: 'number' },+ { key: 'unseen', label: 'Unread', format: 'number' },+ { key: 'recent', label: 'Recent', format: 'number' },+ { key: 'uid_next', label: 'Next UID', format: 'number' },+ { key: 'uid_validity', label: 'UID Validity' },+ {+ key: 'highest_modseq',+ label: 'Highest Mod-Sequence',+ description: 'Present only when the server supports CONDSTORE.',+ },+ ],+};++export const createFolderOutputSchema: OutputSchema = {+ fields: [+ { key: 'path', label: 'Path' },+ {+ key: 'created',+ label: 'Created',+ format: 'boolean',+ description: 'False when the folder already existed.',+ },+ ],+};++export const renameFolderOutputSchema: OutputSchema = {+ fields: [+ { key: 'path', label: 'Old Path' },+ { key: 'new_path', label: 'New Path' },+ ],+};++export const deleteFolderOutputSchema: OutputSchema = {+ fields: [+ { key: 'path', label: 'Path' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ ],+};++export const getQuotaOutputSchema: OutputSchema = {+ fields: [+ { key: 'path', label: 'Path' },+ { key: 'has_quota', label: 'Has Quota', format: 'boolean' },+ { key: 'storage_used_bytes', label: 'Storage Used', format: 'filesize' },+ { key: 'storage_limit_bytes', label: 'Storage Limit', format: 'filesize' },+ { key: 'messages_used', label: 'Messages Used', format: 'number' },+ { key: 'messages_limit', label: 'Messages Limit', format: 'number' },+ ],+};++export const searchEmailsOutputSchema: OutputSchema = {+ fields: [+ { key: 'folder', label: 'Folder' },+ { key: 'uid_validity', label: 'UID Validity' },+ { key: 'total_matches', label: 'Total Matches', format: 'number' },+ { key: 'count', label: 'Returned', format: 'number' },+ { key: 'emails', label: 'Emails', labelKey: 'subject', listItems: emailSummaryFields },+ ],+};++export const getEmailOutputSchema: OutputSchema = {+ fields: [+ { key: 'folder', label: 'Folder' },+ { key: 'uid', label: 'Message UID', format: 'number' },+ { key: 'uid_validity', label: 'UID Validity' },+ { key: 'message_id', label: 'Message-ID' },+ { key: 'in_reply_to', label: 'In Reply To' },+ { key: 'references', label: 'References' },+ { key: 'subject', label: 'Subject' },+ { key: 'date', label: 'Date', format: 'datetime' },+ { key: 'internal_date', label: 'Received At', format: 'datetime' },+ { key: 'from_name', label: 'From Name' },+ { key: 'from_address', label: 'From Email', format: 'email' },+ { key: 'to', label: 'To', labelKey: 'address', listItems: recipientListItems },+ { key: 'cc', label: 'Cc', labelKey: 'address', listItems: recipientListItems },+ { key: 'bcc', label: 'Bcc', labelKey: 'address', listItems: recipientListItems },+ { key: 'reply_to', label: 'Reply To', labelKey: 'address', listItems: recipientListItems },+ { key: 'text', label: 'Text Body' },+ { key: 'html', label: 'HTML Body', format: 'html' },+ { key: 'flags', label: 'Flags' },+ { key: 'seen', label: 'Read', format: 'boolean' },+ { key: 'flagged', label: 'Flagged', format: 'boolean' },+ { key: 'size', label: 'Size', format: 'filesize' },+ {+ key: 'attachments',+ label: 'Attachments',+ labelKey: 'filename',+ listItems: [+ { key: 'filename', label: 'File Name' },+ { key: 'content_type', label: 'Content Type' },+ { key: 'size', label: 'Size', format: 'filesize' },+ {+ key: 'file',+ label: 'File',+ description: 'Stored file reference; pass it to any action that accepts a file.',+ },+ ],+ },+ ],+};++export const updateEmailFlagsOutputSchema: OutputSchema = {+ fields: [+ { key: 'folder', label: 'Folder' },+ { key: 'uid_validity', label: 'UID Validity' },+ {+ key: 'emails',+ label: 'Emails',+ labelKey: 'uid',+ listItems: [+ { key: 'uid', label: 'Message UID', format: 'number' },+ { key: 'flags', label: 'Flags' },+ { key: 'seen', label: 'Read', format: 'boolean' },+ { key: 'flagged', label: 'Flagged', format: 'boolean' },+ { key: 'answered', label: 'Answered', format: 'boolean' },+ ],+ },+ { key: 'not_found_uids', label: 'UIDs Not Found' },+ ],+};++export const moveEmailsOutputSchema: OutputSchema = {+ fields: [...transferFields, { key: 'target_folder', label: 'Target Folder' }],+};++export const copyEmailsOutputSchema: OutputSchema = {+ fields: [...transferFields, { key: 'target_folder', label: 'Target Folder' }],+};++export const trashEmailsOutputSchema: OutputSchema = {+ fields: [...transferFields, ...specialDestinationFields],+};++export const archiveEmailsOutputSchema: OutputSchema = {+ fields: [...transferFields, ...specialDestinationFields],+};++export const deleteEmailsOutputSchema: OutputSchema = {+ fields: [+ { key: 'folder', label: 'Folder' },+ { key: 'deleted_uids', label: 'Deleted UIDs' },+ {+ key: 'not_deleted_uids',+ label: 'UIDs Not Deleted',+ description: 'UIDs that still exist after the delete.',+ },+ { key: 'not_found_uids', label: 'UIDs Not Found' },+ ],+};++export const createDraftOutputSchema: OutputSchema = {+ fields: [+ { key: 'folder', label: 'Folder' },+ {+ key: 'uid',+ label: 'Draft UID',+ format: 'number',+ description: 'UID of the saved draft, when the server reports it.',},+ { key: 'uid_validity', label: 'UID Validity' },+ { key: 'message_id', label: 'Message-ID' },],};diff --git a/packages/pieces/community/woocommerce/package.json b/packages/pieces/community/woocommerce/package.jsonindex 463f2ada63c..21f797e9d20 100644--- a/packages/pieces/community/woocommerce/package.json+++ b/packages/pieces/community/woocommerce/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-woocommerce",- "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/woocommerce/src/i18n/translation.json b/packages/pieces/community/woocommerce/src/i18n/translation.jsonindex 8c9f91cc59f..1f2de1f40ec 100644--- a/packages/pieces/community/woocommerce/src/i18n/translation.json+++ b/packages/pieces/community/woocommerce/src/i18n/translation.json@@ -198,5 +198,304 @@"Triggers when an existing coupon is deleted.": "Triggers when an existing coupon is deleted.","Triggers when new customer is created.": "Triggers when new customer is created.","Triggers when an existing customer is updated.": "Triggers when an existing customer is updated.",- "Triggers when an existing customer is deleted.": "Triggers when an existing customer is deleted."-}\ No newline at end of file+ "Triggers when an existing customer is deleted.": "Triggers when an existing customer is deleted.",+ "Add a private or customer-facing note to an order.": "Add a private or customer-facing note to an order.",+ "Batch Update Products": "Batch Update Products",+ "Update the price, stock or status of up to 100 products in one call.": "Update the price, stock or status of up to 100 products in one call.",+ "Updates": "Updates",+ "One entry per product, 1 to 100 entries. Each needs the product id and at least one field to change.": "One entry per product, 1 to 100 entries. Each needs the product id and at least one field to change.",+ "Decimal string, e.g. 19.99.": "Decimal string, e.g. 19.99.",+ "Decimal string, e.g. 14.99.": "Decimal string, e.g. 14.99.",+ "Units in stock. Turns on stock management for that product.": "Units in stock. Turns on stock management for that product.",+ "Pending review": "Pending review",+ "Create a discount coupon.": "Create a discount coupon.",+ "Code": "Code",+ "Coupon code customers enter at checkout. Must be unique.": "Coupon code customers enter at checkout. Must be unique.",+ "Percentage off the cart, a fixed amount off the cart, or a fixed amount off each product.": "Percentage off the cart, a fixed amount off the cart, or a fixed amount off each product.",+ "Discount amount as a decimal string: a percentage for percentage coupons, otherwise money, e.g. 10.": "Discount amount as a decimal string: a percentage for percentage coupons, otherwise money, e.g. 10.",+ "Internal description of the coupon.": "Internal description of the coupon.",+ "Expiry Date": "Expiry Date",+ "The coupon stops working after this date.": "The coupon stops working after this date.",+ "Minimum cart subtotal needed to use the coupon, e.g. 50.00.": "Minimum cart subtotal needed to use the coupon, e.g. 50.00.",+ "Maximum Spend": "Maximum Spend",+ "Maximum cart subtotal allowed when using the coupon.": "Maximum cart subtotal allowed when using the coupon.",+ "Individual Use Only": "Individual Use Only",+ "Yes stops this coupon from being combined with other coupons. Leave empty for the store default (No).": "Yes stops this coupon from being combined with other coupons. Leave empty for the store default (No).",+ "Yes": "Yes",+ "No": "No",+ "Exclude Sale Items": "Exclude Sale Items",+ "Yes stops the coupon from applying to items already on sale. Leave empty for the store default (No).": "Yes stops the coupon from applying to items already on sale. Leave empty for the store default (No).",+ "Free Shipping": "Free Shipping",+ "Yes lets the coupon unlock free shipping, if a free-shipping method is set up. Leave empty for the store default (No).": "Yes lets the coupon unlock free shipping, if a free-shipping method is set up. Leave empty for the store default (No).",+ "How many times the coupon can be used in total.": "How many times the coupon can be used in total.",+ "Usage Limit Per Customer": "Usage Limit Per Customer",+ "How many times each customer can use the coupon.": "How many times each customer can use the coupon.",+ "Product IDs": "Product IDs",+ "Ids of the only products the coupon applies to.": "Ids of the only products the coupon applies to.",+ "Excluded Product IDs": "Excluded Product IDs",+ "Ids of products the coupon never applies to.": "Ids of products the coupon never applies to.",+ "Allowed Emails": "Allowed Emails",+ "Only customers with these billing emails can use the coupon.": "Only customers with these billing emails can use the coupon.",+ "Create a customer account. Only the email is required.": "Create a customer account. Only the email is required.",+ "Email address of the customer. Must not already be registered.": "Email address of the customer. Must not already be registered.",+ "Login name. Generated from the email when empty and the store allows it.": "Login name. Generated from the email when empty and the store allows it.",+ "Account password. Generated when empty and the store allows it.": "Account password. Generated when empty and the store allows it.",+ "Billing Company": "Billing Company",+ "Billing Address Line 1": "Billing Address Line 1",+ "Billing Address Line 2": "Billing Address Line 2",+ "Billing State": "Billing State",+ "State or county code, e.g. CA.": "State or county code, e.g. CA.",+ "Two-letter ISO country code, e.g. US.": "Two-letter ISO country code, e.g. US.",+ "Shipping Company": "Shipping Company",+ "Shipping Address Line 1": "Shipping Address Line 1",+ "Shipping Address Line 2": "Shipping Address Line 2",+ "Shipping City": "Shipping City",+ "Shipping State": "Shipping State",+ "Shipping Postcode": "Shipping Postcode",+ "Shipping Country": "Shipping Country",+ "Create an order with one or more line items.": "Create an order with one or more line items.",+ "Quantity": "Quantity",+ "Create Order Refund": "Create Order Refund",+ "Refund an amount on an order. By default the refund is only recorded in WooCommerce.": "Refund an amount on an order. By default the refund is only recorded in WooCommerce.",+ "Id of the order to refund.": "Id of the order to refund.",+ "Amount to refund as a decimal string, e.g. 10.00. Cannot exceed what is left to refund on the order.": "Amount to refund as a decimal string, e.g. 10.00. Cannot exceed what is left to refund on the order.",+ "Reason": "Reason",+ "Reason for the refund, stored with the refund.": "Reason for the refund, stored with the refund.",+ "Refund Via Gateway": "Refund Via Gateway",+ "When on, the money is actually sent back to the customer through the payment gateway. When off (the default) the refund is only recorded in WooCommerce.": "When on, the money is actually sent back to the customer through the payment gateway. When off (the default) the refund is only recorded in WooCommerce.",+ "Create a product. Only the name is required.": "Create a product. Only the name is required.",+ "Product name.": "Product name.",+ "Product Type": "Product Type",+ "Defaults to simple.": "Defaults to simple.",+ "External / affiliate": "External / affiliate",+ "Defaults to published, which makes the product visible in the shop.": "Defaults to published, which makes the product visible in the shop.",+ "Price as a decimal string, e.g. 19.99.": "Price as a decimal string, e.g. 19.99.",+ "Discounted price as a decimal string. Must be lower than the regular price.": "Discounted price as a decimal string. Must be lower than the regular price.",+ "SKU": "SKU",+ "Stock keeping unit. Must be unique in the store.": "Stock keeping unit. Must be unique in the store.",+ "Full product description. HTML is allowed.": "Full product description. HTML is allowed.",+ "Short Description": "Short Description",+ "Short summary shown near the price. HTML is allowed.": "Short summary shown near the price. HTML is allowed.",+ "Category IDs": "Category IDs",+ "Ids of the categories to put the product in. Find them with list_product_categories.": "Ids of the categories to put the product in. Find them with list_product_categories.",+ "Tag IDs": "Tag IDs",+ "Ids of the tags to attach. Find them with list_product_tags.": "Ids of the tags to attach. Find them with list_product_tags.",+ "Image URLs": "Image URLs",+ "Public image URLs. The first one becomes the main image. The store downloads each one, so an unreachable URL fails the call.": "Public image URLs. The first one becomes the main image. The store downloads each one, so an unreachable URL fails the call.",+ "Units in stock. Setting it turns on stock management for the product.": "Units in stock. Setting it turns on stock management for the product.",+ "Stock Status": "Stock Status",+ "Stock status. Ignored when a stock quantity is set, because the quantity decides it.": "Stock status. Ignored when a stock quantity is set, because the quantity decides it.",+ "In stock": "In stock",+ "Out of stock": "Out of stock",+ "On backorder": "On backorder",+ "Create Product Category": "Create Product Category",+ "Create a product category.": "Create a product category.",+ "Category name.": "Category name.",+ "Parent Category ID": "Parent Category ID",+ "Id of the parent category. Leave empty for a top-level category.": "Id of the parent category. Leave empty for a top-level category.",+ "Slug": "Slug",+ "URL-friendly name. Generated from the name when empty.": "URL-friendly name. Generated from the name when empty.",+ "Category description. HTML is allowed.": "Category description. HTML is allowed.",+ "Create Product Tag": "Create Product Tag",+ "Create a product tag.": "Create a product tag.",+ "Tag name.": "Tag name.",+ "Tag description.": "Tag description.",+ "Delete Coupon": "Delete Coupon",+ "Move a coupon to the trash, or delete it permanently.": "Move a coupon to the trash, or delete it permanently.",+ "Id of the coupon to delete.": "Id of the coupon to delete.",+ "Delete Permanently": "Delete Permanently",+ "When off (the default) the coupon is moved to the trash and can be restored from the WordPress admin. When on it is deleted for good.": "When off (the default) the coupon is moved to the trash and can be restored from the WordPress admin. When on it is deleted for good.",+ "Delete Customer": "Delete Customer",+ "Permanently delete a customer account.": "Permanently delete a customer account.",+ "Id of the customer to delete. Find it with list_customers.": "Id of the customer to delete. Find it with list_customers.",+ "Reassign To User ID": "Reassign To User ID",+ "Optional id of another user who takes over the posts owned by the deleted customer. Must differ from the customer id.": "Optional id of another user who takes over the posts owned by the deleted customer. Must differ from the customer id.",+ "Delete Order": "Delete Order",+ "Move an order to the trash, or delete it permanently.": "Move an order to the trash, or delete it permanently.",+ "Id of the order to delete. Find it with list_orders.": "Id of the order to delete. Find it with list_orders.",+ "When off (the default) the order is moved to the trash and can be restored from the WordPress admin. When on it is deleted for good.": "When off (the default) the order is moved to the trash and can be restored from the WordPress admin. When on it is deleted for good.",+ "Delete Order Note": "Delete Order Note",+ "Permanently delete a note from an order.": "Permanently delete a note from an order.",+ "Id of the order the note belongs to.": "Id of the order the note belongs to.",+ "Note ID": "Note ID",+ "Id of the note to delete.": "Id of the note to delete.",+ "Delete Product": "Delete Product",+ "Move a product to the trash, or delete it permanently.": "Move a product to the trash, or delete it permanently.",+ "Id of the product to delete. Find it with list_products.": "Id of the product to delete. Find it with list_products.",+ "When off (the default) the product is moved to the trash and can be restored from the WordPress admin. When on it is deleted for good.": "When off (the default) the product is moved to the trash and can be restored from the WordPress admin. When on it is deleted for good.",+ "Get Coupon": "Get Coupon",+ "Get a coupon by its ID.": "Get a coupon by its ID.",+ "Get a customer by their ID.": "Get a customer by their ID.",+ "Get an order by its ID.": "Get an order by its ID.",+ "Get Order Totals Report": "Get Order Totals Report",+ "Get the number of orders in each status.": "Get the number of orders in each status.",+ "Get Product": "Get Product",+ "Get a product by its ID.": "Get a product by its ID.",+ "Get Product Variation": "Get Product Variation",+ "Get one variation of a variable product.": "Get one variation of a variable product.",+ "Id of the parent variable product.": "Id of the parent variable product.",+ "Variation ID": "Variation ID",+ "Id of the variation.": "Id of the variation.",+ "Get Sales Report": "Get Sales Report",+ "Get sales totals for a period or date range.": "Get sales totals for a period or date range.",+ "Period": "Period",+ "Preset period to report on. Leave empty when using a date range; if both are empty the current week is used.": "Preset period to report on. Leave empty when using a date range; if both are empty the current week is used.",+ "This week": "This week",+ "This month": "This month",+ "Last month": "Last month",+ "This year": "This year",+ "Start Date": "Start Date",+ "First day of a custom range, as YYYY-MM-DD. Use together with End Date instead of Period.": "First day of a custom range, as YYYY-MM-DD. Use together with End Date instead of Period.",+ "End Date": "End Date",+ "Last day of a custom range, as YYYY-MM-DD. Use together with Start Date instead of Period.": "Last day of a custom range, as YYYY-MM-DD. Use together with Start Date instead of Period.",+ "Get Top Sellers Report": "Get Top Sellers Report",+ "Get the best-selling products for a period or date range.": "Get the best-selling products for a period or date range.",+ "List Coupons": "List Coupons",+ "List coupons, or find one by its exact code.": "List coupons, or find one by its exact code.",+ "Exact coupon code to find.": "Exact coupon code to find.",+ "Search": "Search",+ "Text to match against coupon codes and descriptions.": "Text to match against coupon codes and descriptions.",+ "Only return coupons created after this date and time (ISO 8601).": "Only return coupons created after this date and time (ISO 8601).",+ "Created Before": "Created Before",+ "Only return coupons created before this date and time (ISO 8601).": "Only return coupons created before this date and time (ISO 8601).",+ "Page": "Page",+ "Page number, starting at 1. If a page comes back with exactly per_page items, request the next page to see more.": "Page number, starting at 1. If a page comes back with exactly per_page items, request the next page to see more.",+ "Per Page": "Per Page",+ "Number of items per page, from 1 to 100. Defaults to 10.": "Number of items per page, from 1 to 100. Defaults to 10.",+ "List Customers": "List Customers",+ "List customers, filtered by email, text or role.": "List customers, filtered by email, text or role.",+ "Exact email address to match.": "Exact email address to match.",+ "Text to match against names, usernames and emails.": "Text to match against names, usernames and emails.",+ "Role": "Role",+ "WordPress role to return. Defaults to all roles.": "WordPress role to return. Defaults to all roles.",+ "All roles": "All roles",+ "Customer": "Customer",+ "Subscriber": "Subscriber",+ "Shop manager": "Shop manager",+ "Administrator": "Administrator",+ "Sort By": "Sort By",+ "Field to sort by. Defaults to name.": "Field to sort by. Defaults to name.",+ "ID": "ID",+ "Registration date": "Registration date",+ "Sort Direction": "Sort Direction",+ "Ascending or descending. Defaults to ascending.": "Ascending or descending. Defaults to ascending.",+ "Ascending": "Ascending",+ "Descending": "Descending",+ "List Order Notes": "List Order Notes",+ "List the notes on an order.": "List the notes on an order.",+ "Id of the order.": "Id of the order.",+ "Note Type": "Note Type",+ "Which notes to return. Defaults to all.": "Which notes to return. Defaults to all.",+ "All notes": "All notes",+ "Notes sent to the customer": "Notes sent to the customer",+ "Private notes": "Private notes",+ "List Order Refunds": "List Order Refunds",+ "List the refunds recorded on an order.": "List the refunds recorded on an order.",+ "List Orders": "List Orders",+ "List orders, filtered by status, customer, product, text or date range.": "List orders, filtered by status, customer, product, text or date range.",+ "Only return orders with this status. Leave empty for any status except trash.": "Only return orders with this status. Leave empty for any status except trash.",+ "Pending payment": "Pending payment",+ "Only return orders placed by this customer. Find the id with list_customers.": "Only return orders placed by this customer. Find the id with list_customers.",+ "Only return orders that contain this product.": "Only return orders that contain this product.",+ "Text to match against order fields such as the billing name or email.": "Text to match against order fields such as the billing name or email.",+ "Only return orders created after this date and time (ISO 8601).": "Only return orders created after this date and time (ISO 8601).",+ "Only return orders created before this date and time (ISO 8601).": "Only return orders created before this date and time (ISO 8601).",+ "Field to sort by. Defaults to date.": "Field to sort by. Defaults to date.",+ "Date": "Date",+ "Title": "Title",+ "Ascending or descending. Defaults to descending.": "Ascending or descending. Defaults to descending.",+ "List Payment Gateways": "List Payment Gateways",+ "List the payment methods installed in the store and whether they are enabled.": "List the payment methods installed in the store and whether they are enabled.",+ "List Product Categories": "List Product Categories",+ "List product categories, optionally filtered by name, slug or parent.": "List product categories, optionally filtered by name, slug or parent.",+ "Text to match against category names.": "Text to match against category names.",+ "Exact category slug.": "Exact category slug.",+ "Only return direct children of this category. Use 0 for top-level categories.": "Only return direct children of this category. Use 0 for top-level categories.",+ "Hide Empty": "Hide Empty",+ "When on, categories without products are left out.": "When on, categories without products are left out.",+ "List Product Reviews": "List Product Reviews",+ "List product reviews, including ones waiting for moderation.": "List product reviews, including ones waiting for moderation.",+ "Only return reviews of this product.": "Only return reviews of this product.",+ "Moderation status to return. Defaults to all.": "Moderation status to return. Defaults to all.",+ "All": "All",+ "Approved": "Approved",+ "On hold (awaiting moderation)": "On hold (awaiting moderation)",+ "Spam": "Spam",+ "Reviewer Email": "Reviewer Email",+ "Only return reviews written with this email address.": "Only return reviews written with this email address.",+ "Text to match against the review content.": "Text to match against the review content.",+ "List Product Tags": "List Product Tags",+ "List product tags, optionally filtered by name or slug.": "List product tags, optionally filtered by name or slug.",+ "Text to match against tag names.": "Text to match against tag names.",+ "Exact tag slug.": "Exact tag slug.",+ "When on, tags without products are left out.": "When on, tags without products are left out.",+ "List Product Variations": "List Product Variations",+ "List the variations of a variable product.": "List the variations of a variable product.",+ "Id of the variable product. Find it with list_products.": "Id of the variable product. Find it with list_products.",+ "Only return the variation with this SKU.": "Only return the variation with this SKU.",+ "Only return variations with this stock status.": "Only return variations with this stock status.",+ "List Products": "List Products",+ "List products, filtered by text, SKU, status, category, tag, stock or price.": "List products, filtered by text, SKU, status, category, tag, stock or price.",+ "Text to match against product names and content.": "Text to match against product names and content.",+ "Exact SKU to match. Separate several SKUs with commas.": "Exact SKU to match. Separate several SKUs with commas.",+ "Only return products with this status. Leave empty for any status.": "Only return products with this status. Leave empty for any status.",+ "Only return products of this type.": "Only return products of this type.",+ "Category ID": "Category ID",+ "Only return products in this category. Find ids with list_product_categories.": "Only return products in this category. Find ids with list_product_categories.",+ "Tag ID": "Tag ID",+ "Only return products with this tag. Find ids with list_product_tags.": "Only return products with this tag. Find ids with list_product_tags.",+ "Only return products with this stock status.": "Only return products with this stock status.",+ "On Sale": "On Sale",+ "Yes returns only products on sale, No only products not on sale. Leave empty for both.": "Yes returns only products on sale, No only products not on sale. Leave empty for both.",+ "Minimum Price": "Minimum Price",+ "Only return products priced at or above this amount, e.g. 10.00.": "Only return products priced at or above this amount, e.g. 10.00.",+ "Maximum Price": "Maximum Price",+ "Only return products priced at or below this amount, e.g. 99.99.": "Only return products priced at or below this amount, e.g. 99.99.",+ "Price": "Price",+ "Popularity": "Popularity",+ "Rating": "Rating",+ "Change the amount, type, expiry or limits of a coupon.": "Change the amount, type, expiry or limits of a coupon.",+ "Change the name, email or billing details of a customer.": "Change the name, email or billing details of a customer.",+ "Change the status, customer note or transaction ID of an order.": "Change the status, customer note or transaction ID of an order.",+ "Change selected fields of a product. Fields left empty are not changed.": "Change selected fields of a product. Fields left empty are not changed.",+ "Id of the product to update. Find it with list_products.": "Id of the product to update. Find it with list_products.",+ "New product name.": "New product name.",+ "New SKU. Must be unique in the store.": "New SKU. Must be unique in the store.",+ "New status.": "New status.",+ "New regular price as a decimal string, e.g. 19.99.": "New regular price as a decimal string, e.g. 19.99.",+ "New sale price as a decimal string. To remove a sale use End Sale instead.": "New sale price as a decimal string. To remove a sale use End Sale instead.",+ "End Sale": "End Sale",+ "When on, clears the sale price so the product sells at its regular price again.": "When on, clears the sale price so the product sells at its regular price again.",+ "New number of units in stock. Setting it turns on stock management.": "New number of units in stock. Setting it turns on stock management.",+ "New stock status. Ignored when a stock quantity is set.": "New stock status. Ignored when a stock quantity is set.",+ "Featured": "Featured",+ "Yes marks the product as featured, No removes the mark. Leave empty to keep it.": "Yes marks the product as featured, No removes the mark. Leave empty to keep it.",+ "Catalog Visibility": "Catalog Visibility",+ "Where the product is shown.": "Where the product is shown.",+ "Shop and search results": "Shop and search results",+ "Shop only": "Shop only",+ "Search results only": "Search results only",+ "Hidden": "Hidden",+ "New full description. HTML is allowed.": "New full description. HTML is allowed.",+ "New short description. HTML is allowed.": "New short description. HTML is allowed.",+ "Replaces all of the product categories with these ids. Include the ones to keep.": "Replaces all of the product categories with these ids. Include the ones to keep.",+ "Replaces all of the product tags with these ids. Include the ones to keep.": "Replaces all of the product tags with these ids. Include the ones to keep.",+ "Moderate Product Review": "Moderate Product Review",+ "Approve, hold, mark as spam or trash a product review.": "Approve, hold, mark as spam or trash a product review.",+ "Review ID": "Review ID",+ "Id of the review.": "Id of the review.",+ "New moderation status.": "New moderation status.",+ "Approve": "Approve",+ "Hold (unapprove)": "Hold (unapprove)",+ "Mark as spam": "Mark as spam",+ "Not spam": "Not spam",+ "Move to trash": "Move to trash",+ "Restore from trash": "Restore from trash",+ "Update Product Variation": "Update Product Variation",+ "Change selected fields of one variation. Fields left empty are not changed.": "Change selected fields of one variation. Fields left empty are not changed.",+ "Id of the variation to update.": "Id of the variation to update.",+ "When on, clears the sale price so the variation sells at its regular price again.": "When on, clears the sale price so the variation sells at its regular price again.",+ "New status. Private hides the variation from customers.": "New status. Private hides the variation from customers.",+ "New number of units in stock. Setting it turns on stock management for this variation.": "New number of units in stock. Setting it turns on stock management for this variation.",+ "New variation description.": "New variation description."+}diff --git a/packages/pieces/community/woocommerce/src/index.ts b/packages/pieces/community/woocommerce/src/index.tsindex 5115ce1ea07..3a2d6f72875 100644--- a/packages/pieces/community/woocommerce/src/index.ts+++ b/packages/pieces/community/woocommerce/src/index.ts@@ -21,6 +21,45 @@ import { wooCreateCustomer } from './lib/actions/create-customer';import { wooCreateProduct } from './lib/actions/create-product';import { wooFindCustomer } from './lib/actions/find-customer';import { wooFindProduct } from './lib/actions/find-product';+import { wooAiAddOrderNote } from './lib/actions/ai/add-order-note';+import { wooAiBatchUpdateProducts } from './lib/actions/ai/batch-update-products';+import { wooAiCreateCoupon } from './lib/actions/ai/create-coupon';+import { wooAiCreateCustomer } from './lib/actions/ai/create-customer';+import { wooAiCreateOrder } from './lib/actions/ai/create-order';+import { wooAiCreateOrderRefund } from './lib/actions/ai/create-order-refund';+import { wooAiCreateProduct } from './lib/actions/ai/create-product';+import { wooAiCreateProductCategory } from './lib/actions/ai/create-product-category';+import { wooAiCreateProductTag } from './lib/actions/ai/create-product-tag';+import { wooAiDeleteCoupon } from './lib/actions/ai/delete-coupon';+import { wooAiDeleteCustomer } from './lib/actions/ai/delete-customer';+import { wooAiDeleteOrder } from './lib/actions/ai/delete-order';+import { wooAiDeleteOrderNote } from './lib/actions/ai/delete-order-note';+import { wooAiDeleteProduct } from './lib/actions/ai/delete-product';+import { wooAiGetCoupon } from './lib/actions/ai/get-coupon';+import { wooAiGetCustomer } from './lib/actions/ai/get-customer';+import { wooAiGetOrder } from './lib/actions/ai/get-order';+import { wooAiGetOrderTotalsReport } from './lib/actions/ai/get-order-totals-report';+import { wooAiGetProduct } from './lib/actions/ai/get-product';+import { wooAiGetProductVariation } from './lib/actions/ai/get-product-variation';+import { wooAiGetSalesReport } from './lib/actions/ai/get-sales-report';+import { wooAiGetTopSellersReport } from './lib/actions/ai/get-top-sellers-report';+import { wooAiListCoupons } from './lib/actions/ai/list-coupons';+import { wooAiListCustomers } from './lib/actions/ai/list-customers';+import { wooAiListOrderNotes } from './lib/actions/ai/list-order-notes';+import { wooAiListOrderRefunds } from './lib/actions/ai/list-order-refunds';+import { wooAiListOrders } from './lib/actions/ai/list-orders';+import { wooAiListPaymentGateways } from './lib/actions/ai/list-payment-gateways';+import { wooAiListProductCategories } from './lib/actions/ai/list-product-categories';+import { wooAiListProductReviews } from './lib/actions/ai/list-product-reviews';+import { wooAiListProductTags } from './lib/actions/ai/list-product-tags';+import { wooAiListProductVariations } from './lib/actions/ai/list-product-variations';+import { wooAiListProducts } from './lib/actions/ai/list-products';+import { wooAiUpdateCoupon } from './lib/actions/ai/update-coupon';+import { wooAiUpdateCustomer } from './lib/actions/ai/update-customer';+import { wooAiUpdateOrder } from './lib/actions/ai/update-order';+import { wooAiUpdateProduct } from './lib/actions/ai/update-product';+import { wooAiUpdateProductReview } from './lib/actions/ai/update-product-review';+import { wooAiUpdateProductVariation } from './lib/actions/ai/update-product-variation';import { triggers } from './lib/triggers';import { wooAuth } from './lib/auth';@@ -42,7 +81,7 @@ export const woocommerce = createPiece({logoUrl: 'https://cdn.activepieces.com/pieces/woocommerce.png',categories: [PieceCategory.COMMERCE],auth: wooAuth,- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',authors: ["TaskMagicKyle","kishanprmr","MoShizzle","khaledmashaly","abuaboud"],actions: [wooCreateCustomer,@@ -60,6 +99,45 @@ export const woocommerce = createPiece({wooCreateOrder,wooUpdateOrder,wooAddOrderNote,+ wooAiAddOrderNote,+ wooAiBatchUpdateProducts,+ wooAiCreateCoupon,+ wooAiCreateCustomer,+ wooAiCreateOrder,+ wooAiCreateOrderRefund,+ wooAiCreateProduct,+ wooAiCreateProductCategory,+ wooAiCreateProductTag,+ wooAiDeleteCoupon,+ wooAiDeleteCustomer,+ wooAiDeleteOrder,+ wooAiDeleteOrderNote,+ wooAiDeleteProduct,+ wooAiGetCoupon,+ wooAiGetCustomer,+ wooAiGetOrder,+ wooAiGetOrderTotalsReport,+ wooAiGetProduct,+ wooAiGetProductVariation,+ wooAiGetSalesReport,+ wooAiGetTopSellersReport,+ wooAiListCoupons,+ wooAiListCustomers,+ wooAiListOrderNotes,+ wooAiListOrderRefunds,+ wooAiListOrders,+ wooAiListPaymentGateways,+ wooAiListProductCategories,+ wooAiListProductReviews,+ wooAiListProductTags,+ wooAiListProductVariations,+ wooAiListProducts,+ wooAiUpdateCoupon,+ wooAiUpdateCustomer,+ wooAiUpdateOrder,+ wooAiUpdateProduct,+ wooAiUpdateProductReview,+ wooAiUpdateProductVariation,createCustomApiCallAction({baseUrl: (auth) => (auth?.props.baseUrl ?? ''),auth: wooAuth,diff --git a/packages/pieces/community/woocommerce/src/lib/actions/add-order-note.ts b/packages/pieces/community/woocommerce/src/lib/actions/add-order-note.tsindex f4d1fd5c894..0571ab9e6b0 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/add-order-note.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/add-order-note.ts@@ -14,7 +14,7 @@ export const wooAddOrderNote = createAction({classification: 'WRITE',displayName: 'Add Order Note',description: 'Add a note to an order, optionally visible to the customer',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Adds a note to an existing WooCommerce order. A private note is visible only to store staff; a customer note is emailed to the customer and shown on the order page. Use when an agent needs to record why something happened on an order or communicate an update. Not idempotent: each call appends another note.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/add-order-note.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/add-order-note.tsnew file mode 100644index 00000000000..7e48f3100db--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/add-order-note.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { addOrderNoteOutputSchema } from '../../output-schemas';+import { wooAddOrderNote } from '../add-order-note';++export const wooAiAddOrderNote = createAction({+ name: 'add_order_note',+ classification: 'WRITE',+ displayName: 'Add Order Note',+ description: 'Add a private or customer-facing note to an order.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Adds a note to one order: a private note for staff, or, with customer note on, a note that is emailed to the customer straight away. Read existing notes with list_order_notes. Each call adds another note, so a retry duplicates it (and resends the email).',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: addOrderNoteOutputSchema,+ props: wooAddOrderNote.props,+ run: wooAddOrderNote.run,+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/batch-update-products.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/batch-update-products.tsnew file mode 100644index 00000000000..00738d11805--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/batch-update-products.ts@@ -0,0 +1,95 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { batchUpdateProductsOutputSchema } from '../../output-schemas';++export const wooAiBatchUpdateProducts = createAction({+ name: 'batch_update_products',+ classification: 'WRITE',+ displayName: 'Batch Update Products',+ description: 'Update the price, stock or status of up to 100 products in one call.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates prices, stock quantity or status of 1 to 100 products in a single request; only the fields given for each product change. The call succeeds as a whole even when some products fail, so check each returned entry for an error. For other fields, or a single product, use update_product.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: batchUpdateProductsOutputSchema,+ props: {+ updates: Property.Array({+ displayName: 'Updates',+ description: 'One entry per product, 1 to 100 entries. Each needs the product id and at least one field to change.',+ required: true,+ properties: {+ id: Property.Number({+ displayName: 'Product ID',+ required: true,+ }),+ regular_price: Property.ShortText({+ displayName: 'Regular Price',+ description: 'Decimal string, e.g. 19.99.',+ required: false,+ }),+ sale_price: Property.ShortText({+ displayName: 'Sale Price',+ description: 'Decimal string, e.g. 14.99.',+ required: false,+ }),+ stock_quantity: Property.Number({+ displayName: 'Stock Quantity',+ description: 'Units in stock. Turns on stock management for that product.',+ required: false,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ required: false,+ options: { options: wooProps.productStatusOptions },+ }),+ },+ }),+ },+ async run(context) {+ const updates = context.propsValue.updates ?? [];+ if (updates.length === 0 || updates.length > 100) {+ throw new Error(`Updates must contain between 1 and 100 entries; got ${updates.length}.`);+ }+ const items = updates.map((item, index) => toBatchItem({ item, index }));+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.POST,+ path: '/products/batch',+ body: { update: items },+ });+ },+});++function toBatchItem({ item, index }: { item: unknown; index: number }): Record<string, unknown> {+ const entry: Record<string, unknown> = Object(item);+ const id = Number(entry['id']);+ if (!Number.isInteger(id) || id <= 0) {+ throw new Error(`Entry ${index + 1} has no valid product id.`);+ }+ const stock = entry['stock_quantity'];+ const hasStock = stock !== undefined && stock !== null && stock !== '';+ const fields = wooValues.pruneUndefined({+ regular_price: readText(entry['regular_price']),+ sale_price: readText(entry['sale_price']),+ manage_stock: hasStock ? true : undefined,+ stock_quantity: hasStock ? Number(stock) : undefined,+ status: readText(entry['status']),+ });+ if (Object.keys(fields).length === 0) {+ throw new Error(`Entry ${index + 1} (product ${id}) has no field to change.`);+ }+ return { id, ...fields };+}++function readText(value: unknown): string | undefined {+ if (value === undefined || value === null) {+ return undefined;+ }+ return wooValues.nonEmpty(String(value));+}diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/create-coupon.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-coupon.tsnew file mode 100644index 00000000000..c8b9fce0129--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-coupon.ts@@ -0,0 +1,132 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { createCouponOutputSchema } from '../../output-schemas';++export const wooAiCreateCoupon = createAction({+ name: 'create_coupon',+ classification: 'WRITE',+ displayName: 'Create Coupon',+ description: 'Create a discount coupon.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a discount coupon with a code, discount type and amount; optional limits and restrictions are only applied when given. Coupon codes must be unique, and a code that already exists is rejected, so check list_coupons with the code first. Each call creates a new coupon.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: createCouponOutputSchema,+ props: {+ code: Property.ShortText({+ displayName: 'Code',+ description: 'Coupon code customers enter at checkout. Must be unique.',+ required: true,+ }),+ discount_type: Property.StaticDropdown({+ displayName: 'Discount Type',+ description: 'Percentage off the cart, a fixed amount off the cart, or a fixed amount off each product.',+ required: true,+ options: {+ options: [+ { label: 'Percentage discount', value: 'percent' },+ { label: 'Fixed cart discount', value: 'fixed_cart' },+ { label: 'Fixed product discount', value: 'fixed_product' },+ ],+ },+ }),+ amount: Property.ShortText({+ displayName: 'Amount',+ description: 'Discount amount as a decimal string: a percentage for percentage coupons, otherwise money, e.g. 10.',+ required: true,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'Internal description of the coupon.',+ required: false,+ }),+ date_expires: Property.DateTime({+ displayName: 'Expiry Date',+ description: 'The coupon stops working after this date.',+ required: false,+ }),+ minimum_amount: Property.ShortText({+ displayName: 'Minimum Spend',+ description: 'Minimum cart subtotal needed to use the coupon, e.g. 50.00.',+ required: false,+ }),+ maximum_amount: Property.ShortText({+ displayName: 'Maximum Spend',+ description: 'Maximum cart subtotal allowed when using the coupon.',+ required: false,+ }),+ individual_use: wooProps.triStateProp({+ displayName: 'Individual Use Only',+ description: 'Yes stops this coupon from being combined with other coupons. Leave empty for the store default (No).',+ }),+ exclude_sale_items: wooProps.triStateProp({+ displayName: 'Exclude Sale Items',+ description: 'Yes stops the coupon from applying to items already on sale. Leave empty for the store default (No).',+ }),+ free_shipping: wooProps.triStateProp({+ displayName: 'Free Shipping',+ description: 'Yes lets the coupon unlock free shipping, if a free-shipping method is set up. Leave empty for the store default (No).',+ }),+ usage_limit: Property.Number({+ displayName: 'Usage Limit',+ description: 'How many times the coupon can be used in total.',+ required: false,+ }),+ usage_limit_per_user: Property.Number({+ displayName: 'Usage Limit Per Customer',+ description: 'How many times each customer can use the coupon.',+ required: false,+ }),+ product_ids: Property.Array({+ displayName: 'Product IDs',+ description: 'Ids of the only products the coupon applies to.',+ required: false,+ }),+ excluded_product_ids: Property.Array({+ displayName: 'Excluded Product IDs',+ description: 'Ids of products the coupon never applies to.',+ required: false,+ }),+ email_restrictions: Property.Array({+ displayName: 'Allowed Emails',+ description: 'Only customers with these billing emails can use the coupon.',+ required: false,+ }),+ },+ async run(context) {+ const props = context.propsValue;+ const amount = props.amount.trim();+ if (amount.length === 0 || !Number.isFinite(Number(amount)) || Number(amount) < 0) {+ throw new Error(`Amount must be a non-negative decimal number such as 10; got "${props.amount}".`);+ }+ const body = wooValues.pruneUndefined({+ code: props.code.trim(),+ discount_type: props.discount_type,+ amount,+ description: wooValues.nonEmpty(props.description),+ date_expires: wooValues.nonEmpty(props.date_expires),+ minimum_amount: wooValues.nonEmpty(props.minimum_amount),+ maximum_amount: wooValues.nonEmpty(props.maximum_amount),+ individual_use: wooValues.resolveTriState(props.individual_use),+ exclude_sale_items: wooValues.resolveTriState(props.exclude_sale_items),+ free_shipping: wooValues.resolveTriState(props.free_shipping),+ usage_limit: props.usage_limit ?? undefined,+ usage_limit_per_user: props.usage_limit_per_user ?? undefined,+ product_ids: wooValues.toIdList(props.product_ids),+ excluded_product_ids: wooValues.toIdList(props.excluded_product_ids),+ email_restrictions: wooValues.toStringList(props.email_restrictions),+ });+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.POST,+ path: '/coupons',+ body,+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/create-customer.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-customer.tsnew file mode 100644index 00000000000..db093d0a038--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-customer.ts@@ -0,0 +1,110 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooValues } from '../../common/props';+import { createCustomerOutputSchema } from '../../output-schemas';++export const wooAiCreateCustomer = createAction({+ name: 'create_customer',+ classification: 'WRITE',+ displayName: 'Create Customer',+ description: 'Create a customer account. Only the email is required.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a customer account (a WordPress user with the customer role); only the email is required. Check list_customers by email first, because an email that is already registered is rejected. Username and password are generated when the store settings allow it, otherwise a password must be given; the store may email the new customer their account details.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: createCustomerOutputSchema,+ props: {+ email: Property.ShortText({+ displayName: 'Email',+ description: 'Email address of the customer. Must not already be registered.',+ required: true,+ }),+ first_name: Property.ShortText({ displayName: 'First Name', required: false }),+ last_name: Property.ShortText({ displayName: 'Last Name', required: false }),+ username: Property.ShortText({+ displayName: 'Username',+ description: 'Login name. Generated from the email when empty and the store allows it.',+ required: false,+ }),+ password: Property.ShortText({+ displayName: 'Password',+ description: 'Account password. Generated when empty and the store allows it.',+ required: false,+ }),+ billing_company: Property.ShortText({ displayName: 'Billing Company', required: false }),+ billing_address_1: Property.ShortText({ displayName: 'Billing Address Line 1', required: false }),+ billing_address_2: Property.ShortText({ displayName: 'Billing Address Line 2', required: false }),+ billing_city: Property.ShortText({ displayName: 'Billing City', required: false }),+ billing_state: Property.ShortText({+ displayName: 'Billing State',+ description: 'State or county code, e.g. CA.',+ required: false,+ }),+ billing_postcode: Property.ShortText({ displayName: 'Billing Postcode', required: false }),+ billing_country: Property.ShortText({+ displayName: 'Billing Country',+ description: 'Two-letter ISO country code, e.g. US.',+ required: false,+ }),+ billing_phone: Property.ShortText({ displayName: 'Billing Phone', required: false }),+ shipping_company: Property.ShortText({ displayName: 'Shipping Company', required: false }),+ shipping_address_1: Property.ShortText({ displayName: 'Shipping Address Line 1', required: false }),+ shipping_address_2: Property.ShortText({ displayName: 'Shipping Address Line 2', required: false }),+ shipping_city: Property.ShortText({ displayName: 'Shipping City', required: false }),+ shipping_state: Property.ShortText({+ displayName: 'Shipping State',+ description: 'State or county code, e.g. CA.',+ required: false,+ }),+ shipping_postcode: Property.ShortText({ displayName: 'Shipping Postcode', required: false }),+ shipping_country: Property.ShortText({+ displayName: 'Shipping Country',+ description: 'Two-letter ISO country code, e.g. US.',+ required: false,+ }),+ },+ async run(context) {+ const props = context.propsValue;+ const firstName = wooValues.nonEmpty(props.first_name);+ const lastName = wooValues.nonEmpty(props.last_name);+ const billing = wooValues.pruneUndefined({+ company: wooValues.nonEmpty(props.billing_company),+ address_1: wooValues.nonEmpty(props.billing_address_1),+ address_2: wooValues.nonEmpty(props.billing_address_2),+ city: wooValues.nonEmpty(props.billing_city),+ state: wooValues.nonEmpty(props.billing_state),+ postcode: wooValues.nonEmpty(props.billing_postcode),+ country: wooValues.nonEmpty(props.billing_country),+ phone: wooValues.nonEmpty(props.billing_phone),+ });+ const shipping = wooValues.pruneUndefined({+ company: wooValues.nonEmpty(props.shipping_company),+ address_1: wooValues.nonEmpty(props.shipping_address_1),+ address_2: wooValues.nonEmpty(props.shipping_address_2),+ city: wooValues.nonEmpty(props.shipping_city),+ state: wooValues.nonEmpty(props.shipping_state),+ postcode: wooValues.nonEmpty(props.shipping_postcode),+ country: wooValues.nonEmpty(props.shipping_country),+ });+ const body = wooValues.pruneUndefined({+ email: props.email.trim(),+ first_name: firstName,+ last_name: lastName,+ username: wooValues.nonEmpty(props.username),+ password: wooValues.nonEmpty(props.password),+ billing: Object.keys(billing).length > 0 ? billing : undefined,+ shipping: Object.keys(shipping).length > 0 ? shipping : undefined,+ });+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.POST,+ path: '/customers',+ body,+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/create-order-refund.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-order-refund.tsnew file mode 100644index 00000000000..06c1a0068ec--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-order-refund.ts@@ -0,0 +1,62 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooValues } from '../../common/props';+import { orderRefundOutputSchema } from '../../output-schemas';++export const wooAiCreateOrderRefund = createAction({+ name: 'create_order_refund',+ classification: 'DESTRUCTIVE',+ displayName: 'Create Order Refund',+ description: 'Refund an amount on an order. By default the refund is only recorded in WooCommerce.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Records an irreversible refund of an amount on one order and emails the customer about it; by default no money moves, but the order total drops and a full refund marks the order refunded. With Refund Via Gateway on, real money is sent back through the payment gateway, which fails on gateways without refund support (bank transfer, cheque, cash on delivery). Check list_order_refunds first, because each call adds another refund.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: orderRefundOutputSchema,+ props: {+ order_id: Property.Number({+ displayName: 'Order ID',+ description: 'Id of the order to refund.',+ required: true,+ }),+ amount: Property.ShortText({+ displayName: 'Amount',+ description: 'Amount to refund as a decimal string, e.g. 10.00. Cannot exceed what is left to refund on the order.',+ required: true,+ }),+ reason: Property.ShortText({+ displayName: 'Reason',+ description: 'Reason for the refund, stored with the refund.',+ required: false,+ }),+ refund_via_gateway: Property.Checkbox({+ displayName: 'Refund Via Gateway',+ description: 'When on, the money is actually sent back to the customer through the payment gateway. When off (the default) the refund is only recorded in WooCommerce.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const { order_id, amount, reason, refund_via_gateway } = context.propsValue;+ const trimmedAmount = amount.trim();+ const numericAmount = Number(trimmedAmount);+ if (trimmedAmount.length === 0 || !Number.isFinite(numericAmount) || numericAmount <= 0) {+ throw new Error(`Amount must be a positive decimal number such as 10.00; got "${amount}".`);+ }+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.POST,+ path: `/orders/${wooClient.encodeId(order_id)}/refunds`,+ body: wooValues.pruneUndefined({+ amount: trimmedAmount,+ reason: wooValues.nonEmpty(reason),+ api_refund: refund_via_gateway === true,+ }),+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/create-order.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-order.tsnew file mode 100644index 00000000000..41136c4204f--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-order.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { createOrderOutputSchema } from '../../output-schemas';+import { wooCreateOrder } from '../create-order';++export const wooAiCreateOrder = createAction({+ name: 'create_order',+ classification: 'WRITE',+ displayName: 'Create Order',+ description: 'Create an order with one or more line items.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a new order from product ids and quantities, optionally for a customer, with a status, and with a payment gateway; get product ids from list_products (a variation id can be used as the product id), customer ids from list_customers, and payment gateways from list_payment_gateways, passing the gateway id as Payment Method ID and its title as Payment Method Title. Status processing or completed reduces stock and emails the customer, while pending (the default) does neither. Each call creates a separate order.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: createOrderOutputSchema,+ props: wooCreateOrder.props,+ run: wooCreateOrder.run,+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/create-product-category.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-product-category.tsnew file mode 100644index 00000000000..c2f5269bf00--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-product-category.ts@@ -0,0 +1,57 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooValues } from '../../common/props';+import { productCategoryOutputSchema } from '../../output-schemas';++export const wooAiCreateProductCategory = createAction({+ name: 'create_product_category',+ classification: 'WRITE',+ displayName: 'Create Product Category',+ description: 'Create a product category.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a new product category, optionally under a parent category. Look it up with list_product_categories first: a category with the same name under the same parent is rejected, and the error message then gives the existing category id to use instead.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: productCategoryOutputSchema,+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Category name.',+ required: true,+ }),+ parent_id: Property.Number({+ displayName: 'Parent Category ID',+ description: 'Id of the parent category. Leave empty for a top-level category.',+ required: false,+ }),+ slug: Property.ShortText({+ displayName: 'Slug',+ description: 'URL-friendly name. Generated from the name when empty.',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'Category description. HTML is allowed.',+ required: false,+ }),+ },+ async run(context) {+ const props = context.propsValue;+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.POST,+ path: '/products/categories',+ body: wooValues.pruneUndefined({+ name: props.name,+ parent: props.parent_id ?? undefined,+ slug: wooValues.nonEmpty(props.slug),+ description: wooValues.nonEmpty(props.description),+ }),+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/create-product-tag.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-product-tag.tsnew file mode 100644index 00000000000..c90abc37eeb--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-product-tag.ts@@ -0,0 +1,51 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooValues } from '../../common/props';+import { productTagOutputSchema } from '../../output-schemas';++export const wooAiCreateProductTag = createAction({+ name: 'create_product_tag',+ classification: 'WRITE',+ displayName: 'Create Product Tag',+ description: 'Create a product tag.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a new product tag. Look it up with list_product_tags first: a tag with the same name is rejected, and the error message then gives the existing tag id to use instead.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: productTagOutputSchema,+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Tag name.',+ required: true,+ }),+ slug: Property.ShortText({+ displayName: 'Slug',+ description: 'URL-friendly name. Generated from the name when empty.',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'Tag description.',+ required: false,+ }),+ },+ async run(context) {+ const props = context.propsValue;+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.POST,+ path: '/products/tags',+ body: wooValues.pruneUndefined({+ name: props.name,+ slug: wooValues.nonEmpty(props.slug),+ description: wooValues.nonEmpty(props.description),+ }),+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/create-product.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-product.tsnew file mode 100644index 00000000000..95b32df72ce--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/create-product.ts@@ -0,0 +1,117 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { createProductOutputSchema } from '../../output-schemas';++export const wooAiCreateProduct = createAction({+ name: 'create_product',+ classification: 'WRITE',+ displayName: 'Create Product',+ description: 'Create a product. Only the name is required.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a new product in the store catalog; only the name is required and it is published as a simple product unless told otherwise. Check list_products by SKU or name first, because each call creates a separate product. A variable product is created without variations.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: createProductOutputSchema,+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Product name.',+ required: true,+ }),+ type: Property.StaticDropdown({+ displayName: 'Product Type',+ description: 'Defaults to simple.',+ required: false,+ options: { options: wooProps.productTypeOptions },+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Defaults to published, which makes the product visible in the shop.',+ required: false,+ options: { options: wooProps.productStatusOptions },+ }),+ regular_price: Property.ShortText({+ displayName: 'Regular Price',+ description: 'Price as a decimal string, e.g. 19.99.',+ required: false,+ }),+ sale_price: Property.ShortText({+ displayName: 'Sale Price',+ description: 'Discounted price as a decimal string. Must be lower than the regular price.',+ required: false,+ }),+ sku: Property.ShortText({+ displayName: 'SKU',+ description: 'Stock keeping unit. Must be unique in the store.',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'Full product description. HTML is allowed.',+ required: false,+ }),+ short_description: Property.LongText({+ displayName: 'Short Description',+ description: 'Short summary shown near the price. HTML is allowed.',+ required: false,+ }),+ category_ids: Property.Array({+ displayName: 'Category IDs',+ description: 'Ids of the categories to put the product in. Find them with list_product_categories.',+ required: false,+ }),+ tag_ids: Property.Array({+ displayName: 'Tag IDs',+ description: 'Ids of the tags to attach. Find them with list_product_tags.',+ required: false,+ }),+ image_urls: Property.Array({+ displayName: 'Image URLs',+ description: 'Public image URLs. The first one becomes the main image. The store downloads each one, so an unreachable URL fails the call.',+ required: false,+ }),+ stock_quantity: Property.Number({+ displayName: 'Stock Quantity',+ description: 'Units in stock. Setting it turns on stock management for the product.',+ required: false,+ }),+ stock_status: wooProps.stockStatusProp({+ description: 'Stock status. Ignored when a stock quantity is set, because the quantity decides it.',+ }),+ },+ async run(context) {+ const props = context.propsValue;+ const categoryIds = wooValues.toIdList(props.category_ids);+ const tagIds = wooValues.toIdList(props.tag_ids);+ const imageUrls = wooValues.toStringList(props.image_urls);+ const hasStock = props.stock_quantity !== undefined && props.stock_quantity !== null;+ const body = wooValues.pruneUndefined({+ name: props.name,+ type: props.type ?? 'simple',+ status: props.status ?? 'publish',+ regular_price: wooValues.nonEmpty(props.regular_price),+ sale_price: wooValues.nonEmpty(props.sale_price),+ sku: wooValues.nonEmpty(props.sku),+ description: wooValues.nonEmpty(props.description),+ short_description: wooValues.nonEmpty(props.short_description),+ categories: categoryIds?.map((id) => ({ id })),+ tags: tagIds?.map((id) => ({ id })),+ images: imageUrls?.map((src) => ({ src })),+ manage_stock: hasStock ? true : undefined,+ stock_quantity: hasStock ? props.stock_quantity : undefined,+ stock_status: hasStock ? undefined : props.stock_status,+ });+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.POST,+ path: '/products',+ body,+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-coupon.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-coupon.tsnew file mode 100644index 00000000000..1a5f3129a0c--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-coupon.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps } from '../../common/props';+import { deleteCouponOutputSchema } from '../../output-schemas';++export const wooAiDeleteCoupon = createAction({+ name: 'delete_coupon',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Coupon',+ description: 'Move a coupon to the trash, or delete it permanently.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes one coupon by id (find it with list_coupons by code) so it can no longer be used. By default it goes to the trash, which a person can restore from the WordPress admin; with permanent it is deleted for good. Trashing an already-trashed coupon fails, so a retry is not safe.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: deleteCouponOutputSchema,+ props: {+ coupon_id: Property.Number({+ displayName: 'Coupon ID',+ description: 'Id of the coupon to delete.',+ required: true,+ }),+ permanent: wooProps.permanentProp({ resource: 'coupon' }),+ },+ async run(context) {+ const { coupon_id, permanent } = context.propsValue;+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.DELETE,+ path: `/coupons/${wooClient.encodeId(coupon_id)}`,+ queryParams: { force: permanent === true },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-customer.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-customer.tsnew file mode 100644index 00000000000..8b7c1c3dddf--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-customer.ts@@ -0,0 +1,71 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { deleteCustomerOutputSchema } from '../../output-schemas';++export const wooAiDeleteCustomer = createAction({+ name: 'delete_customer',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Customer',+ description: 'Permanently delete a customer account.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes one customer account (its WordPress user); customers have no trash, so it cannot be restored. Only accounts with the customer or subscriber role can be deleted here, so staff and administrators are refused. Their orders stay in the store; optionally reassign their posts to another user id.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: deleteCustomerOutputSchema,+ props: {+ customer_id: Property.Number({+ displayName: 'Customer ID',+ description: 'Id of the customer to delete. Find it with list_customers.',+ required: true,+ }),+ reassign_to_user_id: Property.Number({+ displayName: 'Reassign To User ID',+ description: 'Optional id of another user who takes over the posts owned by the deleted customer. Must differ from the customer id.',+ required: false,+ }),+ },+ async run(context) {+ const { customer_id, reassign_to_user_id } = context.propsValue;+ const auth = context.auth.props;+ const hasReassign = reassign_to_user_id !== undefined && reassign_to_user_id !== null;+ if (hasReassign && String(reassign_to_user_id) === String(customer_id)) {+ throw new Error('Reassign To User ID must be a different user than the customer being deleted.');+ }+ const customer = await wooClient.request<unknown>({+ auth,+ method: HttpMethod.GET,+ path: `/customers/${wooClient.encodeId(customer_id)}`,+ });+ const role = readRole(customer);+ if (role === undefined || !deletableRoles.includes(role)) {+ throw new Error(+ `Refusing to delete user ${customer_id}: their role is "${role ?? 'unknown'}". Only accounts with the customer or subscriber role can be deleted with this action.`+ );+ }+ return wooClient.request<unknown>({+ auth,+ method: HttpMethod.DELETE,+ path: `/customers/${wooClient.encodeId(customer_id)}`,+ queryParams: {+ force: true,+ reassign: hasReassign ? reassign_to_user_id : undefined,+ },+ });+ },+});++function readRole(customer: unknown): string | undefined {+ if (typeof customer !== 'object' || customer === null) {+ return undefined;+ }+ const record: Record<string, unknown> = Object(customer);+ const role = record['role'];+ return typeof role === 'string' ? role : undefined;+}++const deletableRoles = ['customer', 'subscriber'];diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-order-note.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-order-note.tsnew file mode 100644index 00000000000..d3f39cb7a15--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-order-note.ts@@ -0,0 +1,41 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { deleteOrderNoteOutputSchema } from '../../output-schemas';++export const wooAiDeleteOrderNote = createAction({+ name: 'delete_order_note',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Order Note',+ description: 'Permanently delete a note from an order.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes one note from an order (find note ids with list_order_notes); order notes have no trash, so it cannot be restored. Deleting a note sent to the customer does not unsend the email. A second call for the same note fails.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: deleteOrderNoteOutputSchema,+ props: {+ order_id: Property.Number({+ displayName: 'Order ID',+ description: 'Id of the order the note belongs to.',+ required: true,+ }),+ note_id: Property.Number({+ displayName: 'Note ID',+ description: 'Id of the note to delete.',+ required: true,+ }),+ },+ async run(context) {+ const { order_id, note_id } = context.propsValue;+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.DELETE,+ path: `/orders/${wooClient.encodeId(order_id)}/notes/${wooClient.encodeId(note_id)}`,+ queryParams: { force: true },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-order.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-order.tsnew file mode 100644index 00000000000..cfa104d6169--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-order.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps } from '../../common/props';+import { deleteOrderOutputSchema } from '../../output-schemas';++export const wooAiDeleteOrder = createAction({+ name: 'delete_order',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Order',+ description: 'Move an order to the trash, or delete it permanently.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes one order by id; to stop an order without removing it, set its status to cancelled with update_order instead. By default it goes to the trash, which a person can restore from the WordPress admin; with permanent it is deleted for good. Trashing an already-trashed order fails, so a retry is not safe.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: deleteOrderOutputSchema,+ props: {+ order_id: Property.Number({+ displayName: 'Order ID',+ description: 'Id of the order to delete. Find it with list_orders.',+ required: true,+ }),+ permanent: wooProps.permanentProp({ resource: 'order' }),+ },+ async run(context) {+ const { order_id, permanent } = context.propsValue;+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.DELETE,+ path: `/orders/${wooClient.encodeId(order_id)}`,+ queryParams: { force: permanent === true },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-product.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-product.tsnew file mode 100644index 00000000000..b93933b2809--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/delete-product.ts@@ -0,0 +1,38 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps } from '../../common/props';+import { deleteProductOutputSchema } from '../../output-schemas';++export const wooAiDeleteProduct = createAction({+ name: 'delete_product',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Product',+ description: 'Move a product to the trash, or delete it permanently.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Removes one product by id. By default it goes to the trash, which a person can restore from the WordPress admin; with permanent it is deleted for good, together with all variations of a variable product. Trashing an already-trashed product fails, so a retry is not safe.',+ idempotent: false,+ },+ auth: wooAuth,+ outputSchema: deleteProductOutputSchema,+ props: {+ product_id: Property.Number({+ displayName: 'Product ID',+ description: 'Id of the product to delete. Find it with list_products.',+ required: true,+ }),+ permanent: wooProps.permanentProp({ resource: 'product' }),+ },+ async run(context) {+ const { product_id, permanent } = context.propsValue;+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.DELETE,+ path: `/products/${wooClient.encodeId(product_id)}`,+ queryParams: { force: permanent === true },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/get-coupon.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-coupon.tsnew file mode 100644index 00000000000..19db331d093--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-coupon.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { findCouponOutputSchema } from '../../output-schemas';+import { wooFindCoupon } from '../find-coupon';++export const wooAiGetCoupon = createAction({+ name: 'get_coupon',+ classification: 'READ',+ displayName: 'Get Coupon',+ description: 'Get a coupon by its ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one coupon by its numeric id with its code, discount, limits, restrictions and usage count. To find a coupon by its code use list_coupons. Read-only and safe to retry.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: findCouponOutputSchema,+ props: wooFindCoupon.props,+ run: wooFindCoupon.run,+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/get-customer.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-customer.tsnew file mode 100644index 00000000000..81d58008366--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-customer.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { getCustomerOutputSchema } from '../../output-schemas';+import { wooGetCustomer } from '../get-customer';++export const wooAiGetCustomer = createAction({+ name: 'get_customer',+ classification: 'READ',+ displayName: 'Get Customer',+ description: 'Get a customer by their ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one customer by numeric id, with role, billing and shipping addresses and whether they have paid for an order. To find a customer by email or name use list_customers first. Read-only and safe to retry.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: getCustomerOutputSchema,+ props: wooGetCustomer.props,+ run: wooGetCustomer.run,+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/get-order-totals-report.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-order-totals-report.tsnew file mode 100644index 00000000000..4e6c95e2e3e--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-order-totals-report.ts@@ -0,0 +1,28 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { orderTotalsReportOutputSchema } from '../../output-schemas';++export const wooAiGetOrderTotalsReport = createAction({+ name: 'get_order_totals_report',+ classification: 'READ',+ displayName: 'Get Order Totals Report',+ description: 'Get the number of orders in each status.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns how many orders the store currently holds in each status (pending payment, processing, on hold, completed, cancelled, refunded, failed and so on), across all time. Use it for a quick overview of the order pipeline; to see the orders themselves use list_orders with a status.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: orderTotalsReportOutputSchema,+ props: {},+ async run(context) {+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/reports/orders/totals',+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/get-order.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-order.tsnew file mode 100644index 00000000000..91a698978f8--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-order.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { getOrderOutputSchema } from '../../output-schemas';+import { wooGetOrder } from '../get-order';++export const wooAiGetOrder = createAction({+ name: 'get_order',+ classification: 'READ',+ displayName: 'Get Order',+ description: 'Get an order by its ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one order by its numeric id with status, totals, line items, addresses, payment method and refunds. To find orders by status, customer or date use list_orders. Read-only and safe to retry.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: getOrderOutputSchema,+ props: wooGetOrder.props,+ run: wooGetOrder.run,+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/get-product-variation.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-product-variation.tsnew file mode 100644index 00000000000..c42dd5479a3--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-product-variation.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { productVariationOutputSchema } from '../../output-schemas';++export const wooAiGetProductVariation = createAction({+ name: 'get_product_variation',+ classification: 'READ',+ displayName: 'Get Product Variation',+ description: 'Get one variation of a variable product.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one variation of a variable product by product id and variation id, including its attributes, price and stock. Variation ids come from list_product_variations or from the variations list of get_product. Read-only and safe to retry.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: productVariationOutputSchema,+ props: {+ product_id: Property.Number({+ displayName: 'Product ID',+ description: 'Id of the parent variable product.',+ required: true,+ }),+ variation_id: Property.Number({+ displayName: 'Variation ID',+ description: 'Id of the variation.',+ required: true,+ }),+ },+ async run(context) {+ const { product_id, variation_id } = context.propsValue;+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: `/products/${wooClient.encodeId(product_id)}/variations/${wooClient.encodeId(variation_id)}`,+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/get-product.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-product.tsnew file mode 100644index 00000000000..a94ecbb204f--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-product.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { findProductOutputSchema } from '../../output-schemas';+import { wooFindProduct } from '../find-product';++export const wooAiGetProduct = createAction({+ name: 'get_product',+ classification: 'READ',+ displayName: 'Get Product',+ description: 'Get a product by its ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one product by its numeric id with prices, stock, categories, tags, images and, for a variable product, its variation ids. To find a product by name or SKU use list_products first; for a single variation use get_product_variation. Read-only and safe to retry.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: findProductOutputSchema,+ props: wooFindProduct.props,+ run: wooFindProduct.run,+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/get-sales-report.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-sales-report.tsnew file mode 100644index 00000000000..e94991651dd--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-sales-report.ts@@ -0,0 +1,31 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { salesReportOutputSchema } from '../../output-schemas';++export const wooAiGetSalesReport = createAction({+ name: 'get_sales_report',+ classification: 'READ',+ displayName: 'Get Sales Report',+ description: 'Get sales totals for a period or date range.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns store sales totals (gross and net sales, orders, items, tax, shipping, refunds, discounts) for a preset period or a custom date range, plus a per-day or per-month breakdown. Give either a period or both dates, not both; with neither, the current week is used. For best-selling products use get_top_sellers_report; for order counts by status use get_order_totals_report.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: salesReportOutputSchema,+ props: wooProps.reportRangeProps(),+ async run(context) {+ const { period, date_min, date_max } = context.propsValue;+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/reports/sales',+ queryParams: wooValues.resolveReportRange({ period, dateMin: date_min, dateMax: date_max }),+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/get-top-sellers-report.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-top-sellers-report.tsnew file mode 100644index 00000000000..6027b76af3f--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/get-top-sellers-report.ts@@ -0,0 +1,31 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { topSellersReportOutputSchema } from '../../output-schemas';++export const wooAiGetTopSellersReport = createAction({+ name: 'get_top_sellers_report',+ classification: 'READ',+ displayName: 'Get Top Sellers Report',+ description: 'Get the best-selling products for a period or date range.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the best-selling products with the quantity sold for a preset period or a custom date range, highest first. Give either a period or both dates, not both; with neither, the current week is used. For money totals use get_sales_report.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: topSellersReportOutputSchema,+ props: wooProps.reportRangeProps(),+ async run(context) {+ const { period, date_min, date_max } = context.propsValue;+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/reports/top_sellers',+ queryParams: wooValues.resolveReportRange({ period, dateMin: date_min, dateMax: date_max }),+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-coupons.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-coupons.tsnew file mode 100644index 00000000000..4d9ca2cf948--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-coupons.ts@@ -0,0 +1,61 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { listCouponsOutputSchema } from '../../output-schemas';++export const wooAiListCoupons = createAction({+ name: 'list_coupons',+ classification: 'SEARCH',+ displayName: 'List Coupons',+ description: 'List coupons, or find one by its exact code.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists discount coupons with their codes, amounts, limits and usage counts. Pass code to look up one coupon by its exact code (the way to get a coupon id for get_coupon, update_coupon or delete_coupon, and to check that a code is free before create_coupon). Paged: if a page returns exactly per_page items, request the next page.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listCouponsOutputSchema,+ props: {+ code: Property.ShortText({+ displayName: 'Code',+ description: 'Exact coupon code to find.',+ required: false,+ }),+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Text to match against coupon codes and descriptions.',+ required: false,+ }),+ after: Property.DateTime({+ displayName: 'Created After',+ description: 'Only return coupons created after this date and time (ISO 8601).',+ required: false,+ }),+ before: Property.DateTime({+ displayName: 'Created Before',+ description: 'Only return coupons created before this date and time (ISO 8601).',+ required: false,+ }),+ page: wooProps.pageProp(),+ per_page: wooProps.perPageProp(),+ },+ async run(context) {+ const props = context.propsValue;+ const paging = await wooValues.paging({ page: props.page, perPage: props.per_page });+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/coupons',+ queryParams: {+ code: wooValues.nonEmpty(props.code),+ search: wooValues.nonEmpty(props.search),+ after: wooValues.nonEmpty(props.after),+ before: wooValues.nonEmpty(props.before),+ ...paging,+ },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-customers.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-customers.tsnew file mode 100644index 00000000000..2977e91f039--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-customers.ts@@ -0,0 +1,90 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { listCustomersOutputSchema } from '../../output-schemas';++export const wooAiListCustomers = createAction({+ name: 'list_customers',+ classification: 'SEARCH',+ displayName: 'List Customers',+ description: 'List customers, filtered by email, text or role.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Searches store customers and returns them with their ids, emails and addresses. Use it to find a customer id by exact email or by name before get_customer, update_customer, create_order or list_orders; role defaults to all, so shop staff and administrators are included. Paged: if a page returns exactly per_page items, request the next page.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listCustomersOutputSchema,+ props: {+ email: Property.ShortText({+ displayName: 'Email',+ description: 'Exact email address to match.',+ required: false,+ }),+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Text to match against names, usernames and emails.',+ required: false,+ }),+ role: Property.StaticDropdown({+ displayName: 'Role',+ description: 'WordPress role to return. Defaults to all roles.',+ required: false,+ defaultValue: 'all',+ options: {+ options: [+ { label: 'All roles', value: 'all' },+ { label: 'Customer', value: 'customer' },+ { label: 'Subscriber', value: 'subscriber' },+ { label: 'Shop manager', value: 'shop_manager' },+ { label: 'Administrator', value: 'administrator' },+ ],+ },+ }),+ orderby: Property.StaticDropdown({+ displayName: 'Sort By',+ description: 'Field to sort by. Defaults to name.',+ required: false,+ options: {+ options: [+ { label: 'Name', value: 'name' },+ { label: 'ID', value: 'id' },+ { label: 'Registration date', value: 'registered_date' },+ ],+ },+ }),+ order: Property.StaticDropdown({+ displayName: 'Sort Direction',+ description: 'Ascending or descending. Defaults to ascending.',+ required: false,+ options: {+ options: [+ { label: 'Ascending', value: 'asc' },+ { label: 'Descending', value: 'desc' },+ ],+ },+ }),+ page: wooProps.pageProp(),+ per_page: wooProps.perPageProp(),+ },+ async run(context) {+ const props = context.propsValue;+ const paging = await wooValues.paging({ page: props.page, perPage: props.per_page });+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/customers',+ queryParams: {+ email: wooValues.nonEmpty(props.email),+ search: wooValues.nonEmpty(props.search),+ role: props.role ?? 'all',+ orderby: props.orderby,+ order: props.order,+ ...paging,+ },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-order-notes.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-order-notes.tsnew file mode 100644index 00000000000..c8f6b70dc6c--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-order-notes.ts@@ -0,0 +1,48 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { listOrderNotesOutputSchema } from '../../output-schemas';++export const wooAiListOrderNotes = createAction({+ name: 'list_order_notes',+ classification: 'SEARCH',+ displayName: 'List Order Notes',+ description: 'List the notes on an order.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists all notes on one order, both private staff notes and notes sent to the customer, including the ones WooCommerce writes itself for status changes and emails. Use it to read an order history or to find a note id for delete_order_note; add a note with add_order_note.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listOrderNotesOutputSchema,+ props: {+ order_id: Property.Number({+ displayName: 'Order ID',+ description: 'Id of the order.',+ required: true,+ }),+ type: Property.StaticDropdown({+ displayName: 'Note Type',+ description: 'Which notes to return. Defaults to all.',+ required: false,+ options: {+ options: [+ { label: 'All notes', value: 'any' },+ { label: 'Notes sent to the customer', value: 'customer' },+ { label: 'Private notes', value: 'internal' },+ ],+ },+ }),+ },+ async run(context) {+ const { order_id, type } = context.propsValue;+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: `/orders/${wooClient.encodeId(order_id)}/notes`,+ queryParams: { type: type ?? 'any' },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-order-refunds.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-order-refunds.tsnew file mode 100644index 00000000000..262fdfe5ce0--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-order-refunds.ts@@ -0,0 +1,40 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { listOrderRefundsOutputSchema } from '../../output-schemas';++export const wooAiListOrderRefunds = createAction({+ name: 'list_order_refunds',+ classification: 'SEARCH',+ displayName: 'List Order Refunds',+ description: 'List the refunds recorded on an order.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the refunds already recorded on one order, with amount, reason and whether money was sent back through the gateway. Check it before create_order_refund to avoid refunding twice. Paged: if a page returns exactly per_page items, request the next page.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listOrderRefundsOutputSchema,+ props: {+ order_id: Property.Number({+ displayName: 'Order ID',+ description: 'Id of the order.',+ required: true,+ }),+ page: wooProps.pageProp(),+ per_page: wooProps.perPageProp(),+ },+ async run(context) {+ const props = context.propsValue;+ const paging = await wooValues.paging({ page: props.page, perPage: props.per_page });+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: `/orders/${wooClient.encodeId(props.order_id)}/refunds`,+ queryParams: { ...paging },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-orders.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-orders.tsnew file mode 100644index 00000000000..2af609cf186--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-orders.ts@@ -0,0 +1,90 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { listOrdersOutputSchema } from '../../output-schemas';++export const wooAiListOrders = createAction({+ name: 'list_orders',+ classification: 'SEARCH',+ displayName: 'List Orders',+ description: 'List orders, filtered by status, customer, product, text or date range.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Searches orders and returns them with totals, line items and addresses. Use it to find orders by status, customer id, product id, free text (such as an email or name) or creation date range; use get_order when you already have the order id. Paged: if a page returns exactly per_page items, request the next page.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listOrdersOutputSchema,+ props: {+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Only return orders with this status. Leave empty for any status except trash.',+ required: false,+ options: { options: wooProps.orderStatusOptions },+ }),+ customer_id: Property.Number({+ displayName: 'Customer ID',+ description: 'Only return orders placed by this customer. Find the id with list_customers.',+ required: false,+ }),+ product_id: Property.Number({+ displayName: 'Product ID',+ description: 'Only return orders that contain this product.',+ required: false,+ }),+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Text to match against order fields such as the billing name or email.',+ required: false,+ }),+ after: Property.DateTime({+ displayName: 'Created After',+ description: 'Only return orders created after this date and time (ISO 8601).',+ required: false,+ }),+ before: Property.DateTime({+ displayName: 'Created Before',+ description: 'Only return orders created before this date and time (ISO 8601).',+ required: false,+ }),+ orderby: Property.StaticDropdown({+ displayName: 'Sort By',+ description: 'Field to sort by. Defaults to date.',+ required: false,+ options: {+ options: [+ { label: 'Date', value: 'date' },+ { label: 'ID', value: 'id' },+ { label: 'Title', value: 'title' },+ { label: 'Slug', value: 'slug' },+ ],+ },+ }),+ order: wooProps.sortOrderProp(),+ page: wooProps.pageProp(),+ per_page: wooProps.perPageProp(),+ },+ async run(context) {+ const props = context.propsValue;+ const paging = await wooValues.paging({ page: props.page, perPage: props.per_page });+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/orders',+ queryParams: {+ status: props.status,+ customer: props.customer_id,+ product: props.product_id,+ search: wooValues.nonEmpty(props.search),+ after: wooValues.nonEmpty(props.after),+ before: wooValues.nonEmpty(props.before),+ orderby: props.orderby,+ order: props.order,+ ...paging,+ },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-payment-gateways.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-payment-gateways.tsnew file mode 100644index 00000000000..6ba284f86d5--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-payment-gateways.ts@@ -0,0 +1,43 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { listPaymentGatewaysOutputSchema } from '../../output-schemas';++export const wooAiListPaymentGateways = createAction({+ name: 'list_payment_gateways',+ classification: 'SEARCH',+ displayName: 'List Payment Gateways',+ description: 'List the payment methods installed in the store and whether they are enabled.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the payment gateways installed in the store with their ids, titles, whether they are enabled, and what they support (for example refunds). Use it to pick a payment method for create_order, or to check whether a gateway supports refunds before create_order_refund with Refund Via Gateway. Gateway settings and credentials are never returned.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listPaymentGatewaysOutputSchema,+ props: {},+ async run(context) {+ const gateways = await wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/payment_gateways',+ });+ return gateways.map((gateway) => toPublicGateway(gateway));+ },+});++function toPublicGateway(gateway: unknown): Record<string, unknown> {+ const record: Record<string, unknown> = Object(gateway);+ return {+ id: record['id'],+ title: record['title'],+ description: record['description'],+ order: record['order'],+ enabled: record['enabled'],+ method_title: record['method_title'],+ method_description: record['method_description'],+ method_supports: record['method_supports'],+ };+}diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-categories.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-categories.tsnew file mode 100644index 00000000000..7925a5a0b41--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-categories.ts@@ -0,0 +1,62 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { listProductCategoriesOutputSchema } from '../../output-schemas';++export const wooAiListProductCategories = createAction({+ name: 'list_product_categories',+ classification: 'SEARCH',+ displayName: 'List Product Categories',+ description: 'List product categories, optionally filtered by name, slug or parent.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists product categories with their ids, slugs, parents and product counts. Use it to find a category id for list_products, create_product or update_product, and before create_product_category to avoid a duplicate. Paged: if a page returns exactly per_page items, request the next page.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listProductCategoriesOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Text to match against category names.',+ required: false,+ }),+ slug: Property.ShortText({+ displayName: 'Slug',+ description: 'Exact category slug.',+ required: false,+ }),+ parent_id: Property.Number({+ displayName: 'Parent Category ID',+ description: 'Only return direct children of this category. Use 0 for top-level categories.',+ required: false,+ }),+ hide_empty: Property.Checkbox({+ displayName: 'Hide Empty',+ description: 'When on, categories without products are left out.',+ required: false,+ defaultValue: false,+ }),+ page: wooProps.pageProp(),+ per_page: wooProps.perPageProp(),+ },+ async run(context) {+ const props = context.propsValue;+ const paging = await wooValues.paging({ page: props.page, perPage: props.per_page });+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/products/categories',+ queryParams: {+ search: wooValues.nonEmpty(props.search),+ slug: wooValues.nonEmpty(props.slug),+ parent: props.parent_id,+ hide_empty: props.hide_empty === true ? true : undefined,+ ...paging,+ },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-reviews.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-reviews.tsnew file mode 100644index 00000000000..51b35300d3f--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-reviews.ts@@ -0,0 +1,71 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { listProductReviewsOutputSchema } from '../../output-schemas';++export const wooAiListProductReviews = createAction({+ name: 'list_product_reviews',+ classification: 'SEARCH',+ displayName: 'List Product Reviews',+ description: 'List product reviews, including ones waiting for moderation.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists customer product reviews with their rating, text, reviewer and moderation status. Status defaults to all, so reviews on hold or marked as spam are included; use it to find a review id for update_product_review. Paged: if a page returns exactly per_page items, request the next page.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listProductReviewsOutputSchema,+ props: {+ product_id: Property.Number({+ displayName: 'Product ID',+ description: 'Only return reviews of this product.',+ required: false,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Moderation status to return. Defaults to all.',+ required: false,+ defaultValue: 'all',+ options: {+ options: [+ { label: 'All', value: 'all' },+ { label: 'Approved', value: 'approved' },+ { label: 'On hold (awaiting moderation)', value: 'hold' },+ { label: 'Spam', value: 'spam' },+ { label: 'Trash', value: 'trash' },+ ],+ },+ }),+ reviewer_email: Property.ShortText({+ displayName: 'Reviewer Email',+ description: 'Only return reviews written with this email address.',+ required: false,+ }),+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Text to match against the review content.',+ required: false,+ }),+ page: wooProps.pageProp(),+ per_page: wooProps.perPageProp(),+ },+ async run(context) {+ const props = context.propsValue;+ const paging = await wooValues.paging({ page: props.page, perPage: props.per_page });+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/products/reviews',+ queryParams: {+ product: props.product_id,+ status: props.status ?? 'all',+ reviewer_email: wooValues.nonEmpty(props.reviewer_email),+ search: wooValues.nonEmpty(props.search),+ ...paging,+ },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-tags.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-tags.tsnew file mode 100644index 00000000000..01ff34a408e--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-tags.ts@@ -0,0 +1,56 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { listProductTagsOutputSchema } from '../../output-schemas';++export const wooAiListProductTags = createAction({+ name: 'list_product_tags',+ classification: 'SEARCH',+ displayName: 'List Product Tags',+ description: 'List product tags, optionally filtered by name or slug.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists product tags with their ids, slugs and product counts. Use it to find a tag id for list_products, create_product or update_product, and before create_product_tag to avoid a duplicate. Paged: if a page returns exactly per_page items, request the next page.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listProductTagsOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Text to match against tag names.',+ required: false,+ }),+ slug: Property.ShortText({+ displayName: 'Slug',+ description: 'Exact tag slug.',+ required: false,+ }),+ hide_empty: Property.Checkbox({+ displayName: 'Hide Empty',+ description: 'When on, tags without products are left out.',+ required: false,+ defaultValue: false,+ }),+ page: wooProps.pageProp(),+ per_page: wooProps.perPageProp(),+ },+ async run(context) {+ const props = context.propsValue;+ const paging = await wooValues.paging({ page: props.page, perPage: props.per_page });+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/products/tags',+ queryParams: {+ search: wooValues.nonEmpty(props.search),+ slug: wooValues.nonEmpty(props.slug),+ hide_empty: props.hide_empty === true ? true : undefined,+ ...paging,+ },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-variations.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-variations.tsnew file mode 100644index 00000000000..b49771d63b6--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-product-variations.ts@@ -0,0 +1,52 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { listProductVariationsOutputSchema } from '../../output-schemas';++export const wooAiListProductVariations = createAction({+ name: 'list_product_variations',+ classification: 'SEARCH',+ displayName: 'List Product Variations',+ description: 'List the variations of a variable product.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists the variations (such as sizes or colours) of one variable product, with their ids, attributes, prices and stock. Use it to find a variation id for get_product_variation or update_product_variation; simple products have no variations. Paged: if a page returns exactly per_page items, request the next page.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listProductVariationsOutputSchema,+ props: {+ product_id: Property.Number({+ displayName: 'Product ID',+ description: 'Id of the variable product. Find it with list_products.',+ required: true,+ }),+ sku: Property.ShortText({+ displayName: 'SKU',+ description: 'Only return the variation with this SKU.',+ required: false,+ }),+ stock_status: wooProps.stockStatusProp({+ description: 'Only return variations with this stock status.',+ }),+ page: wooProps.pageProp(),+ per_page: wooProps.perPageProp(),+ },+ async run(context) {+ const props = context.propsValue;+ const paging = await wooValues.paging({ page: props.page, perPage: props.per_page });+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: `/products/${wooClient.encodeId(props.product_id)}/variations`,+ queryParams: {+ sku: wooValues.nonEmpty(props.sku),+ stock_status: props.stock_status,+ ...paging,+ },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/list-products.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-products.tsnew file mode 100644index 00000000000..1ddb2e84497--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/list-products.ts@@ -0,0 +1,116 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { listProductsOutputSchema } from '../../output-schemas';++export const wooAiListProducts = createAction({+ name: 'list_products',+ classification: 'SEARCH',+ displayName: 'List Products',+ description: 'List products, filtered by text, SKU, status, category, tag, stock or price.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Searches the store catalog and returns matching products, including their ids, prices and stock. Use it to find a product id by name or SKU before get_product, update_product or create_order; variations of a variable product are listed with list_product_variations. Paged: if a page returns exactly per_page items, request the next page.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: listProductsOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Text to match against product names and content.',+ required: false,+ }),+ sku: Property.ShortText({+ displayName: 'SKU',+ description: 'Exact SKU to match. Separate several SKUs with commas.',+ required: false,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Only return products with this status. Leave empty for any status.',+ required: false,+ options: { options: wooProps.productStatusOptions },+ }),+ type: Property.StaticDropdown({+ displayName: 'Product Type',+ description: 'Only return products of this type.',+ required: false,+ options: { options: wooProps.productTypeOptions },+ }),+ category_id: Property.Number({+ displayName: 'Category ID',+ description: 'Only return products in this category. Find ids with list_product_categories.',+ required: false,+ }),+ tag_id: Property.Number({+ displayName: 'Tag ID',+ description: 'Only return products with this tag. Find ids with list_product_tags.',+ required: false,+ }),+ stock_status: wooProps.stockStatusProp({+ description: 'Only return products with this stock status.',+ }),+ on_sale: wooProps.triStateProp({+ displayName: 'On Sale',+ description: 'Yes returns only products on sale, No only products not on sale. Leave empty for both.',+ }),+ min_price: Property.ShortText({+ displayName: 'Minimum Price',+ description: 'Only return products priced at or above this amount, e.g. 10.00.',+ required: false,+ }),+ max_price: Property.ShortText({+ displayName: 'Maximum Price',+ description: 'Only return products priced at or below this amount, e.g. 99.99.',+ required: false,+ }),+ orderby: Property.StaticDropdown({+ displayName: 'Sort By',+ description: 'Field to sort by. Defaults to date.',+ required: false,+ options: {+ options: [+ { label: 'Date', value: 'date' },+ { label: 'ID', value: 'id' },+ { label: 'Title', value: 'title' },+ { label: 'Slug', value: 'slug' },+ { label: 'Price', value: 'price' },+ { label: 'Popularity', value: 'popularity' },+ { label: 'Rating', value: 'rating' },+ ],+ },+ }),+ order: wooProps.sortOrderProp(),+ page: wooProps.pageProp(),+ per_page: wooProps.perPageProp(),+ },+ async run(context) {+ const props = context.propsValue;+ const paging = await wooValues.paging({ page: props.page, perPage: props.per_page });+ const onSale = wooValues.resolveTriState(props.on_sale);+ return wooClient.request<unknown[]>({+ auth: context.auth.props,+ method: HttpMethod.GET,+ path: '/products',+ queryParams: {+ search: wooValues.nonEmpty(props.search),+ sku: wooValues.nonEmpty(props.sku),+ status: props.status,+ type: props.type,+ category: props.category_id,+ tag: props.tag_id,+ stock_status: props.stock_status,+ on_sale: onSale,+ min_price: wooValues.nonEmpty(props.min_price),+ max_price: wooValues.nonEmpty(props.max_price),+ orderby: props.orderby,+ order: props.order,+ ...paging,+ },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/update-coupon.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-coupon.tsnew file mode 100644index 00000000000..3b568343c7d--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-coupon.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { updateCouponOutputSchema } from '../../output-schemas';+import { wooUpdateCoupon } from '../update-coupon';++export const wooAiUpdateCoupon = createAction({+ name: 'update_coupon',+ classification: 'WRITE',+ displayName: 'Update Coupon',+ description: 'Change the amount, type, expiry or limits of a coupon.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes the amount, discount type, description, expiry date, usage limit or minimum spend of one coupon by id; fields left empty are kept. Find the id with list_coupons by code.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: updateCouponOutputSchema,+ props: wooUpdateCoupon.props,+ run: wooUpdateCoupon.run,+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/update-customer.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-customer.tsnew file mode 100644index 00000000000..52bde320781--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-customer.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { updateCustomerOutputSchema } from '../../output-schemas';+import { wooUpdateCustomer } from '../update-customer';++export const wooAiUpdateCustomer = createAction({+ name: 'update_customer',+ classification: 'WRITE',+ displayName: 'Update Customer',+ description: 'Change the name, email or billing details of a customer.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes the email, first or last name, or billing phone, city, postcode and country of one customer by id; fields left empty are kept. Find the id with list_customers.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: updateCustomerOutputSchema,+ props: wooUpdateCustomer.props,+ run: wooUpdateCustomer.run,+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/update-order.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-order.tsnew file mode 100644index 00000000000..34e1d3ae56c--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-order.ts@@ -0,0 +1,21 @@+import { createAction } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { updateOrderOutputSchema } from '../../output-schemas';+import { wooUpdateOrder } from '../update-order';++export const wooAiUpdateOrder = createAction({+ name: 'update_order',+ classification: 'WRITE',+ displayName: 'Update Order',+ description: 'Change the status, customer note or transaction ID of an order.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes the status, customer-provided note field or transaction id of one order; fields left empty are kept. Status changes have side effects: processing and completed email the customer, and refunded records a refund for the remaining amount and emails the customer, but moves no money and does not restock (use create_order_refund for partial refunds). The customer note field sends nothing; to message the customer use add_order_note.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: updateOrderOutputSchema,+ props: wooUpdateOrder.props,+ run: wooUpdateOrder.run,+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/update-product-review.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-product-review.tsnew file mode 100644index 00000000000..713db11f7c7--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-product-review.ts@@ -0,0 +1,51 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { productReviewOutputSchema } from '../../output-schemas';++export const wooAiUpdateProductReview = createAction({+ name: 'update_product_review',+ classification: 'WRITE',+ displayName: 'Moderate Product Review',+ description: 'Approve, hold, mark as spam or trash a product review.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes the moderation status of one product review: approve it, put it on hold, mark or unmark it as spam, or move it to or from the trash. The review text and rating cannot be changed here. Find review ids with list_product_reviews.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: productReviewOutputSchema,+ props: {+ review_id: Property.Number({+ displayName: 'Review ID',+ description: 'Id of the review.',+ required: true,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'New moderation status.',+ required: true,+ options: {+ options: [+ { label: 'Approve', value: 'approved' },+ { label: 'Hold (unapprove)', value: 'hold' },+ { label: 'Mark as spam', value: 'spam' },+ { label: 'Not spam', value: 'unspam' },+ { label: 'Move to trash', value: 'trash' },+ { label: 'Restore from trash', value: 'untrash' },+ ],+ },+ }),+ },+ async run(context) {+ const { review_id, status } = context.propsValue;+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.PUT,+ path: `/products/reviews/${wooClient.encodeId(review_id)}`,+ body: { status },+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/update-product-variation.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-product-variation.tsnew file mode 100644index 00000000000..7781f871fce--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-product-variation.ts@@ -0,0 +1,96 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { productVariationOutputSchema } from '../../output-schemas';++export const wooAiUpdateProductVariation = createAction({+ name: 'update_product_variation',+ classification: 'WRITE',+ displayName: 'Update Product Variation',+ description: 'Change selected fields of one variation. Fields left empty are not changed.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes only the supplied fields (price, SKU, status, stock, description) of one variation of a variable product; everything else is left as it is. Find the ids with list_product_variations. For the parent product itself use update_product.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: productVariationOutputSchema,+ props: {+ product_id: Property.Number({+ displayName: 'Product ID',+ description: 'Id of the parent variable product.',+ required: true,+ }),+ variation_id: Property.Number({+ displayName: 'Variation ID',+ description: 'Id of the variation to update.',+ required: true,+ }),+ regular_price: Property.ShortText({+ displayName: 'Regular Price',+ description: 'New regular price as a decimal string, e.g. 19.99.',+ required: false,+ }),+ sale_price: Property.ShortText({+ displayName: 'Sale Price',+ description: 'New sale price as a decimal string. To remove a sale use End Sale instead.',+ required: false,+ }),+ end_sale: Property.Checkbox({+ displayName: 'End Sale',+ description: 'When on, clears the sale price so the variation sells at its regular price again.',+ required: false,+ defaultValue: false,+ }),+ sku: Property.ShortText({+ displayName: 'SKU',+ description: 'New SKU. Must be unique in the store.',+ required: false,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'New status. Private hides the variation from customers.',+ required: false,+ options: { options: wooProps.productStatusOptions },+ }),+ stock_quantity: Property.Number({+ displayName: 'Stock Quantity',+ description: 'New number of units in stock. Setting it turns on stock management for this variation.',+ required: false,+ }),+ stock_status: wooProps.stockStatusProp({+ description: 'New stock status. Ignored when a stock quantity is set.',+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'New variation description.',+ required: false,+ }),+ },+ async run(context) {+ const props = context.propsValue;+ const hasStock = props.stock_quantity !== undefined && props.stock_quantity !== null;+ const body = wooValues.pruneUndefined({+ regular_price: wooValues.nonEmpty(props.regular_price),+ sale_price: props.end_sale ? '' : wooValues.nonEmpty(props.sale_price),+ sku: wooValues.nonEmpty(props.sku),+ status: props.status,+ manage_stock: hasStock ? true : undefined,+ stock_quantity: hasStock ? props.stock_quantity : undefined,+ stock_status: hasStock ? undefined : props.stock_status,+ description: wooValues.nonEmpty(props.description),+ });+ if (Object.keys(body).length === 0) {+ throw new Error('No fields to update were supplied. Provide at least one field to change.');+ }+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.PUT,+ path: `/products/${wooClient.encodeId(props.product_id)}/variations/${wooClient.encodeId(props.variation_id)}`,+ body,+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/ai/update-product.ts b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-product.tsnew file mode 100644index 00000000000..c8f3ba25ca8--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/actions/ai/update-product.ts@@ -0,0 +1,136 @@+import { HttpMethod } from '@activepieces/pieces-common';+import { createAction, Property } from '@activepieces/pieces-framework';+import { wooAuth } from '../../auth';+import { wooClient } from '../../common/client';+import { wooProps, wooValues } from '../../common/props';+import { updateProductOutputSchema } from '../../output-schemas';++export const wooAiUpdateProduct = createAction({+ name: 'update_product',+ classification: 'WRITE',+ displayName: 'Update Product',+ description: 'Change selected fields of a product. Fields left empty are not changed.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Changes only the supplied fields of one product by id; everything else is left as it is. Category IDs and Tag IDs replace the whole list, so include the existing ids you want to keep (read them with get_product). For several products at once use batch_update_products; for a variation use update_product_variation.',+ idempotent: true,+ },+ auth: wooAuth,+ outputSchema: updateProductOutputSchema,+ props: {+ product_id: Property.Number({+ displayName: 'Product ID',+ description: 'Id of the product to update. Find it with list_products.',+ required: true,+ }),+ name: Property.ShortText({+ displayName: 'Name',+ description: 'New product name.',+ required: false,+ }),+ sku: Property.ShortText({+ displayName: 'SKU',+ description: 'New SKU. Must be unique in the store.',+ required: false,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'New status.',+ required: false,+ options: { options: wooProps.productStatusOptions },+ }),+ regular_price: Property.ShortText({+ displayName: 'Regular Price',+ description: 'New regular price as a decimal string, e.g. 19.99.',+ required: false,+ }),+ sale_price: Property.ShortText({+ displayName: 'Sale Price',+ description: 'New sale price as a decimal string. To remove a sale use End Sale instead.',+ required: false,+ }),+ end_sale: Property.Checkbox({+ displayName: 'End Sale',+ description: 'When on, clears the sale price so the product sells at its regular price again.',+ required: false,+ defaultValue: false,+ }),+ stock_quantity: Property.Number({+ displayName: 'Stock Quantity',+ description: 'New number of units in stock. Setting it turns on stock management.',+ required: false,+ }),+ stock_status: wooProps.stockStatusProp({+ description: 'New stock status. Ignored when a stock quantity is set.',+ }),+ featured: wooProps.triStateProp({+ displayName: 'Featured',+ description: 'Yes marks the product as featured, No removes the mark. Leave empty to keep it.',+ }),+ catalog_visibility: Property.StaticDropdown({+ displayName: 'Catalog Visibility',+ description: 'Where the product is shown.',+ required: false,+ options: {+ options: [+ { label: 'Shop and search results', value: 'visible' },+ { label: 'Shop only', value: 'catalog' },+ { label: 'Search results only', value: 'search' },+ { label: 'Hidden', value: 'hidden' },+ ],+ },+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'New full description. HTML is allowed.',+ required: false,+ }),+ short_description: Property.LongText({+ displayName: 'Short Description',+ description: 'New short description. HTML is allowed.',+ required: false,+ }),+ category_ids: Property.Array({+ displayName: 'Category IDs',+ description: 'Replaces all of the product categories with these ids. Include the ones to keep.',+ required: false,+ }),+ tag_ids: Property.Array({+ displayName: 'Tag IDs',+ description: 'Replaces all of the product tags with these ids. Include the ones to keep.',+ required: false,+ }),+ },+ async run(context) {+ const props = context.propsValue;+ const categoryIds = wooValues.toIdList(props.category_ids);+ const tagIds = wooValues.toIdList(props.tag_ids);+ const hasStock = props.stock_quantity !== undefined && props.stock_quantity !== null;+ const body = wooValues.pruneUndefined({+ name: wooValues.nonEmpty(props.name),+ sku: wooValues.nonEmpty(props.sku),+ status: props.status,+ regular_price: wooValues.nonEmpty(props.regular_price),+ sale_price: props.end_sale ? '' : wooValues.nonEmpty(props.sale_price),+ manage_stock: hasStock ? true : undefined,+ stock_quantity: hasStock ? props.stock_quantity : undefined,+ stock_status: hasStock ? undefined : props.stock_status,+ featured: wooValues.resolveTriState(props.featured),+ catalog_visibility: props.catalog_visibility,+ description: wooValues.nonEmpty(props.description),+ short_description: wooValues.nonEmpty(props.short_description),+ categories: categoryIds?.map((id) => ({ id })),+ tags: tagIds?.map((id) => ({ id })),+ });+ if (Object.keys(body).length === 0) {+ throw new Error('No fields to update were supplied. Provide at least one field to change.');+ }+ return wooClient.request<unknown>({+ auth: context.auth.props,+ method: HttpMethod.PUT,+ path: `/products/${wooClient.encodeId(props.product_id)}`,+ body,+ });+ },+});diff --git a/packages/pieces/community/woocommerce/src/lib/actions/create-coupon.ts b/packages/pieces/community/woocommerce/src/lib/actions/create-coupon.tsindex cf9a7068bf8..126d7a26b3f 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/create-coupon.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/create-coupon.ts@@ -19,7 +19,7 @@ export const wooCreateCoupon = createAction({classification: 'WRITE',displayName: 'Create Coupon',description: 'Create a coupon',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Creates a new discount coupon in a WooCommerce store with a code, discount type (fixed_cart, fixed_product, percent, or percent_product), amount, and minimum order amount. Use when an agent needs to issue a promotional or discount code. Not idempotent: each call posts a new coupon, and the code must be unique in the store.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/create-customer.ts b/packages/pieces/community/woocommerce/src/lib/actions/create-customer.tsindex e3e51f260c7..28db2eb026d 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/create-customer.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/create-customer.ts@@ -14,7 +14,7 @@ export const wooCreateCustomer = createAction({classification: 'WRITE',displayName: 'Create Customer',description: 'Create a Customer',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Creates a new customer account in a WooCommerce store with email, name, username, password, and a billing/shipping address (the same address is applied to both). Use when an agent needs to register a shopper. Not idempotent: each call creates a new customer, and email and username must be unique in the store.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/create-order.ts b/packages/pieces/community/woocommerce/src/lib/actions/create-order.tsindex 0f33edd344a..706772de51d 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/create-order.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/create-order.ts@@ -14,10 +14,10 @@ export const wooCreateOrder = createAction({classification: 'WRITE',displayName: 'Create Order',description: 'Create an order with one or more line items',- audience: 'both',+ audience: 'human',aiMetadata: {description:- 'Creates a new order in a WooCommerce store from a list of product IDs and quantities, with an optional customer, status, and billing email. Use when an agent needs to place an order on a customer behalf. Not idempotent: each call creates a separate order.',+ 'Creates a new order in a WooCommerce store from a list of product IDs and quantities, with an optional customer, status, billing email, and payment gateway (payment method id, with an optional display title). Use when an agent needs to place an order on a customer behalf. Not idempotent: each call creates a separate order.',idempotent: false,},auth: wooAuth,@@ -62,6 +62,12 @@ export const wooCreateOrder = createAction({description: 'Email address for the order',required: false,}),+ payment_method: Property.ShortText({+ displayName: 'Payment Method ID',+ description:+ 'Payment gateway id the order is associated with, e.g. bacs, cheque or cod',+ required: false,+ }),payment_method_title: Property.ShortText({displayName: 'Payment Method Title',description: 'Human-readable payment method, e.g. Direct bank transfer',@@ -70,8 +76,14 @@ export const wooCreateOrder = createAction({},async run(configValue) {const trimmedBaseUrl = configValue.auth.props.baseUrl.replace(/\/$/, '');- const { line_items, customer_id, status, billing_email, payment_method_title } =- configValue.propsValue;+ const {+ line_items,+ customer_id,+ status,+ billing_email,+ payment_method,+ payment_method_title,+ } = configValue.propsValue;const body: Record<string, unknown> = {line_items: line_items.map((item) => {@@ -91,6 +103,9 @@ export const wooCreateOrder = createAction({if (billing_email) {body['billing'] = { email: billing_email };}+ if (payment_method) {+ body['payment_method'] = payment_method;+ }if (payment_method_title) {body['payment_method_title'] = payment_method_title;}diff --git a/packages/pieces/community/woocommerce/src/lib/actions/create-product.ts b/packages/pieces/community/woocommerce/src/lib/actions/create-product.tsindex 3f0b9bb224a..faafdc7a38b 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/create-product.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/create-product.ts@@ -14,7 +14,7 @@ export const wooCreateProduct = createAction({classification: 'WRITE',displayName: 'Create Product',description: 'Create a Product',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Creates a new product in a WooCommerce store with a name, type (simple, grouped, external, or variable), regular price, descriptions, category IDs, and image URLs (categories and images are comma-separated lists). Use when an agent needs to add a catalog item. Not idempotent: each call creates a new product.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/find-coupon.ts b/packages/pieces/community/woocommerce/src/lib/actions/find-coupon.tsindex de17bea6c74..5244406d207 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/find-coupon.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/find-coupon.ts@@ -14,7 +14,7 @@ export const wooFindCoupon = createAction({classification: 'READ',displayName: 'Find Coupon',description: 'Find a Coupon',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Retrieves a single coupon from a WooCommerce store by its numeric coupon ID, including the discount type, amount, usage limits and restrictions. Use when an agent already has a coupon ID and needs the full coupon record. Read-only and idempotent.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/find-customer.ts b/packages/pieces/community/woocommerce/src/lib/actions/find-customer.tsindex 1b9f9b52743..eb80cb27d05 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/find-customer.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/find-customer.ts@@ -14,7 +14,7 @@ export const wooFindCustomer = createAction({classification: 'READ',displayName: 'Find Customer',description: 'Find a Customer',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Looks up customers in a WooCommerce store by exact email address. Use when an agent needs to resolve a shopper to their customer record or ID before referencing them. Read-only and idempotent. Requires the email; returns matching customers (empty if none match).',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/find-orders.ts b/packages/pieces/community/woocommerce/src/lib/actions/find-orders.tsindex 387d449e4c1..fe2110b96ef 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/find-orders.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/find-orders.ts@@ -14,7 +14,7 @@ export const wooFindOrders = createAction({classification: 'READ',displayName: 'Find Orders',description: 'Search orders by status, customer or date',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Searches orders in a WooCommerce store, optionally narrowed by status, customer ID, or a created-after date, and returns a list of full order records. Use when an agent needs to process a batch of orders rather than one known order. Read-only and idempotent. Returns an array, newest first.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/find-product.ts b/packages/pieces/community/woocommerce/src/lib/actions/find-product.tsindex 2696f705fbc..3f1ef6a8ba6 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/find-product.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/find-product.ts@@ -14,7 +14,7 @@ export const wooFindProduct = createAction({classification: 'READ',displayName: 'Find Product',description: 'Find a Product',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Retrieves a single product from a WooCommerce store by its numeric product ID. Use when an agent already has a product ID and needs the full product record (price, stock, status, etc.). Read-only and idempotent. Requires the exact product ID.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/get-customer.ts b/packages/pieces/community/woocommerce/src/lib/actions/get-customer.tsindex 8b90b213e22..8088e50cbff 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/get-customer.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/get-customer.ts@@ -14,7 +14,7 @@ export const wooGetCustomer = createAction({classification: 'READ',displayName: 'Get Customer',description: 'Retrieve a single customer by their ID',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Retrieves one customer from a WooCommerce store by their numeric customer ID, including billing and shipping addresses. Use when an agent has a customer ID rather than an email address; Find Customer searches by email instead. Read-only and idempotent.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/get-order.ts b/packages/pieces/community/woocommerce/src/lib/actions/get-order.tsindex f95fcbfd114..0fcf59ab72c 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/get-order.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/get-order.ts@@ -14,7 +14,7 @@ export const wooGetOrder = createAction({classification: 'READ',displayName: 'Get Order',description: 'Retrieve a single order by its ID',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Retrieves one order from a WooCommerce store by its numeric order ID, including line items, billing and shipping addresses, totals, and status. Use when an agent already has an order ID and needs the full order record. Read-only and idempotent.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/update-coupon.ts b/packages/pieces/community/woocommerce/src/lib/actions/update-coupon.tsindex 6162eaeca47..2ae8eb90003 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/update-coupon.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/update-coupon.ts@@ -14,7 +14,7 @@ export const wooUpdateCoupon = createAction({classification: 'WRITE',displayName: 'Update Coupon',description: 'Update a coupon amount, description, expiry or usage limit',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Updates an existing WooCommerce coupon by ID. Can change the discount amount and type, description, expiry date, usage limit and minimum spend. Only the fields provided are changed. Idempotent: sending the same values twice leaves the coupon in the same state.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/update-customer.ts b/packages/pieces/community/woocommerce/src/lib/actions/update-customer.tsindex f7933cd6e14..3ae04936a00 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/update-customer.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/update-customer.ts@@ -14,7 +14,7 @@ export const wooUpdateCustomer = createAction({classification: 'WRITE',displayName: 'Update Customer',description: 'Update a customer name, email or billing details',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Updates an existing WooCommerce customer by ID. Can change the email, first and last name, and billing phone, city, postcode and country. Only the fields provided are changed. Idempotent: sending the same values twice leaves the customer in the same state.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/update-order.ts b/packages/pieces/community/woocommerce/src/lib/actions/update-order.tsindex 7ce5c414cfb..9859f5ad8fc 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/update-order.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/update-order.ts@@ -14,7 +14,7 @@ export const wooUpdateOrder = createAction({classification: 'WRITE',displayName: 'Update Order',description: 'Update an order, most commonly its status',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Updates an existing WooCommerce order by ID. Most often used to move an order through its lifecycle by setting status (pending, processing, on-hold, completed, cancelled, refunded, failed), and can also set the customer note or transaction ID. Only the fields provided are changed. Idempotent: applying the same status twice leaves the order in the same state.',diff --git a/packages/pieces/community/woocommerce/src/lib/actions/update-product.ts b/packages/pieces/community/woocommerce/src/lib/actions/update-product.tsindex 9198ca8ce20..3d57543eb09 100644--- a/packages/pieces/community/woocommerce/src/lib/actions/update-product.ts+++ b/packages/pieces/community/woocommerce/src/lib/actions/update-product.ts@@ -14,7 +14,7 @@ export const wooUpdateProduct = createAction({classification: 'WRITE',displayName: 'Update Product',description: 'Update a product, for example its price or stock level',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Updates an existing WooCommerce product by ID. Commonly used to change price, sale price, stock quantity, or publish status. Only the fields provided are changed; everything else is left untouched. Idempotent: sending the same values twice leaves the product in the same state.',diff --git a/packages/pieces/community/woocommerce/src/lib/common/client.ts b/packages/pieces/community/woocommerce/src/lib/common/client.tsnew file mode 100644index 00000000000..2cb487fe004--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/common/client.ts@@ -0,0 +1,139 @@+import {+ AuthenticationType,+ HttpError,+ HttpMethod,+ httpClient,+ QueryParams,+} from '@activepieces/pieces-common';+import { tryCatch } from '@activepieces/pieces-framework';++async function request<T>({+ auth,+ method,+ path,+ queryParams,+ body,+}: WooRequestParams): Promise<T> {+ const baseUrl = auth.baseUrl.replace(/\/$/, '');+ const { data, error } = await tryCatch(() =>+ httpClient.sendRequest<T>({+ method,+ url: `${baseUrl}/wp-json/wc/v3${path}`,+ authentication: {+ type: AuthenticationType.BASIC,+ username: auth.consumerKey,+ password: auth.consumerSecret,+ },+ queryParams: dropEmpty(queryParams),+ body,+ })+ );+ if (error) {+ throw toWooError(error);+ }+ return data.body;+}++function dropEmpty(queryParams: WooQueryParams | undefined): QueryParams {+ const result: QueryParams = {};+ if (!queryParams) {+ return result;+ }+ for (const [key, value] of Object.entries(queryParams)) {+ if (value !== undefined && value !== null && value !== '') {+ result[key] = String(value);+ }+ }+ return result;+}++function toWooError(error: Error): Error {+ if (!(error instanceof HttpError)) {+ return error;+ }+ const status = error.response.status;+ const body = readWooErrorBody(error.response.body);+ const detail = `WooCommerce returned ${status}${body.code ? ` (${body.code})` : ''}`;+ const message = body.message ?? '';+ if (status === 401) {+ return new Error(+ `${detail}: authentication failed. Check that the consumer key and secret are valid, that the key has Read/Write permission, and that the store is reached over HTTPS. ${message}`.trim()+ );+ }+ if (status === 403) {+ return new Error(+ `${detail}: the API key's user is not allowed to perform this operation. ${message}`.trim()+ );+ }+ if (status === 404) {+ return new Error(+ `${detail}: the requested resource was not found; check the id. ${message}`.trim()+ );+ }+ if (status === 410) {+ return new Error(+ `${detail}: the resource is already in the trash. Pass permanent=true to delete it for good. ${message}`.trim()+ );+ }+ if (body.resourceId !== undefined) {+ return new Error(+ `${detail}: ${message} Existing resource id: ${body.resourceId}.`+ );+ }+ return new Error(message ? `${detail}: ${message}` : detail);+}++function readWooErrorBody(body: unknown): WooErrorBody {+ if (typeof body !== 'object' || body === null) {+ return {};+ }+ const record: Record<string, unknown> = Object(body);+ const data: Record<string, unknown> =+ typeof record['data'] === 'object' && record['data'] !== null+ ? Object(record['data'])+ : {};+ const resourceId = data['resource_id'];+ return {+ code: typeof record['code'] === 'string' ? record['code'] : undefined,+ message:+ typeof record['message'] === 'string' ? record['message'] : undefined,+ resourceId:+ typeof resourceId === 'number' || typeof resourceId === 'string'+ ? resourceId+ : undefined,+ };+}++function encodeId(id: string | number): string {+ return encodeURIComponent(String(id).trim());+}++export const wooClient = {+ request,+ encodeId,+};++export type WooAuthProps = {+ baseUrl: string;+ consumerKey: string;+ consumerSecret: string;+};++export type WooQueryParams = Record<+ string,+ string | number | boolean | undefined | null+>;++type WooRequestParams = {+ auth: WooAuthProps;+ method: HttpMethod;+ path: string;+ queryParams?: WooQueryParams;+ body?: unknown;+};++type WooErrorBody = {+ code?: string;+ message?: string;+ resourceId?: number | string;+};diff --git a/packages/pieces/community/woocommerce/src/lib/common/props.ts b/packages/pieces/community/woocommerce/src/lib/common/props.tsnew file mode 100644index 00000000000..3107ed94e5d--- /dev/null+++ b/packages/pieces/community/woocommerce/src/lib/common/props.ts@@ -0,0 +1,253 @@+import { propsValidation } from '@activepieces/pieces-common';+import { Property } from '@activepieces/pieces-framework';+import * as z from 'zod/mini';++function pageProp() {+ return Property.Number({+ displayName: 'Page',+ description:+ 'Page number, starting at 1. If a page comes back with exactly per_page items, request the next page to see more.',+ required: false,+ defaultValue: 1,+ });+}++function perPageProp() {+ return Property.Number({+ displayName: 'Per Page',+ description: 'Number of items per page, from 1 to 100. Defaults to 10.',+ required: false,+ defaultValue: 10,+ });+}++function sortOrderProp() {+ return Property.StaticDropdown({+ displayName: 'Sort Direction',+ description: 'Ascending or descending. Defaults to descending.',+ required: false,+ options: {+ options: [+ { label: 'Descending', value: 'desc' },+ { label: 'Ascending', value: 'asc' },+ ],+ },+ });+}++function triStateProp({+ displayName,+ description,+}: {+ displayName: string;+ description: string;+}) {+ return Property.StaticDropdown({+ displayName,+ description,+ required: false,+ options: {+ options: [+ { label: 'Yes', value: 'yes' },+ { label: 'No', value: 'no' },+ ],+ },+ });+}++function stockStatusProp({ description }: { description: string }) {+ return Property.StaticDropdown({+ displayName: 'Stock Status',+ description,+ required: false,+ options: { options: stockStatusOptions },+ });+}++function permanentProp({ resource }: { resource: string }) {+ return Property.Checkbox({+ displayName: 'Delete Permanently',+ description: `When off (the default) the ${resource} is moved to the trash and can be restored from the WordPress admin. When on it is deleted for good.`,+ required: false,+ defaultValue: false,+ });+}++async function paging({+ page,+ perPage,+}: {+ page: number | undefined;+ perPage: number | undefined;+}): Promise<{ page: number; per_page: number }> {+ await propsValidation.validateZod(+ { page, per_page: perPage },+ {+ page: z.optional(z.number().check(z.minimum(1))),+ per_page: z.optional(z.number().check(z.minimum(1), z.maximum(100))),+ }+ );+ return { page: page ?? 1, per_page: perPage ?? 10 };+}++function resolveTriState(value: string | undefined | null): boolean | undefined {+ if (value === 'yes') {+ return true;+ }+ if (value === 'no') {+ return false;+ }+ return undefined;+}++function toIdList(values: unknown[] | undefined | null): number[] | undefined {+ if (!values || values.length === 0) {+ return undefined;+ }+ return values.map((value) => {+ const parsed = Number(String(value).trim());+ if (!Number.isInteger(parsed) || parsed <= 0) {+ throw new Error(+ `Expected a list of numeric ids, but got "${String(value)}". Read the ids with the matching list action first.`+ );+ }+ return parsed;+ });+}++function toStringList(+ values: unknown[] | undefined | null+): string[] | undefined {+ if (!values || values.length === 0) {+ return undefined;+ }+ return values+ .map((value) => String(value).trim())+ .filter((value) => value.length > 0);+}++function pruneUndefined(+ record: Record<string, unknown>+): Record<string, unknown> {+ return Object.fromEntries(+ Object.entries(record).filter(([, value]) => value !== undefined)+ );+}++function nonEmpty(value: string | undefined | null): string | undefined {+ if (value === undefined || value === null) {+ return undefined;+ }+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : undefined;+}++function reportRangeProps() {+ return {+ period: Property.StaticDropdown({+ displayName: 'Period',+ description: 'Preset period to report on. Leave empty when using a date range; if both are empty the current week is used.',+ required: false,+ options: {+ options: [+ { label: 'This week', value: 'week' },+ { label: 'This month', value: 'month' },+ { label: 'Last month', value: 'last_month' },+ { label: 'This year', value: 'year' },+ ],+ },+ }),+ date_min: Property.ShortText({+ displayName: 'Start Date',+ description: 'First day of a custom range, as YYYY-MM-DD. Use together with End Date instead of Period.',+ required: false,+ }),+ date_max: Property.ShortText({+ displayName: 'End Date',+ description: 'Last day of a custom range, as YYYY-MM-DD. Use together with Start Date instead of Period.',+ required: false,+ }),+ };+}++function resolveReportRange({+ period,+ dateMin,+ dateMax,+}: {+ period: string | undefined | null;+ dateMin: string | undefined | null;+ dateMax: string | undefined | null;+}): Record<string, string | undefined> {+ const min = nonEmpty(dateMin);+ const max = nonEmpty(dateMax);+ if ((min && !max) || (!min && max)) {+ throw new Error('Provide both Start Date and End Date for a custom range, or neither.');+ }+ if (period && min) {+ throw new Error('Provide either Period or a Start Date and End Date range, not both.');+ }+ if (min && max) {+ const datePattern = /^\d{4}-\d{2}-\d{2}$/;+ if (!datePattern.test(min) || !datePattern.test(max)) {+ throw new Error('Start Date and End Date must be in YYYY-MM-DD format.');+ }+ return { date_min: min, date_max: max };+ }+ return { period: period ?? undefined };+}++const stockStatusOptions = [+ { label: 'In stock', value: 'instock' },+ { label: 'Out of stock', value: 'outofstock' },+ { label: 'On backorder', value: 'onbackorder' },+];++const orderStatusOptions = [+ { label: 'Pending payment', value: 'pending' },+ { label: 'Processing', value: 'processing' },+ { label: 'On hold', value: 'on-hold' },+ { label: 'Completed', value: 'completed' },+ { label: 'Cancelled', value: 'cancelled' },+ { label: 'Refunded', value: 'refunded' },+ { label: 'Failed', value: 'failed' },+ { label: 'Trash', value: 'trash' },+];++const productStatusOptions = [+ { label: 'Published', value: 'publish' },+ { label: 'Draft', value: 'draft' },+ { label: 'Pending review', value: 'pending' },+ { label: 'Private', value: 'private' },+];++const productTypeOptions = [+ { label: 'Simple', value: 'simple' },+ { label: 'Variable', value: 'variable' },+ { label: 'Grouped', value: 'grouped' },+ { label: 'External / affiliate', value: 'external' },+];++export const wooProps = {+ pageProp,+ perPageProp,+ sortOrderProp,+ triStateProp,+ stockStatusProp,+ permanentProp,+ reportRangeProps,+ stockStatusOptions,+ orderStatusOptions,+ productStatusOptions,+ productTypeOptions,+};++export const wooValues = {+ paging,+ resolveTriState,+ toIdList,+ toStringList,+ pruneUndefined,+ nonEmpty,+ resolveReportRange,+};diff --git a/packages/pieces/community/woocommerce/src/lib/output-schemas.ts b/packages/pieces/community/woocommerce/src/lib/output-schemas.tsindex 3f8823e8a55..df739a931df 100644--- a/packages/pieces/community/woocommerce/src/lib/output-schemas.ts+++ b/packages/pieces/community/woocommerce/src/lib/output-schemas.ts@@ -341,6 +341,168 @@ const orderNoteFields: Fields = [{ key: 'date_created_gmt', label: 'Created At (GMT)', format: 'datetime' },];+const variationAttributeFields: Fields = [+ { key: 'id', label: 'Attribute ID' },+ { key: 'name', label: 'Name' },+ { key: 'slug', label: 'Slug' },+ { key: 'option', label: 'Option' },+];++const variationFields: Fields = [+ { key: 'id', label: 'Variation ID' },+ { key: 'parent_id', label: 'Parent Product ID' },+ { key: 'name', label: 'Name' },+ { key: 'type', label: 'Type' },+ { key: 'status', label: 'Status' },+ { key: 'description', label: 'Description', format: 'html' },+ { key: 'permalink', label: 'Permalink', format: 'url' },+ { key: 'sku', label: 'SKU' },+ { key: 'global_unique_id', label: 'Global Unique ID' },+ { key: 'price', label: 'Price' },+ { key: 'regular_price', label: 'Regular Price' },+ { key: 'sale_price', label: 'Sale Price' },+ { key: 'date_on_sale_from', label: 'On Sale From', format: 'datetime' },+ { key: 'date_on_sale_from_gmt', label: 'On Sale From (GMT)', format: 'datetime' },+ { key: 'date_on_sale_to', label: 'On Sale To', format: 'datetime' },+ { key: 'date_on_sale_to_gmt', label: 'On Sale To (GMT)', format: 'datetime' },+ { key: 'on_sale', label: 'On Sale', format: 'boolean' },+ { key: 'purchasable', label: 'Purchasable', format: 'boolean' },+ { key: 'virtual', label: 'Virtual', format: 'boolean' },+ { key: 'downloadable', label: 'Downloadable', format: 'boolean' },+ { key: 'downloads', label: 'Downloads', listItems: downloadFields, labelKey: 'name' },+ { key: 'download_limit', label: 'Download Limit', format: 'number' },+ { key: 'download_expiry', label: 'Download Expiry (Days)', format: 'number' },+ { key: 'tax_status', label: 'Tax Status' },+ { key: 'tax_class', label: 'Tax Class' },+ { key: 'manage_stock', label: 'Manage Stock' },+ { key: 'stock_quantity', label: 'Stock Quantity', format: 'number' },+ { key: 'stock_status', label: 'Stock Status' },+ { key: 'backorders', label: 'Backorders' },+ { key: 'backorders_allowed', label: 'Backorders Allowed', format: 'boolean' },+ { key: 'backordered', label: 'Backordered', format: 'boolean' },+ { key: 'low_stock_amount', label: 'Low Stock Amount', format: 'number' },+ { key: 'weight', label: 'Weight' },+ { key: 'dimensions', label: 'Dimensions', children: dimensionFields },+ { key: 'shipping_class', label: 'Shipping Class' },+ { key: 'shipping_class_id', label: 'Shipping Class ID' },+ { key: 'image', label: 'Image', children: imageFields },+ { key: 'gallery_image_ids', label: 'Gallery Image IDs' },+ { key: 'attributes', label: 'Attributes', listItems: variationAttributeFields, labelKey: 'name' },+ { key: 'menu_order', label: 'Menu Order', format: 'number' },+ { key: 'date_created', label: 'Created At', format: 'datetime' },+ { key: 'date_created_gmt', label: 'Created At (GMT)', format: 'datetime' },+ { key: 'date_modified', label: 'Modified At', format: 'datetime' },+ { key: 'date_modified_gmt', label: 'Modified At (GMT)', format: 'datetime' },+ { key: 'meta_data', label: 'Meta Data', listItems: metaDataFields, labelKey: 'key' },+];++const categoryFields: Fields = [+ { key: 'id', label: 'Category ID' },+ { key: 'name', label: 'Name' },+ { key: 'slug', label: 'Slug' },+ { key: 'parent', label: 'Parent Category ID' },+ { key: 'description', label: 'Description', format: 'html' },+ { key: 'display', label: 'Display Type' },+ { key: 'image', label: 'Image' },+ { key: 'menu_order', label: 'Menu Order', format: 'number' },+ { key: 'count', label: 'Product Count', format: 'number' },+];++const tagFields: Fields = [+ { key: 'id', label: 'Tag ID' },+ { key: 'name', label: 'Name' },+ { key: 'slug', label: 'Slug' },+ { key: 'description', label: 'Description' },+ { key: 'count', label: 'Product Count', format: 'number' },+];++const reviewFields: Fields = [+ { key: 'id', label: 'Review ID' },+ { key: 'product_id', label: 'Product ID' },+ { key: 'product_name', label: 'Product Name' },+ { key: 'product_permalink', label: 'Product URL', format: 'url' },+ { key: 'status', label: 'Status' },+ { key: 'reviewer', label: 'Reviewer' },+ { key: 'reviewer_email', label: 'Reviewer Email', format: 'email' },+ { key: 'review', label: 'Review', format: 'html' },+ { key: 'rating', label: 'Rating', format: 'number' },+ { key: 'verified', label: 'Verified Owner', format: 'boolean' },+ { key: 'reviewer_avatar_urls', label: 'Reviewer Avatar URLs', children: [+ { key: '24', label: 'Avatar 24px', format: 'url' },+ { key: '48', label: 'Avatar 48px', format: 'url' },+ { key: '96', label: 'Avatar 96px', format: 'url' },+ ] },+ { key: 'date_created', label: 'Created At', format: 'datetime' },+ { key: 'date_created_gmt', label: 'Created At (GMT)', format: 'datetime' },+];++const refundFields: Fields = [+ { key: 'id', label: 'Refund ID' },+ { key: 'amount', label: 'Amount' },+ { key: 'reason', label: 'Reason' },+ { key: 'refunded_by', label: 'Refunded By User ID' },+ { key: 'refunded_payment', label: 'Refunded Through Gateway', format: 'boolean' },+ { key: 'date_created', label: 'Created At', format: 'datetime' },+ { key: 'date_created_gmt', label: 'Created At (GMT)', format: 'datetime' },+ { key: 'line_items', label: 'Refunded Line Items', listItems: lineItemFields, labelKey: 'name' },+ { key: 'shipping_lines', label: 'Refunded Shipping Lines', listItems: shippingLineFields, labelKey: 'method_title' },+ { key: 'tax_lines', label: 'Refunded Tax Lines', listItems: taxLineFields, labelKey: 'label' },+ { key: 'fee_lines', label: 'Refunded Fee Lines', listItems: feeLineFields, labelKey: 'name' },+ { key: 'meta_data', label: 'Meta Data', listItems: metaDataFields, labelKey: 'key' },+];++const salesReportFields: Fields = [+ { key: 'total_sales', label: 'Total Sales' },+ { key: 'net_sales', label: 'Net Sales' },+ { key: 'average_sales', label: 'Average Sales Per Day' },+ { key: 'total_orders', label: 'Total Orders', format: 'number' },+ { key: 'total_items', label: 'Total Items', format: 'number' },+ { key: 'total_tax', label: 'Total Tax' },+ { key: 'total_shipping', label: 'Total Shipping' },+ { key: 'total_refunds', label: 'Total Refunds' },+ { key: 'total_discount', label: 'Total Discount' },+ { key: 'total_customers', label: 'New Customers', format: 'number' },+ { key: 'totals_grouped_by', label: 'Grouped By' },+ { key: 'totals', label: 'Totals By Period', dynamicKey: true, children: [+ { key: 'sales', label: 'Sales' },+ { key: 'orders', label: 'Orders', format: 'number' },+ { key: 'items', label: 'Items', format: 'number' },+ { key: 'tax', label: 'Tax' },+ { key: 'shipping', label: 'Shipping' },+ { key: 'discount', label: 'Discount' },+ { key: 'customers', label: 'New Customers', format: 'number' },+ { key: 'refunds', label: 'Refunds' },+ ] },+];++const topSellerFields: Fields = [+ { key: 'name', label: 'Product Name' },+ { key: 'product_id', label: 'Product ID' },+ { key: 'quantity', label: 'Quantity Sold', format: 'number' },+];++const orderTotalFields: Fields = [+ { key: 'slug', label: 'Status' },+ { key: 'name', label: 'Status Name' },+ { key: 'total', label: 'Orders', format: 'number' },+];++const paymentGatewayFields: Fields = [+ { key: 'id', label: 'Gateway ID' },+ { key: 'title', label: 'Title' },+ { key: 'description', label: 'Description' },+ { key: 'order', label: 'Sort Order' },+ { key: 'enabled', label: 'Enabled', format: 'boolean' },+ { key: 'method_title', label: 'Method Title' },+ { key: 'method_description', label: 'Method Description', format: 'html' },+ { key: 'method_supports', label: 'Supported Features' },+];++const batchErrorFields: Fields = [+ { key: 'code', label: 'Error Code' },+ { key: 'message', label: 'Error Message' },+];+const listOf = (key: string, label: string, fields: Fields, itemLabel: string): OutputSchema => ({itemLabel,fields: [{ key, label, value: '', listItems: fields }],@@ -366,6 +528,39 @@ export const findOrdersOutputSchema: OutputSchema = listOf('orders', 'Orders', oexport const addOrderNoteOutputSchema: OutputSchema = { fields: orderNoteFields };+export const listProductsOutputSchema: OutputSchema = listOf('products', 'Products', productFields, '{name}');+export const deleteProductOutputSchema: OutputSchema = { fields: productFields };+export const batchUpdateProductsOutputSchema: OutputSchema = {+ fields: [+ { key: 'update', label: 'Updated Products', labelKey: 'name', listItems: [+ ...productFields,+ { key: 'error', label: 'Error', children: batchErrorFields },+ ] },+ ],+};+export const listProductVariationsOutputSchema: OutputSchema = listOf('variations', 'Variations', variationFields, '{sku}');+export const productVariationOutputSchema: OutputSchema = { fields: variationFields };+export const listProductCategoriesOutputSchema: OutputSchema = listOf('categories', 'Categories', categoryFields, '{name}');+export const productCategoryOutputSchema: OutputSchema = { fields: categoryFields };+export const listProductTagsOutputSchema: OutputSchema = listOf('tags', 'Tags', tagFields, '{name}');+export const productTagOutputSchema: OutputSchema = { fields: tagFields };+export const listProductReviewsOutputSchema: OutputSchema = listOf('reviews', 'Reviews', reviewFields, '{reviewer}');+export const productReviewOutputSchema: OutputSchema = { fields: reviewFields };+export const listOrdersOutputSchema: OutputSchema = listOf('orders', 'Orders', orderFields, '#{number} — {status}');+export const deleteOrderOutputSchema: OutputSchema = { fields: orderFields };+export const listOrderNotesOutputSchema: OutputSchema = listOf('notes', 'Notes', orderNoteFields, '{note}');+export const deleteOrderNoteOutputSchema: OutputSchema = { fields: orderNoteFields };+export const orderRefundOutputSchema: OutputSchema = { fields: refundFields };+export const listOrderRefundsOutputSchema: OutputSchema = listOf('refunds', 'Refunds', refundFields, '{amount} — {reason}');+export const listCustomersOutputSchema: OutputSchema = listOf('customers', 'Customers', customerFields, '{email}');+export const deleteCustomerOutputSchema: OutputSchema = { fields: customerFields };+export const listCouponsOutputSchema: OutputSchema = listOf('coupons', 'Coupons', couponFields, '{code}');+export const deleteCouponOutputSchema: OutputSchema = { fields: couponFields };+export const salesReportOutputSchema: OutputSchema = listOf('report', 'Sales Report', salesReportFields, '{total_sales}');+export const topSellersReportOutputSchema: OutputSchema = listOf('top_sellers', 'Top Sellers', topSellerFields, '{name}');+export const orderTotalsReportOutputSchema: OutputSchema = listOf('totals', 'Order Totals', orderTotalFields, '{name}');+export const listPaymentGatewaysOutputSchema: OutputSchema = listOf('gateways', 'Payment Gateways', paymentGatewayFields, '{title}');+export const productTriggerOutputSchema: OutputSchema = { fields: productFields };export const orderTriggerOutputSchema: OutputSchema = { fields: orderFields };export const couponTriggerOutputSchema: OutputSchema = { fields: couponFields };diff --git a/packages/pieces/community/wordpress/package.json b/packages/pieces/community/wordpress/package.jsonindex d5eeb06c8a6..f68535d0e82 100644--- a/packages/pieces/community/wordpress/package.json+++ b/packages/pieces/community/wordpress/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-wordpress",- "version": "0.6.0",+ "version": "0.7.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {diff --git a/packages/pieces/community/wordpress/src/i18n/translation.json b/packages/pieces/community/wordpress/src/i18n/translation.jsonindex 363a0db9280..81cf5c5168f 100644--- a/packages/pieces/community/wordpress/src/i18n/translation.json+++ b/packages/pieces/community/wordpress/src/i18n/translation.json@@ -72,5 +72,262 @@"Raw": "Raw","New Post": "New Post","Triggers when a new post is published": "Triggers when a new post is published",- "Authors": "Authors"-}\ No newline at end of file+ "Authors": "Authors",+ "List Posts": "List Posts",+ "Lists blog posts, optionally filtered by keyword, status, category, tag, author or date.": "Lists blog posts, optionally filtered by keyword, status, category, tag, author or date.",+ "Search": "Search",+ "Only posts whose title, content or excerpt contain this text.": "Only posts whose title, content or excerpt contain this text.",+ "Post statuses to include. Defaults to published only. \"Any\" includes every status except trash.": "Post statuses to include. Defaults to published only. \"Any\" includes every status except trash.",+ "Pending Review": "Pending Review",+ "Any": "Any",+ "Category IDs": "Category IDs",+ "Only posts in any of these category IDs (from list_categories).": "Only posts in any of these category IDs (from list_categories).",+ "Tag IDs": "Tag IDs",+ "Only posts with any of these tag IDs (from list_tags).": "Only posts with any of these tag IDs (from list_tags).",+ "Author ID": "Author ID",+ "Only posts by this user ID (from list_users).": "Only posts by this user ID (from list_users).",+ "Published After": "Published After",+ "Only posts published after this ISO 8601 date, e.g. 2026-01-31T00:00:00.": "Only posts published after this ISO 8601 date, e.g. 2026-01-31T00:00:00.",+ "Published Before": "Published Before",+ "Only posts published before this ISO 8601 date.": "Only posts published before this ISO 8601 date.",+ "Order By": "Order By",+ "Sort field. Defaults to date. \"Relevance\" needs Search.": "Sort field. Defaults to date. \"Relevance\" needs Search.",+ "Modified Date": "Modified Date",+ "ID": "ID",+ "Relevance": "Relevance",+ "Order": "Order",+ "Sort direction. Defaults to descending.": "Sort direction. Defaults to descending.",+ "Descending": "Descending",+ "Ascending": "Ascending",+ "Results Per Page": "Results Per Page",+ "How many results to return, from 1 to 100. Defaults to 10.": "How many results to return, from 1 to 100. Defaults to 10.",+ "Page": "Page",+ "Page of results to return, starting at 1. The output reports total_pages.": "Page of results to return, starting at 1. The output reports total_pages.",+ "Get Post by ID": "Get Post by ID",+ "Gets one blog post by its ID.": "Gets one blog post by its ID.",+ "ID of the post, from list_posts or search_site_content.": "ID of the post, from list_posts or search_site_content.",+ "Create Blog Post": "Create Blog Post",+ "Creates a blog post. Saved as a draft unless a status is given.": "Creates a blog post. Saved as a draft unless a status is given.",+ "The post title.": "The post title.",+ "The post body as HTML.": "The post body as HTML.",+ "Leave empty to save the post as a draft. \"Scheduled (future)\" needs a Publish Date.": "Leave empty to save the post as a draft. \"Scheduled (future)\" needs a Publish Date.",+ "Publish": "Publish",+ "Scheduled (future)": "Scheduled (future)",+ "Publish Date": "Publish Date",+ "Publish date in the site's timezone, ISO 8601 (e.g. 2030-01-31T09:00:00). A past date with status \"future\" publishes immediately.": "Publish date in the site's timezone, ISO 8601 (e.g. 2030-01-31T09:00:00). A past date with status \"future\" publishes immediately.",+ "URL slug.": "URL slug.",+ "Featured Media ID": "Featured Media ID",+ "ID of an uploaded image to use as the featured image. Get it from upload_media or list_media.": "ID of an uploaded image to use as the featured image. Get it from upload_media or list_media.",+ "User ID of the author. Get it from list_users or get_current_user. Leave empty for the connected user.": "User ID of the author. Get it from list_users or get_current_user. Leave empty for the connected user.",+ "Comments": "Comments",+ "Whether visitors can comment.": "Whether visitors can comment.",+ "Open": "Open",+ "Closed": "Closed",+ "Pingbacks": "Pingbacks",+ "Whether the post accepts pingbacks and trackbacks.": "Whether the post accepts pingbacks and trackbacks.",+ "Short summary of the post.": "Short summary of the post.",+ "Category IDs from list_categories or create_category.": "Category IDs from list_categories or create_category.",+ "Tag IDs from list_tags or create_tag.": "Tag IDs from list_tags or create_tag.",+ "Sticky": "Sticky",+ "Whether the post is pinned to the top of the blog.": "Whether the post is pinned to the top of the blog.",+ "Yes": "Yes",+ "No": "No",+ "Format": "Format",+ "Custom ACF Fields": "Custom ACF Fields",+ "Post format. Only formats the active theme supports are accepted.": "Post format. Only formats the active theme supports are accepted.",+ "Advanced Custom Fields values as field name and value pairs; field names come from the ACF plugin menu. Only the fields you supply are written. Requires the site to expose ACF over the REST API.": "Advanced Custom Fields values as field name and value pairs; field names come from the ACF plugin menu. Only the fields you supply are written. Requires the site to expose ACF over the REST API.",+ "Standard": "Standard",+ "Aside": "Aside",+ "Chat": "Chat",+ "Gallery": "Gallery",+ "Link": "Link",+ "Image": "Image",+ "Quote": "Quote",+ "Video": "Video",+ "Audio": "Audio",+ "Update Blog Post": "Update Blog Post",+ "Changes only the fields you supply on an existing blog post.": "Changes only the fields you supply on an existing blog post.",+ "ID of the post to update, from list_posts.": "ID of the post to update, from list_posts.",+ "The post title. Leave empty to keep the current value.": "The post title. Leave empty to keep the current value.",+ "The post body as HTML. Leave empty to keep the current value.": "The post body as HTML. Leave empty to keep the current value.",+ "New status. Leave empty to keep the current value. To trash the post, use the trash action instead.": "New status. Leave empty to keep the current value. To trash the post, use the trash action instead.",+ "Publish date in the site's timezone, ISO 8601 (e.g. 2030-01-31T09:00:00). A past date with status \"future\" publishes immediately. Leave empty to keep the current value.": "Publish date in the site's timezone, ISO 8601 (e.g. 2030-01-31T09:00:00). A past date with status \"future\" publishes immediately. Leave empty to keep the current value.",+ "URL slug. Leave empty to keep the current value.": "URL slug. Leave empty to keep the current value.",+ "ID of an uploaded image to use as the featured image. Get it from upload_media or list_media. Leave empty to keep the current value.": "ID of an uploaded image to use as the featured image. Get it from upload_media or list_media. Leave empty to keep the current value.",+ "Whether visitors can comment. Leave empty to keep the current value.": "Whether visitors can comment. Leave empty to keep the current value.",+ "Whether the post accepts pingbacks and trackbacks. Leave empty to keep the current value.": "Whether the post accepts pingbacks and trackbacks. Leave empty to keep the current value.",+ "Short summary of the post. Leave empty to keep the current value.": "Short summary of the post. Leave empty to keep the current value.",+ "Category IDs from list_categories or create_category. The list replaces the post's current set. Leave empty to keep the current value.": "Category IDs from list_categories or create_category. The list replaces the post's current set. Leave empty to keep the current value.",+ "Tag IDs from list_tags or create_tag. The list replaces the post's current set. Leave empty to keep the current value.": "Tag IDs from list_tags or create_tag. The list replaces the post's current set. Leave empty to keep the current value.",+ "Whether the post is pinned to the top of the blog. Leave empty to keep the current value.": "Whether the post is pinned to the top of the blog. Leave empty to keep the current value.",+ "Post format. Only formats the active theme supports are accepted. Leave empty to keep the current value.": "Post format. Only formats the active theme supports are accepted. Leave empty to keep the current value.",+ "Advanced Custom Fields values as field name and value pairs; field names come from the ACF plugin menu. Only the fields you supply are written. Requires the site to expose ACF over the REST API. Leave empty to keep the current value.": "Advanced Custom Fields values as field name and value pairs; field names come from the ACF plugin menu. Only the fields you supply are written. Requires the site to expose ACF over the REST API. Leave empty to keep the current value.",+ "Move Post to Trash": "Move Post to Trash",+ "Moves a blog post to the trash, where it can still be restored.": "Moves a blog post to the trash, where it can still be restored.",+ "ID of the post to trash, from list_posts.": "ID of the post to trash, from list_posts.",+ "Delete Post Permanently": "Delete Post Permanently",+ "Permanently deletes a blog post, skipping the trash. This cannot be undone.": "Permanently deletes a blog post, skipping the trash. This cannot be undone.",+ "ID of the post to delete, from list_posts.": "ID of the post to delete, from list_posts.",+ "List Pages": "List Pages",+ "Lists site pages, optionally filtered by keyword, status or parent page.": "Lists site pages, optionally filtered by keyword, status or parent page.",+ "Only pages whose title or content contain this text.": "Only pages whose title or content contain this text.",+ "Page statuses to include. Defaults to published only. \"Any\" includes every status except trash.": "Page statuses to include. Defaults to published only. \"Any\" includes every status except trash.",+ "Parent Page ID": "Parent Page ID",+ "Only direct children of this page ID. Use 0 for top-level pages.": "Only direct children of this page ID. Use 0 for top-level pages.",+ "Menu Order": "Menu Order",+ "Get Page": "Get Page",+ "Gets one site page by its ID.": "Gets one site page by its ID.",+ "Page ID": "Page ID",+ "ID of the page, from list_pages or search_site_content.": "ID of the page, from list_pages or search_site_content.",+ "Create Site Page": "Create Site Page",+ "Creates a static page. Saved as a draft unless a status is given.": "Creates a static page. Saved as a draft unless a status is given.",+ "The page title.": "The page title.",+ "The page body as HTML.": "The page body as HTML.",+ "Leave empty to save the page as a draft. \"Scheduled (future)\" needs a Publish Date.": "Leave empty to save the page as a draft. \"Scheduled (future)\" needs a Publish Date.",+ "Whether the page accepts pingbacks and trackbacks.": "Whether the page accepts pingbacks and trackbacks.",+ "ID of the parent page, from list_pages.": "ID of the parent page, from list_pages.",+ "Position of the page among its siblings.": "Position of the page among its siblings.",+ "Update Page": "Update Page",+ "Changes only the fields you supply on an existing page.": "Changes only the fields you supply on an existing page.",+ "ID of the page to update, from list_pages.": "ID of the page to update, from list_pages.",+ "The page title. Leave empty to keep the current value.": "The page title. Leave empty to keep the current value.",+ "The page body as HTML. Leave empty to keep the current value.": "The page body as HTML. Leave empty to keep the current value.",+ "New status. Leave empty to keep the current value. To trash the page, use the trash action instead.": "New status. Leave empty to keep the current value. To trash the page, use the trash action instead.",+ "Whether the page accepts pingbacks and trackbacks. Leave empty to keep the current value.": "Whether the page accepts pingbacks and trackbacks. Leave empty to keep the current value.",+ "ID of the parent page, from list_pages. Leave empty to keep the current value.": "ID of the parent page, from list_pages. Leave empty to keep the current value.",+ "Position of the page among its siblings. Leave empty to keep the current value.": "Position of the page among its siblings. Leave empty to keep the current value.",+ "Move Page to Trash": "Move Page to Trash",+ "Moves a page to the trash, where it can still be restored.": "Moves a page to the trash, where it can still be restored.",+ "ID of the page to trash, from list_pages.": "ID of the page to trash, from list_pages.",+ "List Categories": "List Categories",+ "Lists post categories, optionally filtered by name, parent or post.": "Lists post categories, optionally filtered by name, parent or post.",+ "Only categories whose name or slug contain this text.": "Only categories whose name or slug contain this text.",+ "Only the category with this exact slug.": "Only the category with this exact slug.",+ "Parent Category ID": "Parent Category ID",+ "Only direct children of this category ID. Use 0 for top-level categories.": "Only direct children of this category ID. Use 0 for top-level categories.",+ "Only categories assigned to this post ID (from list_posts).": "Only categories assigned to this post ID (from list_posts).",+ "Hide Empty": "Hide Empty",+ "Whether to leave out categories with no published posts. Defaults to No.": "Whether to leave out categories with no published posts. Defaults to No.",+ "Create Category": "Create Category",+ "Creates a post category, or returns the existing one with the same name.": "Creates a post category, or returns the existing one with the same name.",+ "Name": "Name",+ "Category name.": "Category name.",+ "Description": "Description",+ "Category description, used only when a new category is created.": "Category description, used only when a new category is created.",+ "URL slug. Leave empty to generate it from the name. Fails if another category already uses it.": "URL slug. Leave empty to generate it from the name. Fails if another category already uses it.",+ "ID of the parent category, from list_categories. Leave empty for a top-level category.": "ID of the parent category, from list_categories. Leave empty for a top-level category.",+ "Delete Category": "Delete Category",+ "Permanently deletes a post category. This cannot be undone.": "Permanently deletes a post category. This cannot be undone.",+ "Category ID": "Category ID",+ "ID of the category to delete, from list_categories.": "ID of the category to delete, from list_categories.",+ "List Tags": "List Tags",+ "Lists post tags, optionally filtered by name or post.": "Lists post tags, optionally filtered by name or post.",+ "Only tags whose name or slug contain this text.": "Only tags whose name or slug contain this text.",+ "Only the tag with this exact slug.": "Only the tag with this exact slug.",+ "Only tags assigned to this post ID (from list_posts).": "Only tags assigned to this post ID (from list_posts).",+ "Whether to leave out tags with no published posts. Defaults to No.": "Whether to leave out tags with no published posts. Defaults to No.",+ "Create Tag": "Create Tag",+ "Creates a post tag, or returns the existing one with the same name.": "Creates a post tag, or returns the existing one with the same name.",+ "Tag name.": "Tag name.",+ "Tag description, used only when a new tag is created.": "Tag description, used only when a new tag is created.",+ "URL slug. Leave empty to generate it from the name. Fails if another tag already uses it.": "URL slug. Leave empty to generate it from the name. Fails if another tag already uses it.",+ "Delete Tag": "Delete Tag",+ "Permanently deletes a post tag. This cannot be undone.": "Permanently deletes a post tag. This cannot be undone.",+ "Tag ID": "Tag ID",+ "ID of the tag to delete, from list_tags.": "ID of the tag to delete, from list_tags.",+ "List Comments": "List Comments",+ "Lists comments, optionally filtered by post, status, author or keyword.": "Lists comments, optionally filtered by post, status, author or keyword.",+ "Only comments on this post or page ID (from list_posts or list_pages).": "Only comments on this post or page ID (from list_posts or list_pages).",+ "Moderation status to list. Defaults to approved. Other statuses need a moderator (Editor or Administrator) connection.": "Moderation status to list. Defaults to approved. Other statuses need a moderator (Editor or Administrator) connection.",+ "Approved": "Approved",+ "Pending (held for moderation)": "Pending (held for moderation)",+ "Spam": "Spam",+ "Only comments containing this text.": "Only comments containing this text.",+ "Author User ID": "Author User ID",+ "Only comments written by this registered user ID (from list_users).": "Only comments written by this registered user ID (from list_users).",+ "Parent Comment ID": "Parent Comment ID",+ "Only replies to this comment ID. Use 0 for top-level comments.": "Only replies to this comment ID. Use 0 for top-level comments.",+ "Sort direction by date. Defaults to newest first.": "Sort direction by date. Defaults to newest first.",+ "Create Comment": "Create Comment",+ "Adds a comment, or a reply to a comment, on a published post or page.": "Adds a comment, or a reply to a comment, on a published post or page.",+ "ID of a published post or page with comments open, from list_posts or list_pages.": "ID of a published post or page with comments open, from list_posts or list_pages.",+ "Comment": "Comment",+ "Comment text. Basic HTML is allowed.": "Comment text. Basic HTML is allowed.",+ "Reply To Comment ID": "Reply To Comment ID",+ "ID of the comment to reply to, from list_comments. Leave empty for a top-level comment.": "ID of the comment to reply to, from list_comments. Leave empty for a top-level comment.",+ "Moderate Comment": "Moderate Comment",+ "Approves, holds, marks as spam, or trashes a comment, or reverses spam or trash.": "Approves, holds, marks as spam, or trashes a comment, or reverses spam or trash.",+ "Comment ID": "Comment ID",+ "ID of the comment, from list_comments.": "ID of the comment, from list_comments.",+ "Action": "Action",+ "The moderation action to apply.": "The moderation action to apply.",+ "Approve": "Approve",+ "Hold for moderation": "Hold for moderation",+ "Mark as spam": "Mark as spam",+ "Not spam": "Not spam",+ "Move to trash": "Move to trash",+ "Restore from trash": "Restore from trash",+ "Delete Comment Permanently": "Delete Comment Permanently",+ "Permanently deletes a comment, skipping the trash. This cannot be undone.": "Permanently deletes a comment, skipping the trash. This cannot be undone.",+ "ID of the comment to delete, from list_comments.": "ID of the comment to delete, from list_comments.",+ "List Media": "List Media",+ "Lists files in the media library, optionally filtered by keyword, type or attached post.": "Lists files in the media library, optionally filtered by keyword, type or attached post.",+ "Only files whose title, caption or file name contain this text.": "Only files whose title, caption or file name contain this text.",+ "Media Type": "Media Type",+ "Only files of this general type.": "Only files of this general type.",+ "Text": "Text",+ "Application (PDF, documents, archives)": "Application (PDF, documents, archives)",+ "MIME Type": "MIME Type",+ "Only files with this exact MIME type, e.g. image/png.": "Only files with this exact MIME type, e.g. image/png.",+ "Attached Post ID": "Attached Post ID",+ "Only files attached to this post or page ID. Use 0 for unattached files.": "Only files attached to this post or page ID. Use 0 for unattached files.",+ "Get Media": "Get Media",+ "Gets one media library file by its ID.": "Gets one media library file by its ID.",+ "Media ID": "Media ID",+ "ID of the media item, from list_media or upload_media.": "ID of the media item, from list_media or upload_media.",+ "Upload Media": "Upload Media",+ "Uploads a file to the media library, with optional title, alt text, caption and description.": "Uploads a file to the media library, with optional title, alt text, caption and description.",+ "File": "File",+ "The file to upload, as a URL or base64 data. The file name and extension decide its type.": "The file to upload, as a URL or base64 data. The file name and extension decide its type.",+ "Media title. Defaults to the file name.": "Media title. Defaults to the file name.",+ "Alt Text": "Alt Text",+ "Alternative text describing the image for screen readers.": "Alternative text describing the image for screen readers.",+ "Caption": "Caption",+ "Caption shown with the file.": "Caption shown with the file.",+ "Longer description of the file.": "Longer description of the file.",+ "Attach To Post ID": "Attach To Post ID",+ "ID of the post or page to attach the file to, from list_posts or list_pages.": "ID of the post or page to attach the file to, from list_posts or list_pages.",+ "Update Media Details": "Update Media Details",+ "Changes the title, alt text, caption, description or attached post of a media file.": "Changes the title, alt text, caption, description or attached post of a media file.",+ "New title. Leave empty to keep the current value.": "New title. Leave empty to keep the current value.",+ "New alternative text. Leave empty to keep the current value.": "New alternative text. Leave empty to keep the current value.",+ "New caption. Leave empty to keep the current value.": "New caption. Leave empty to keep the current value.",+ "New description. Leave empty to keep the current value.": "New description. Leave empty to keep the current value.",+ "ID of the post or page to attach the file to. Leave empty to keep the current value.": "ID of the post or page to attach the file to. Leave empty to keep the current value.",+ "Delete Media": "Delete Media",+ "Permanently deletes a media file and its generated sizes. This cannot be undone.": "Permanently deletes a media file and its generated sizes. This cannot be undone.",+ "ID of the media item to delete, from list_media.": "ID of the media item to delete, from list_media.",+ "Get Current User": "Get Current User",+ "Gets the WordPress user this connection signs in as, with roles and capabilities.": "Gets the WordPress user this connection signs in as, with roles and capabilities.",+ "List Users": "List Users",+ "Lists site users, optionally filtered by name or role.": "Lists site users, optionally filtered by name or role.",+ "Only users whose name, slug, email or URL contain this text.": "Only users whose name, slug, email or URL contain this text.",+ "Roles": "Roles",+ "Only users with any of these role slugs, e.g. administrator, editor, author, contributor, subscriber.": "Only users with any of these role slugs, e.g. administrator, editor, author, contributor, subscriber.",+ "Search Site Content": "Search Site Content",+ "Searches published posts and pages, or categories and tags, by keyword.": "Searches published posts and pages, or categories and tags, by keyword.",+ "Text to search for.": "Text to search for.",+ "Type": "Type",+ "What to search. Defaults to posts and pages.": "What to search. Defaults to posts and pages.",+ "Posts and pages": "Posts and pages",+ "Categories and tags": "Categories and tags",+ "Post formats": "Post formats",+ "Subtype": "Subtype",+ "Narrow the search within the chosen Type. \"Post\" and \"Page\" work only with Type \"Posts and pages\"; \"Category\" and \"Tag\" only with Type \"Categories and tags\". Leave empty for all.": "Narrow the search within the chosen Type. \"Post\" and \"Page\" work only with Type \"Posts and pages\"; \"Category\" and \"Tag\" only with Type \"Categories and tags\". Leave empty for all.",+ "Category": "Category",+ "Tag": "Tag",+ "Get Site Settings": "Get Site Settings",+ "Gets the site title, tagline, URL, timezone, date format and reading settings.": "Gets the site title, tagline, URL, timezone, date format and reading settings.",+ "Short summary of the page. Takes effect only when the theme or site supports page excerpts; WordPress silently ignores it otherwise.": "Short summary of the page. Takes effect only when the theme or site supports page excerpts; WordPress silently ignores it otherwise.",+ "Short summary of the page. Takes effect only when the theme or site supports page excerpts; WordPress silently ignores it otherwise. Leave empty to keep the current value.": "Short summary of the page. Takes effect only when the theme or site supports page excerpts; WordPress silently ignores it otherwise. Leave empty to keep the current value."+}diff --git a/packages/pieces/community/wordpress/src/index.ts b/packages/pieces/community/wordpress/src/index.tsindex 512bd6881c3..a0afab49a46 100644--- a/packages/pieces/community/wordpress/src/index.ts+++ b/packages/pieces/community/wordpress/src/index.ts@@ -17,6 +17,36 @@ import { getWordPressPost } from './lib/actions/get-post.action';import { wordpressCommon } from './lib/common';import { wordpressNewPost } from './lib/trigger/new-post.trigger';import { updateWordPressPost } from './lib/actions/update-post.action';+import { listPostsAction } from './lib/actions/list-posts.action';+import { getPostByIdAction } from './lib/actions/get-post-by-id.action';+import { createBlogPostAction } from './lib/actions/create-blog-post.action';+import { updateBlogPostAction } from './lib/actions/update-blog-post.action';+import { trashPostAction } from './lib/actions/trash-post.action';+import { deletePostPermanentlyAction } from './lib/actions/delete-post-permanently.action';+import { listPagesAction } from './lib/actions/list-pages.action';+import { getPageAction } from './lib/actions/get-page.action';+import { createSitePageAction } from './lib/actions/create-site-page.action';+import { updatePageAction } from './lib/actions/update-page.action';+import { trashPageAction } from './lib/actions/trash-page.action';+import { listCategoriesAction } from './lib/actions/list-categories.action';+import { createCategoryAction } from './lib/actions/create-category.action';+import { deleteCategoryAction } from './lib/actions/delete-category.action';+import { listTagsAction } from './lib/actions/list-tags.action';+import { createTagAction } from './lib/actions/create-tag.action';+import { deleteTagAction } from './lib/actions/delete-tag.action';+import { listCommentsAction } from './lib/actions/list-comments.action';+import { createCommentAction } from './lib/actions/create-comment.action';+import { moderateCommentAction } from './lib/actions/moderate-comment.action';+import { deleteCommentAction } from './lib/actions/delete-comment.action';+import { listMediaAction } from './lib/actions/list-media.action';+import { getMediaAction } from './lib/actions/get-media.action';+import { uploadMediaAction } from './lib/actions/upload-media.action';+import { updateMediaDetailsAction } from './lib/actions/update-media-details.action';+import { deleteMediaAction } from './lib/actions/delete-media.action';+import { getCurrentUserAction } from './lib/actions/get-current-user.action';+import { listUsersAction } from './lib/actions/list-users.action';+import { searchSiteContentAction } from './lib/actions/search-site-content.action';+import { getSiteSettingsAction } from './lib/actions/get-site-settings.action';const markdownPropertyDescription = `Connect with a WordPress **application password**:@@ -120,6 +150,36 @@ export const wordpress = createPiece({createWordPressPage,updateWordPressPost,getWordPressPost,+ listPostsAction,+ getPostByIdAction,+ createBlogPostAction,+ updateBlogPostAction,+ trashPostAction,+ deletePostPermanentlyAction,+ listPagesAction,+ getPageAction,+ createSitePageAction,+ updatePageAction,+ trashPageAction,+ listCategoriesAction,+ createCategoryAction,+ deleteCategoryAction,+ listTagsAction,+ createTagAction,+ deleteTagAction,+ listCommentsAction,+ createCommentAction,+ moderateCommentAction,+ deleteCommentAction,+ listMediaAction,+ getMediaAction,+ uploadMediaAction,+ updateMediaDetailsAction,+ deleteMediaAction,+ getCurrentUserAction,+ listUsersAction,+ searchSiteContentAction,+ getSiteSettingsAction,createCustomApiCallAction({baseUrl: (auth) =>auth ?(auth.props.website_url).trim() + '/wp-json/wp/v2' : '',diff --git a/packages/pieces/community/wordpress/src/lib/actions/create-blog-post.action.ts b/packages/pieces/community/wordpress/src/lib/actions/create-blog-post.action.tsnew file mode 100644index 00000000000..d803e7fd11c--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/create-blog-post.action.ts@@ -0,0 +1,36 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { postEditOutputSchema } from '../output-schemas';++export const createBlogPostAction = createAction({+ auth: wordpressAuth,+ name: 'create_blog_post',+ classification: 'WRITE',+ displayName: 'Create Blog Post',+ description: 'Creates a blog post. Saved as a draft unless a status is given.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a WordPress blog post from HTML content, optionally with categories, tags and a featured image. With no status the post is saved as a draft; set status "publish" to publish now, or "future" with a Publish Date to schedule (a past date publishes immediately). Custom ACF fields can be set by field name when the site exposes ACF over the REST API. Use create_site_page for static pages. Each call creates a new post, so retries duplicate.',+ idempotent: false,+ },+ outputSchema: postEditOutputSchema,+ props: {+ ...wordpressContent.contentProps({ kind: 'post', mode: 'create' }),+ ...wordpressContent.postOnlyProps({ mode: 'create' }),+ },+ async run({ auth, propsValue }) {+ wordpressContent.requireDateForFuture({ values: propsValue });+ const body = wordpressContent.buildContentBody({ kind: 'post', values: propsValue });+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.POST,+ path: '/posts',+ body,+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/create-category.action.ts b/packages/pieces/community/wordpress/src/lib/actions/create-category.action.tsnew file mode 100644index 00000000000..c13f12b1509--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/create-category.action.ts@@ -0,0 +1,58 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { wordpressAuth } from '../..';+import { wordpressApi } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { createCategoryOutputSchema } from '../output-schemas';++export const createCategoryAction = createAction({+ auth: wordpressAuth,+ name: 'create_category',+ classification: 'WRITE',+ displayName: 'Create Category',+ description: 'Creates a post category, or returns the existing one with the same name.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Gets or creates a WordPress post category by name. If a category with that name already exists under the same parent it is returned unchanged with created=false (its description is not updated); otherwise a new one is created with created=true. Use the returned ID in create_blog_post. Safe to retry.',+ idempotent: true,+ },+ outputSchema: createCategoryOutputSchema,+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Category name.',+ required: true,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'Category description, used only when a new category is created.',+ required: false,+ }),+ slug: Property.ShortText({+ displayName: 'Slug',+ description: 'URL slug. Leave empty to generate it from the name. Fails if another category already uses it.',+ required: false,+ }),+ parent: Property.Number({+ displayName: 'Parent Category ID',+ description: 'ID of the parent category, from list_categories. Leave empty for a top-level category.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const body: Record<string, unknown> = { name: propsValue.name };+ if (wordpressContent.isFilledText(propsValue.description)) {+ body['description'] = propsValue.description;+ }+ if (wordpressContent.isFilledText(propsValue.slug)) {+ body['slug'] = propsValue.slug;+ }+ if (wordpressContent.isSetNumber(propsValue.parent)) {+ body['parent'] = wordpressContent.requireWholeNumber({+ value: propsValue.parent,+ propName: 'Parent Category ID',+ });+ }+ return wordpressApi.getOrCreateTerm({ auth, taxonomy: 'categories', body });+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/create-comment.action.ts b/packages/pieces/community/wordpress/src/lib/actions/create-comment.action.tsnew file mode 100644index 00000000000..4e9780894dc--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/create-comment.action.ts@@ -0,0 +1,57 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { commentEditOutputSchema } from '../output-schemas';++export const createCommentAction = createAction({+ auth: wordpressAuth,+ name: 'create_comment',+ classification: 'WRITE',+ displayName: 'Create Comment',+ description: 'Adds a comment, or a reply to a comment, on a published post or page.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Posts a comment as the connected WordPress user on a published post or page, or replies to an existing comment. Fails if the post is not published or its comments are closed. Each call adds a new comment, so retries duplicate (WordPress rejects an exact duplicate).',+ idempotent: false,+ },+ outputSchema: commentEditOutputSchema,+ props: {+ post: Property.Number({+ displayName: 'Post ID',+ description: 'ID of a published post or page with comments open, from list_posts or list_pages.',+ required: true,+ }),+ content: Property.LongText({+ displayName: 'Comment',+ description: 'Comment text. Basic HTML is allowed.',+ required: true,+ }),+ parent: Property.Number({+ displayName: 'Reply To Comment ID',+ description: 'ID of the comment to reply to, from list_comments. Leave empty for a top-level comment.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const body: Record<string, unknown> = {+ post: wordpressContent.requireWholeNumber({ value: propsValue.post, propName: 'Post ID' }),+ content: propsValue.content,+ };+ if (wordpressContent.isSetNumber(propsValue.parent)) {+ body['parent'] = wordpressContent.requireWholeNumber({+ value: propsValue.parent,+ propName: 'Reply To Comment ID',+ });+ }+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.POST,+ path: '/comments',+ body,+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/create-page.action.ts b/packages/pieces/community/wordpress/src/lib/actions/create-page.action.tsindex c8a69adb6be..2c1074439d6 100644--- a/packages/pieces/community/wordpress/src/lib/actions/create-page.action.ts+++ b/packages/pieces/community/wordpress/src/lib/actions/create-page.action.ts@@ -14,7 +14,7 @@ export const createWordPressPage = createAction({name: 'create_page',classification: 'WRITE',description: 'Add a new page to your WordPress site',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Publishes a new static page (not a blog post) on a WordPress site via the REST API, with optional status, slug, excerpt, and comment settings. Choose this for standalone pages like About or Contact rather than dated posts. Requires a title and HTML content; not idempotent — each call creates a separate page.', idempotent: false },displayName: 'Create Page',outputSchema: createPageActionOutputSchema,diff --git a/packages/pieces/community/wordpress/src/lib/actions/create-post.action.ts b/packages/pieces/community/wordpress/src/lib/actions/create-post.action.tsindex 862fab239f1..e15ff1a59c6 100644--- a/packages/pieces/community/wordpress/src/lib/actions/create-post.action.ts+++ b/packages/pieces/community/wordpress/src/lib/actions/create-post.action.ts@@ -18,7 +18,7 @@ export const createWordPressPost = createAction({name: 'create_post',classification: 'WRITE',description: 'Add a new post to your WordPress site',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Publishes a new blog post on a WordPress site via the REST API, with optional status (draft/publish/etc.), categories, tags, excerpt, featured image, and custom ACF fields. Choose this to add fresh content; for editing an existing post use Update Post. Requires a title and HTML content; not idempotent — each call creates a separate post.', idempotent: false },displayName: 'Create Post',outputSchema: createPostActionOutputSchema,diff --git a/packages/pieces/community/wordpress/src/lib/actions/create-site-page.action.ts b/packages/pieces/community/wordpress/src/lib/actions/create-site-page.action.tsnew file mode 100644index 00000000000..208fee493a5--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/create-site-page.action.ts@@ -0,0 +1,36 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { pageEditOutputSchema } from '../output-schemas';++export const createSitePageAction = createAction({+ auth: wordpressAuth,+ name: 'create_site_page',+ classification: 'WRITE',+ displayName: 'Create Site Page',+ description: 'Creates a static page. Saved as a draft unless a status is given.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Creates a WordPress static page (About, Contact and similar) from HTML content, optionally under a parent page. With no status the page is saved as a draft; set status "publish" to publish now. Use create_blog_post for dated blog posts. Each call creates a new page, so retries duplicate.',+ idempotent: false,+ },+ outputSchema: pageEditOutputSchema,+ props: {+ ...wordpressContent.contentProps({ kind: 'page', mode: 'create' }),+ ...wordpressContent.pageOnlyProps({ mode: 'create' }),+ },+ async run({ auth, propsValue }) {+ wordpressContent.requireDateForFuture({ values: propsValue });+ const body = wordpressContent.buildContentBody({ kind: 'page', values: propsValue });+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.POST,+ path: '/pages',+ body,+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/create-tag.action.ts b/packages/pieces/community/wordpress/src/lib/actions/create-tag.action.tsnew file mode 100644index 00000000000..836e2ba0234--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/create-tag.action.ts@@ -0,0 +1,47 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { wordpressAuth } from '../..';+import { wordpressApi } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { createTagOutputSchema } from '../output-schemas';++export const createTagAction = createAction({+ auth: wordpressAuth,+ name: 'create_tag',+ classification: 'WRITE',+ displayName: 'Create Tag',+ description: 'Creates a post tag, or returns the existing one with the same name.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Gets or creates a WordPress post tag by name. If a tag with that name already exists it is returned unchanged with created=false; otherwise a new one is created with created=true. Use the returned ID in create_blog_post. Safe to retry.',+ idempotent: true,+ },+ outputSchema: createTagOutputSchema,+ props: {+ name: Property.ShortText({+ displayName: 'Name',+ description: 'Tag name.',+ required: true,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'Tag description, used only when a new tag is created.',+ required: false,+ }),+ slug: Property.ShortText({+ displayName: 'Slug',+ description: 'URL slug. Leave empty to generate it from the name. Fails if another tag already uses it.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const body: Record<string, unknown> = { name: propsValue.name };+ if (wordpressContent.isFilledText(propsValue.description)) {+ body['description'] = propsValue.description;+ }+ if (wordpressContent.isFilledText(propsValue.slug)) {+ body['slug'] = propsValue.slug;+ }+ return wordpressApi.getOrCreateTerm({ auth, taxonomy: 'tags', body });+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/delete-category.action.ts b/packages/pieces/community/wordpress/src/lib/actions/delete-category.action.tsnew file mode 100644index 00000000000..46a690afcf8--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/delete-category.action.ts@@ -0,0 +1,31 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { wordpressAuth } from '../..';+import { wordpressApi } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { deleteCategoryOutputSchema } from '../output-schemas';++export const deleteCategoryAction = createAction({+ auth: wordpressAuth,+ name: 'delete_category',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Category',+ description: 'Permanently deletes a post category. This cannot be undone.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a WordPress category; categories have no trash. Posts in it keep their other categories, and posts left with none move to the default category. The site\'s default category (usually "Uncategorized") cannot be deleted and returns a 403. A repeat call fails because the category no longer exists.',+ idempotent: false,+ },+ outputSchema: deleteCategoryOutputSchema,+ props: {+ category_id: Property.Number({+ displayName: 'Category ID',+ description: 'ID of the category to delete, from list_categories.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = wordpressContent.requireWholeNumber({ value: propsValue.category_id, propName: 'Category ID' });+ return wordpressApi.forceDelete({ auth, path: `/categories/${id}` });+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/delete-comment.action.ts b/packages/pieces/community/wordpress/src/lib/actions/delete-comment.action.tsnew file mode 100644index 00000000000..5b6ce7658eb--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/delete-comment.action.ts@@ -0,0 +1,31 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { wordpressAuth } from '../..';+import { wordpressApi } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { deleteCommentOutputSchema } from '../output-schemas';++export const deleteCommentAction = createAction({+ auth: wordpressAuth,+ name: 'delete_comment',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Comment Permanently',+ description: 'Permanently deletes a comment, skipping the trash. This cannot be undone.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a WordPress comment, bypassing the trash; it cannot be restored. Use moderate_comment with "trash" or "spam" when the comment may need to come back. A repeat call fails because the comment no longer exists.',+ idempotent: false,+ },+ outputSchema: deleteCommentOutputSchema,+ props: {+ comment_id: Property.Number({+ displayName: 'Comment ID',+ description: 'ID of the comment to delete, from list_comments.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = wordpressContent.requireWholeNumber({ value: propsValue.comment_id, propName: 'Comment ID' });+ return wordpressApi.forceDelete({ auth, path: `/comments/${id}` });+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/delete-media.action.ts b/packages/pieces/community/wordpress/src/lib/actions/delete-media.action.tsnew file mode 100644index 00000000000..bb4913bd184--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/delete-media.action.ts@@ -0,0 +1,31 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { wordpressAuth } from '../..';+import { wordpressApi } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { deleteMediaOutputSchema } from '../output-schemas';++export const deleteMediaAction = createAction({+ auth: wordpressAuth,+ name: 'delete_media',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Media',+ description: 'Permanently deletes a media file and its generated sizes. This cannot be undone.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a WordPress media item and removes its files from the server; media has no trash by default, so there is no recoverable alternative. Posts that used it as a featured image or embedded it will show a missing image. A repeat call fails because the item no longer exists.',+ idempotent: false,+ },+ outputSchema: deleteMediaOutputSchema,+ props: {+ media_id: Property.Number({+ displayName: 'Media ID',+ description: 'ID of the media item to delete, from list_media.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = wordpressContent.requireWholeNumber({ value: propsValue.media_id, propName: 'Media ID' });+ return wordpressApi.forceDelete({ auth, path: `/media/${id}` });+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/delete-post-permanently.action.ts b/packages/pieces/community/wordpress/src/lib/actions/delete-post-permanently.action.tsnew file mode 100644index 00000000000..45681d4c01a--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/delete-post-permanently.action.ts@@ -0,0 +1,31 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { wordpressAuth } from '../..';+import { wordpressApi } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { deletePostOutputSchema } from '../output-schemas';++export const deletePostPermanentlyAction = createAction({+ auth: wordpressAuth,+ name: 'delete_post_permanently',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Post Permanently',+ description: 'Permanently deletes a blog post, skipping the trash. This cannot be undone.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a WordPress blog post in any status, bypassing the trash; it cannot be restored. Use trash_post instead when the post may need to come back. Returns the deleted post; a repeat call fails because the post no longer exists.',+ idempotent: false,+ },+ outputSchema: deletePostOutputSchema,+ props: {+ post_id: Property.Number({+ displayName: 'Post ID',+ description: 'ID of the post to delete, from list_posts.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = wordpressContent.requireWholeNumber({ value: propsValue.post_id, propName: 'Post ID' });+ return wordpressApi.forceDelete({ auth, path: `/posts/${id}` });+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/delete-tag.action.ts b/packages/pieces/community/wordpress/src/lib/actions/delete-tag.action.tsnew file mode 100644index 00000000000..a2d03e3d81c--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/delete-tag.action.ts@@ -0,0 +1,31 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { wordpressAuth } from '../..';+import { wordpressApi } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { deleteTagOutputSchema } from '../output-schemas';++export const deleteTagAction = createAction({+ auth: wordpressAuth,+ name: 'delete_tag',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Tag',+ description: 'Permanently deletes a post tag. This cannot be undone.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently deletes a WordPress tag and removes it from every post; tags have no trash. To take a tag off one post only, use update_blog_post with the new tag list. A repeat call fails because the tag no longer exists.',+ idempotent: false,+ },+ outputSchema: deleteTagOutputSchema,+ props: {+ tag_id: Property.Number({+ displayName: 'Tag ID',+ description: 'ID of the tag to delete, from list_tags.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = wordpressContent.requireWholeNumber({ value: propsValue.tag_id, propName: 'Tag ID' });+ return wordpressApi.forceDelete({ auth, path: `/tags/${id}` });+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/get-current-user.action.ts b/packages/pieces/community/wordpress/src/lib/actions/get-current-user.action.tsnew file mode 100644index 00000000000..732dd59f750--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/get-current-user.action.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { getCurrentUserOutputSchema } from '../output-schemas';++export const getCurrentUserAction = createAction({+ auth: wordpressAuth,+ name: 'get_current_user',+ classification: 'READ',+ displayName: 'Get Current User',+ description: 'Gets the WordPress user this connection signs in as, with roles and capabilities.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the WordPress user the connection authenticates as: ID, name, email, roles and capabilities. Use it to check that the connection works and whether the role allows a write (for example edit_pages, moderate_comments, manage_categories) before attempting it. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: getCurrentUserOutputSchema,+ props: {},+ async run({ auth }) {+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.GET,+ path: '/users/me',+ queryParams: { context: 'edit' },+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/get-media.action.ts b/packages/pieces/community/wordpress/src/lib/actions/get-media.action.tsnew file mode 100644index 00000000000..68715486eed--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/get-media.action.ts@@ -0,0 +1,37 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { getMediaOutputSchema } from '../output-schemas';++export const getMediaAction = createAction({+ auth: wordpressAuth,+ name: 'get_media',+ classification: 'READ',+ displayName: 'Get Media',+ description: 'Gets one media library file by its ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one WordPress media library item by ID, with its file URL, MIME type, alt text, caption and image sizes. Get the ID from list_media or upload_media. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: getMediaOutputSchema,+ props: {+ media_id: Property.Number({+ displayName: 'Media ID',+ description: 'ID of the media item, from list_media or upload_media.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = wordpressContent.requireWholeNumber({ value: propsValue.media_id, propName: 'Media ID' });+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.GET,+ path: `/media/${id}`,+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/get-page.action.ts b/packages/pieces/community/wordpress/src/lib/actions/get-page.action.tsnew file mode 100644index 00000000000..210c6c84a1d--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/get-page.action.ts@@ -0,0 +1,37 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { getPageOutputSchema } from '../output-schemas';++export const getPageAction = createAction({+ auth: wordpressAuth,+ name: 'get_page',+ classification: 'READ',+ displayName: 'Get Page',+ description: 'Gets one site page by its ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one WordPress static page by ID, including drafts the connected user can edit. Get the ID from list_pages or search_site_content; use get_post_by_id for blog posts. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: getPageOutputSchema,+ props: {+ page_id: Property.Number({+ displayName: 'Page ID',+ description: 'ID of the page, from list_pages or search_site_content.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const pageId = wordpressContent.requireWholeNumber({ value: propsValue.page_id, propName: 'Page ID' });+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.GET,+ path: `/pages/${pageId}`,+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/get-post-by-id.action.ts b/packages/pieces/community/wordpress/src/lib/actions/get-post-by-id.action.tsnew file mode 100644index 00000000000..06794921a2e--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/get-post-by-id.action.ts@@ -0,0 +1,37 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { getPostByIdOutputSchema } from '../output-schemas';++export const getPostByIdAction = createAction({+ auth: wordpressAuth,+ name: 'get_post_by_id',+ classification: 'READ',+ displayName: 'Get Post by ID',+ description: 'Gets one blog post by its ID.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns one WordPress blog post by ID, including drafts and private posts the connected user can edit. Get the ID from list_posts or search_site_content; use get_page for pages. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: getPostByIdOutputSchema,+ props: {+ post_id: Property.Number({+ displayName: 'Post ID',+ description: 'ID of the post, from list_posts or search_site_content.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const postId = wordpressContent.requireWholeNumber({ value: propsValue.post_id, propName: 'Post ID' });+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.GET,+ path: `/posts/${postId}`,+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/get-post.action.ts b/packages/pieces/community/wordpress/src/lib/actions/get-post.action.tsindex 6afe953a934..dfffef9510f 100644--- a/packages/pieces/community/wordpress/src/lib/actions/get-post.action.ts+++ b/packages/pieces/community/wordpress/src/lib/actions/get-post.action.ts@@ -18,7 +18,7 @@ export const getWordPressPost = createAction({name: 'get_post',classification: 'READ',description: 'Fetch one post by its ID',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Fetches a single WordPress post by its numeric post ID via the REST API. Use it to read the current content, status, or metadata of a known post before acting on it. Requires the post ID; read-only and idempotent.', idempotent: true },displayName: 'Get Post Details',outputSchema: getPostActionOutputSchema,diff --git a/packages/pieces/community/wordpress/src/lib/actions/get-site-settings.action.ts b/packages/pieces/community/wordpress/src/lib/actions/get-site-settings.action.tsnew file mode 100644index 00000000000..9600ac0ad69--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/get-site-settings.action.ts@@ -0,0 +1,29 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { getSiteSettingsOutputSchema } from '../output-schemas';++export const getSiteSettingsAction = createAction({+ auth: wordpressAuth,+ name: 'get_site_settings',+ classification: 'READ',+ displayName: 'Get Site Settings',+ description: 'Gets the site title, tagline, URL, timezone, date format and reading settings.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Returns the WordPress site settings: title, tagline, URL, admin email, timezone, date and time formats, default category and post format, and front-page setup. Use it to learn the site timezone before scheduling a post, or the default category ID. Needs an Administrator connection. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: getSiteSettingsOutputSchema,+ props: {},+ async run({ auth }) {+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.GET,+ path: '/settings',+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/list-categories.action.ts b/packages/pieces/community/wordpress/src/lib/actions/list-categories.action.tsnew file mode 100644index 00000000000..d012a7bbdbd--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/list-categories.action.ts@@ -0,0 +1,82 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { QueryParams } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { listCategoriesOutputSchema } from '../output-schemas';++export const listCategoriesAction = createAction({+ auth: wordpressAuth,+ name: 'list_categories',+ classification: 'SEARCH',+ displayName: 'List Categories',+ description: 'Lists post categories, optionally filtered by name, parent or post.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists WordPress post categories with their IDs, names, slugs, parents and post counts. Use it to turn a category name into the ID that create_blog_post, update_blog_post and list_posts need; use create_category to add a missing one. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: listCategoriesOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Only categories whose name or slug contain this text.',+ required: false,+ }),+ slug: Property.ShortText({+ displayName: 'Slug',+ description: 'Only the category with this exact slug.',+ required: false,+ }),+ parent: Property.Number({+ displayName: 'Parent Category ID',+ description: 'Only direct children of this category ID. Use 0 for top-level categories.',+ required: false,+ }),+ post: Property.Number({+ displayName: 'Post ID',+ description: 'Only categories assigned to this post ID (from list_posts).',+ required: false,+ }),+ hide_empty: Property.StaticDropdown({+ displayName: 'Hide Empty',+ description: 'Whether to leave out categories with no published posts. Defaults to No.',+ required: false,+ options: wordpressContent.trueFalseOptions,+ }),+ ...wordpressContent.pagingProps(),+ },+ async run({ auth, propsValue }) {+ const queryParams: QueryParams = wordpressContent.buildPaging({+ perPage: propsValue.per_page,+ page: propsValue.page,+ });+ if (wordpressContent.isFilledText(propsValue.search)) {+ queryParams['search'] = propsValue.search;+ }+ if (wordpressContent.isFilledText(propsValue.slug)) {+ queryParams['slug'] = propsValue.slug;+ }+ if (wordpressContent.isSetNumber(propsValue.parent)) {+ queryParams['parent'] = String(+ wordpressContent.requireWholeNumber({ value: propsValue.parent, propName: 'Parent Category ID' })+ );+ }+ if (wordpressContent.isSetNumber(propsValue.post)) {+ queryParams['post'] = String(+ wordpressContent.requireWholeNumber({ value: propsValue.post, propName: 'Post ID' })+ );+ }+ if (wordpressContent.isFilledText(propsValue.hide_empty)) {+ queryParams['hide_empty'] = propsValue.hide_empty;+ }+ const result = await wordpressApi.list<WordpressRecord>({ auth, path: '/categories', queryParams });+ return {+ categories: result.items,+ count: result.items.length,+ total: result.total,+ total_pages: result.total_pages,+ };+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/list-comments.action.ts b/packages/pieces/community/wordpress/src/lib/actions/list-comments.action.tsnew file mode 100644index 00000000000..e958d2dfdbf--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/list-comments.action.ts@@ -0,0 +1,101 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { QueryParams } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { listCommentsOutputSchema } from '../output-schemas';++export const listCommentsAction = createAction({+ auth: wordpressAuth,+ name: 'list_comments',+ classification: 'SEARCH',+ displayName: 'List Comments',+ description: 'Lists comments, optionally filtered by post, status, author or keyword.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists WordPress comments filtered by post, moderation status, author or keyword. Defaults to approved comments; pick status "hold" to find comments awaiting moderation for moderate_comment. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: listCommentsOutputSchema,+ props: {+ post: Property.Number({+ displayName: 'Post ID',+ description: 'Only comments on this post or page ID (from list_posts or list_pages).',+ required: false,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description: 'Moderation status to list. Defaults to approved. Other statuses need a moderator (Editor or Administrator) connection.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Approved', value: 'approve' },+ { label: 'Pending (held for moderation)', value: 'hold' },+ { label: 'Spam', value: 'spam' },+ { label: 'Trash', value: 'trash' },+ ],+ },+ }),+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Only comments containing this text.',+ required: false,+ }),+ author: Property.Number({+ displayName: 'Author User ID',+ description: 'Only comments written by this registered user ID (from list_users).',+ required: false,+ }),+ parent: Property.Number({+ displayName: 'Parent Comment ID',+ description: 'Only replies to this comment ID. Use 0 for top-level comments.',+ required: false,+ }),+ order: Property.StaticDropdown({+ displayName: 'Order',+ description: 'Sort direction by date. Defaults to newest first.',+ required: false,+ options: wordpressContent.orderOptions,+ }),+ ...wordpressContent.pagingProps(),+ },+ async run({ auth, propsValue }) {+ const queryParams: QueryParams = wordpressContent.buildPaging({+ perPage: propsValue.per_page,+ page: propsValue.page,+ });+ if (wordpressContent.isSetNumber(propsValue.post)) {+ queryParams['post'] = String(+ wordpressContent.requireWholeNumber({ value: propsValue.post, propName: 'Post ID' })+ );+ }+ if (wordpressContent.isFilledText(propsValue.status)) {+ queryParams['status'] = propsValue.status;+ }+ if (wordpressContent.isFilledText(propsValue.search)) {+ queryParams['search'] = propsValue.search;+ }+ if (wordpressContent.isSetNumber(propsValue.author)) {+ queryParams['author'] = String(+ wordpressContent.requireWholeNumber({ value: propsValue.author, propName: 'Author User ID' })+ );+ }+ if (wordpressContent.isSetNumber(propsValue.parent)) {+ queryParams['parent'] = String(+ wordpressContent.requireWholeNumber({ value: propsValue.parent, propName: 'Parent Comment ID' })+ );+ }+ if (wordpressContent.isFilledText(propsValue.order)) {+ queryParams['order'] = propsValue.order;+ }+ const result = await wordpressApi.list<WordpressRecord>({ auth, path: '/comments', queryParams });+ return {+ comments: result.items,+ count: result.items.length,+ total: result.total,+ total_pages: result.total_pages,+ };+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/list-media.action.ts b/packages/pieces/community/wordpress/src/lib/actions/list-media.action.tsnew file mode 100644index 00000000000..54b71457321--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/list-media.action.ts@@ -0,0 +1,81 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { QueryParams } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { listMediaOutputSchema } from '../output-schemas';++export const listMediaAction = createAction({+ auth: wordpressAuth,+ name: 'list_media',+ classification: 'SEARCH',+ displayName: 'List Media',+ description: 'Lists files in the media library, optionally filtered by keyword, type or attached post.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists files in the WordPress media library with their IDs, URLs, MIME types and sizes, filtered by keyword, media type, MIME type or the post they are attached to. Use it to find a media ID for featured_media in create_blog_post, or for get_media and update_media_details. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: listMediaOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Only files whose title, caption or file name contain this text.',+ required: false,+ }),+ media_type: Property.StaticDropdown({+ displayName: 'Media Type',+ description: 'Only files of this general type.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Image', value: 'image' },+ { label: 'Video', value: 'video' },+ { label: 'Audio', value: 'audio' },+ { label: 'Text', value: 'text' },+ { label: 'Application (PDF, documents, archives)', value: 'application' },+ ],+ },+ }),+ mime_type: Property.ShortText({+ displayName: 'MIME Type',+ description: 'Only files with this exact MIME type, e.g. image/png.',+ required: false,+ }),+ parent: Property.Number({+ displayName: 'Attached Post ID',+ description: 'Only files attached to this post or page ID. Use 0 for unattached files.',+ required: false,+ }),+ ...wordpressContent.pagingProps(),+ },+ async run({ auth, propsValue }) {+ const queryParams: QueryParams = wordpressContent.buildPaging({+ perPage: propsValue.per_page,+ page: propsValue.page,+ });+ if (wordpressContent.isFilledText(propsValue.search)) {+ queryParams['search'] = propsValue.search;+ }+ if (wordpressContent.isFilledText(propsValue.media_type)) {+ queryParams['media_type'] = propsValue.media_type;+ }+ if (wordpressContent.isFilledText(propsValue.mime_type)) {+ queryParams['mime_type'] = propsValue.mime_type;+ }+ if (wordpressContent.isSetNumber(propsValue.parent)) {+ queryParams['parent'] = String(+ wordpressContent.requireWholeNumber({ value: propsValue.parent, propName: 'Attached Post ID' })+ );+ }+ const result = await wordpressApi.list<WordpressRecord>({ auth, path: '/media', queryParams });+ return {+ media: result.items,+ count: result.items.length,+ total: result.total,+ total_pages: result.total_pages,+ };+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/list-pages.action.ts b/packages/pieces/community/wordpress/src/lib/actions/list-pages.action.tsnew file mode 100644index 00000000000..5a48e124d71--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/list-pages.action.ts@@ -0,0 +1,107 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { QueryParams } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { listPagesOutputSchema } from '../output-schemas';++export const listPagesAction = createAction({+ auth: wordpressAuth,+ name: 'list_pages',+ classification: 'SEARCH',+ displayName: 'List Pages',+ description: 'Lists site pages, optionally filtered by keyword, status or parent page.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists WordPress static pages with full page fields, filtered by keyword, status or parent page. Use it to find page IDs for get_page, update_page or trash_page; use list_posts for blog posts. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: listPagesOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Only pages whose title or content contain this text.',+ required: false,+ }),+ status: Property.StaticMultiSelectDropdown({+ displayName: 'Status',+ description: 'Page statuses to include. Defaults to published only. "Any" includes every status except trash.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Published', value: 'publish' },+ { label: 'Draft', value: 'draft' },+ { label: 'Pending Review', value: 'pending' },+ { label: 'Private', value: 'private' },+ { label: 'Scheduled', value: 'future' },+ { label: 'Trash', value: 'trash' },+ { label: 'Any', value: 'any' },+ ],+ },+ }),+ parent: Property.Number({+ displayName: 'Parent Page ID',+ description: 'Only direct children of this page ID. Use 0 for top-level pages.',+ required: false,+ }),+ orderby: Property.StaticDropdown({+ displayName: 'Order By',+ description: 'Sort field. Defaults to date. "Relevance" needs Search.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Date', value: 'date' },+ { label: 'Modified Date', value: 'modified' },+ { label: 'Title', value: 'title' },+ { label: 'ID', value: 'id' },+ { label: 'Slug', value: 'slug' },+ { label: 'Menu Order', value: 'menu_order' },+ { label: 'Relevance', value: 'relevance' },+ ],+ },+ }),+ order: Property.StaticDropdown({+ displayName: 'Order',+ description: 'Sort direction. Defaults to descending.',+ required: false,+ options: wordpressContent.orderOptions,+ }),+ ...wordpressContent.pagingProps(),+ },+ async run({ auth, propsValue }) {+ const queryParams: QueryParams = wordpressContent.buildPaging({+ perPage: propsValue.per_page,+ page: propsValue.page,+ });+ if (wordpressContent.isFilledText(propsValue.search)) {+ queryParams['search'] = propsValue.search;+ }+ if (propsValue.orderby === 'relevance' && queryParams['search'] === undefined) {+ throw new Error('Order By "Relevance" needs a Search value.');+ }+ if (propsValue.status && propsValue.status.length > 0) {+ queryParams['status'] = propsValue.status.join(',');+ }+ if (wordpressContent.isSetNumber(propsValue.parent)) {+ queryParams['parent'] = String(+ wordpressContent.requireWholeNumber({ value: propsValue.parent, propName: 'Parent Page ID' })+ );+ }+ if (wordpressContent.isFilledText(propsValue.orderby)) {+ queryParams['orderby'] = propsValue.orderby;+ }+ if (wordpressContent.isFilledText(propsValue.order)) {+ queryParams['order'] = propsValue.order;+ }+ const result = await wordpressApi.list<WordpressRecord>({ auth, path: '/pages', queryParams });+ return {+ pages: result.items,+ count: result.items.length,+ total: result.total,+ total_pages: result.total_pages,+ };+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/list-posts.action.ts b/packages/pieces/community/wordpress/src/lib/actions/list-posts.action.tsnew file mode 100644index 00000000000..f2fa8a26737--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/list-posts.action.ts@@ -0,0 +1,140 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { QueryParams } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { listPostsOutputSchema } from '../output-schemas';++export const listPostsAction = createAction({+ auth: wordpressAuth,+ name: 'list_posts',+ classification: 'SEARCH',+ displayName: 'List Posts',+ description: 'Lists blog posts, optionally filtered by keyword, status, category, tag, author or date.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists WordPress blog posts with full post fields, filtered by keyword, status, category IDs, tag IDs, author or date range. Use it to find post IDs for get_post_by_id, update_blog_post or trash_post; use search_site_content for a quick keyword lookup across posts and pages together. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: listPostsOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Only posts whose title, content or excerpt contain this text.',+ required: false,+ }),+ status: Property.StaticMultiSelectDropdown({+ displayName: 'Status',+ description: 'Post statuses to include. Defaults to published only. "Any" includes every status except trash.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Published', value: 'publish' },+ { label: 'Draft', value: 'draft' },+ { label: 'Pending Review', value: 'pending' },+ { label: 'Private', value: 'private' },+ { label: 'Scheduled', value: 'future' },+ { label: 'Trash', value: 'trash' },+ { label: 'Any', value: 'any' },+ ],+ },+ }),+ categories: Property.Array({+ displayName: 'Category IDs',+ description: 'Only posts in any of these category IDs (from list_categories).',+ required: false,+ }),+ tags: Property.Array({+ displayName: 'Tag IDs',+ description: 'Only posts with any of these tag IDs (from list_tags).',+ required: false,+ }),+ author: Property.Number({+ displayName: 'Author ID',+ description: 'Only posts by this user ID (from list_users).',+ required: false,+ }),+ after: Property.ShortText({+ displayName: 'Published After',+ description: 'Only posts published after this ISO 8601 date, e.g. 2026-01-31T00:00:00.',+ required: false,+ }),+ before: Property.ShortText({+ displayName: 'Published Before',+ description: 'Only posts published before this ISO 8601 date.',+ required: false,+ }),+ orderby: Property.StaticDropdown({+ displayName: 'Order By',+ description: 'Sort field. Defaults to date. "Relevance" needs Search.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Date', value: 'date' },+ { label: 'Modified Date', value: 'modified' },+ { label: 'Title', value: 'title' },+ { label: 'ID', value: 'id' },+ { label: 'Slug', value: 'slug' },+ { label: 'Relevance', value: 'relevance' },+ ],+ },+ }),+ order: Property.StaticDropdown({+ displayName: 'Order',+ description: 'Sort direction. Defaults to descending.',+ required: false,+ options: wordpressContent.orderOptions,+ }),+ ...wordpressContent.pagingProps(),+ },+ async run({ auth, propsValue }) {+ const queryParams: QueryParams = wordpressContent.buildPaging({+ perPage: propsValue.per_page,+ page: propsValue.page,+ });+ if (wordpressContent.isFilledText(propsValue.search)) {+ queryParams['search'] = propsValue.search;+ }+ if (propsValue.orderby === 'relevance' && queryParams['search'] === undefined) {+ throw new Error('Order By "Relevance" needs a Search value.');+ }+ if (propsValue.status && propsValue.status.length > 0) {+ queryParams['status'] = propsValue.status.join(',');+ }+ const categories = wordpressContent.parseIdList({ values: propsValue.categories, propName: 'Category IDs' });+ if (categories) {+ queryParams['categories'] = categories.join(',');+ }+ const tags = wordpressContent.parseIdList({ values: propsValue.tags, propName: 'Tag IDs' });+ if (tags) {+ queryParams['tags'] = tags.join(',');+ }+ if (wordpressContent.isSetNumber(propsValue.author)) {+ queryParams['author'] = String(+ wordpressContent.requireWholeNumber({ value: propsValue.author, propName: 'Author ID' })+ );+ }+ if (wordpressContent.isFilledText(propsValue.after)) {+ queryParams['after'] = propsValue.after;+ }+ if (wordpressContent.isFilledText(propsValue.before)) {+ queryParams['before'] = propsValue.before;+ }+ if (wordpressContent.isFilledText(propsValue.orderby)) {+ queryParams['orderby'] = propsValue.orderby;+ }+ if (wordpressContent.isFilledText(propsValue.order)) {+ queryParams['order'] = propsValue.order;+ }+ const result = await wordpressApi.list<WordpressRecord>({ auth, path: '/posts', queryParams });+ return {+ posts: result.items,+ count: result.items.length,+ total: result.total,+ total_pages: result.total_pages,+ };+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/list-tags.action.ts b/packages/pieces/community/wordpress/src/lib/actions/list-tags.action.tsnew file mode 100644index 00000000000..6fd7b466434--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/list-tags.action.ts@@ -0,0 +1,72 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { QueryParams } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { listTagsOutputSchema } from '../output-schemas';++export const listTagsAction = createAction({+ auth: wordpressAuth,+ name: 'list_tags',+ classification: 'SEARCH',+ displayName: 'List Tags',+ description: 'Lists post tags, optionally filtered by name or post.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists WordPress post tags with their IDs, names, slugs and post counts. Use it to turn a tag name into the ID that create_blog_post, update_blog_post and list_posts need; use create_tag to add a missing one. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: listTagsOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Only tags whose name or slug contain this text.',+ required: false,+ }),+ slug: Property.ShortText({+ displayName: 'Slug',+ description: 'Only the tag with this exact slug.',+ required: false,+ }),+ post: Property.Number({+ displayName: 'Post ID',+ description: 'Only tags assigned to this post ID (from list_posts).',+ required: false,+ }),+ hide_empty: Property.StaticDropdown({+ displayName: 'Hide Empty',+ description: 'Whether to leave out tags with no published posts. Defaults to No.',+ required: false,+ options: wordpressContent.trueFalseOptions,+ }),+ ...wordpressContent.pagingProps(),+ },+ async run({ auth, propsValue }) {+ const queryParams: QueryParams = wordpressContent.buildPaging({+ perPage: propsValue.per_page,+ page: propsValue.page,+ });+ if (wordpressContent.isFilledText(propsValue.search)) {+ queryParams['search'] = propsValue.search;+ }+ if (wordpressContent.isFilledText(propsValue.slug)) {+ queryParams['slug'] = propsValue.slug;+ }+ if (wordpressContent.isSetNumber(propsValue.post)) {+ queryParams['post'] = String(+ wordpressContent.requireWholeNumber({ value: propsValue.post, propName: 'Post ID' })+ );+ }+ if (wordpressContent.isFilledText(propsValue.hide_empty)) {+ queryParams['hide_empty'] = propsValue.hide_empty;+ }+ const result = await wordpressApi.list<WordpressRecord>({ auth, path: '/tags', queryParams });+ return {+ tags: result.items,+ count: result.items.length,+ total: result.total,+ total_pages: result.total_pages,+ };+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/list-users.action.ts b/packages/pieces/community/wordpress/src/lib/actions/list-users.action.tsnew file mode 100644index 00000000000..5abfeab6560--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/list-users.action.ts@@ -0,0 +1,54 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { QueryParams } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { listUsersOutputSchema } from '../output-schemas';++export const listUsersAction = createAction({+ auth: wordpressAuth,+ name: 'list_users',+ classification: 'SEARCH',+ displayName: 'List Users',+ description: 'Lists site users, optionally filtered by name or role.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Lists WordPress users with their IDs, display names and slugs, filtered by keyword or role. Use it to find an author ID for create_blog_post or list_posts; use get_current_user for the connected account. Without the list_users capability (Administrator) only users with published posts are returned and role filtering fails. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: listUsersOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Only users whose name, slug, email or URL contain this text.',+ required: false,+ }),+ roles: Property.Array({+ displayName: 'Roles',+ description: 'Only users with any of these role slugs, e.g. administrator, editor, author, contributor, subscriber.',+ required: false,+ }),+ ...wordpressContent.pagingProps(),+ },+ async run({ auth, propsValue }) {+ const queryParams: QueryParams = wordpressContent.buildPaging({+ perPage: propsValue.per_page,+ page: propsValue.page,+ });+ if (wordpressContent.isFilledText(propsValue.search)) {+ queryParams['search'] = propsValue.search;+ }+ const roles = wordpressContent.parseStringList({ values: propsValue.roles });+ if (roles) {+ queryParams['roles'] = roles.join(',');+ }+ const result = await wordpressApi.list<WordpressRecord>({ auth, path: '/users', queryParams });+ return {+ users: result.items,+ count: result.items.length,+ total: result.total,+ total_pages: result.total_pages,+ };+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/moderate-comment.action.ts b/packages/pieces/community/wordpress/src/lib/actions/moderate-comment.action.tsnew file mode 100644index 00000000000..83b9bce1530--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/moderate-comment.action.ts@@ -0,0 +1,90 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressApiError, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { commentEditOutputSchema } from '../output-schemas';++function isInTargetState({+ target,+ current,+}: {+ target: string;+ current: unknown;+}): boolean {+ switch (target) {+ case 'approve':+ return current === 'approved';+ case 'unspam':+ return current !== 'spam';+ case 'untrash':+ return current !== 'trash';+ default:+ return current === target;+ }+}++export const moderateCommentAction = createAction({+ auth: wordpressAuth,+ name: 'moderate_comment',+ classification: 'WRITE',+ displayName: 'Moderate Comment',+ description: 'Approves, holds, marks as spam, or trashes a comment, or reverses spam or trash.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Sets the moderation status of a WordPress comment: approve, hold for review, spam, trash, or reverse spam/trash. Trash is recoverable; use delete_comment only to remove a comment for good. Setting the status a comment already has returns the comment unchanged, so it is safe to retry. Needs a moderator (Editor or Administrator) connection.',+ idempotent: true,+ },+ outputSchema: commentEditOutputSchema,+ props: {+ comment_id: Property.Number({+ displayName: 'Comment ID',+ description: 'ID of the comment, from list_comments.',+ required: true,+ }),+ status: Property.StaticDropdown({+ displayName: 'Action',+ description: 'The moderation action to apply.',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Approve', value: 'approve' },+ { label: 'Hold for moderation', value: 'hold' },+ { label: 'Mark as spam', value: 'spam' },+ { label: 'Not spam', value: 'unspam' },+ { label: 'Move to trash', value: 'trash' },+ { label: 'Restore from trash', value: 'untrash' },+ ],+ },+ }),+ },+ async run({ auth, propsValue }) {+ const id = wordpressContent.requireWholeNumber({ value: propsValue.comment_id, propName: 'Comment ID' });+ const target = propsValue.status;+ try {+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.POST,+ path: `/comments/${id}`,+ body: { status: target },+ });+ return response.body;+ } catch (error) {+ if (!(error instanceof WordpressApiError) || error.code !== 'rest_comment_failed_edit') {+ throw error;+ }+ const current = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.GET,+ path: `/comments/${id}`,+ queryParams: { context: 'edit' },+ });+ if (isInTargetState({ target, current: current.body['status'] })) {+ return current.body;+ }+ throw error;+ }+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/search-site-content.action.ts b/packages/pieces/community/wordpress/src/lib/actions/search-site-content.action.tsnew file mode 100644index 00000000000..362bc73dc96--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/search-site-content.action.ts@@ -0,0 +1,87 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { QueryParams } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { searchSiteContentOutputSchema } from '../output-schemas';++const subtypesByType: Record<string, string[]> = {+ post: ['post', 'page'],+ term: ['category', 'post_tag'],+ 'post-format': [],+};++export const searchSiteContentAction = createAction({+ auth: wordpressAuth,+ name: 'search_site_content',+ classification: 'SEARCH',+ displayName: 'Search Site Content',+ description: 'Searches published posts and pages, or categories and tags, by keyword.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Keyword search across the WordPress site, returning only ID, title, URL and type for each match. By default it searches published posts and pages together; set Type to "term" to search categories and tags. Use list_posts or list_pages instead when you need drafts, full fields or filters. Read-only and safe to retry.',+ idempotent: true,+ },+ outputSchema: searchSiteContentOutputSchema,+ props: {+ search: Property.ShortText({+ displayName: 'Search',+ description: 'Text to search for.',+ required: true,+ }),+ type: Property.StaticDropdown({+ displayName: 'Type',+ description: 'What to search. Defaults to posts and pages.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Posts and pages', value: 'post' },+ { label: 'Categories and tags', value: 'term' },+ { label: 'Post formats', value: 'post-format' },+ ],+ },+ }),+ subtype: Property.StaticDropdown({+ displayName: 'Subtype',+ description:+ 'Narrow the search within the chosen Type. "Post" and "Page" work only with Type "Posts and pages"; "Category" and "Tag" only with Type "Categories and tags". Leave empty for all.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Post', value: 'post' },+ { label: 'Page', value: 'page' },+ { label: 'Category', value: 'category' },+ { label: 'Tag', value: 'post_tag' },+ ],+ },+ }),+ ...wordpressContent.pagingProps(),+ },+ async run({ auth, propsValue }) {+ const type = wordpressContent.isFilledText(propsValue.type) ? propsValue.type : 'post';+ const queryParams: QueryParams = {+ ...wordpressContent.buildPaging({ perPage: propsValue.per_page, page: propsValue.page }),+ search: propsValue.search,+ type,+ };+ if (wordpressContent.isFilledText(propsValue.subtype)) {+ const allowed = subtypesByType[type] ?? [];+ if (!allowed.includes(propsValue.subtype)) {+ throw new Error(+ `Subtype "${propsValue.subtype}" does not belong to Type "${type}". Allowed: ${allowed.length > 0 ? allowed.join(', ') : 'none (leave Subtype empty)'}.`+ );+ }+ queryParams['subtype'] = propsValue.subtype;+ }+ const result = await wordpressApi.list<WordpressRecord>({ auth, path: '/search', queryParams });+ return {+ results: result.items,+ count: result.items.length,+ total: result.total,+ total_pages: result.total_pages,+ };+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/trash-page.action.ts b/packages/pieces/community/wordpress/src/lib/actions/trash-page.action.tsnew file mode 100644index 00000000000..a4176654856--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/trash-page.action.ts@@ -0,0 +1,31 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { wordpressAuth } from '../..';+import { wordpressApi } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { pageEditOutputSchema } from '../output-schemas';++export const trashPageAction = createAction({+ auth: wordpressAuth,+ name: 'trash_page',+ classification: 'DESTRUCTIVE',+ displayName: 'Move Page to Trash',+ description: 'Moves a page to the trash, where it can still be restored.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Moves a WordPress static page to the trash; it can be restored from the WordPress admin until the trash is emptied. Child pages are not trashed. Calling it on a page that is already trashed returns the page unchanged, so it is safe to retry.',+ idempotent: true,+ },+ outputSchema: pageEditOutputSchema,+ props: {+ page_id: Property.Number({+ displayName: 'Page ID',+ description: 'ID of the page to trash, from list_pages.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = wordpressContent.requireWholeNumber({ value: propsValue.page_id, propName: 'Page ID' });+ return wordpressApi.trashItem({ auth, collection: 'pages', id });+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/trash-post.action.ts b/packages/pieces/community/wordpress/src/lib/actions/trash-post.action.tsnew file mode 100644index 00000000000..72551d17d8c--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/trash-post.action.ts@@ -0,0 +1,31 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { wordpressAuth } from '../..';+import { wordpressApi } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { postEditOutputSchema } from '../output-schemas';++export const trashPostAction = createAction({+ auth: wordpressAuth,+ name: 'trash_post',+ classification: 'DESTRUCTIVE',+ displayName: 'Move Post to Trash',+ description: 'Moves a blog post to the trash, where it can still be restored.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Moves a WordPress blog post to the trash; it can be restored from the WordPress admin until the trash is emptied. Prefer this over delete_post_permanently unless the post must be gone for good. Calling it on a post that is already trashed returns the post unchanged, so it is safe to retry.',+ idempotent: true,+ },+ outputSchema: postEditOutputSchema,+ props: {+ post_id: Property.Number({+ displayName: 'Post ID',+ description: 'ID of the post to trash, from list_posts.',+ required: true,+ }),+ },+ async run({ auth, propsValue }) {+ const id = wordpressContent.requireWholeNumber({ value: propsValue.post_id, propName: 'Post ID' });+ return wordpressApi.trashItem({ auth, collection: 'posts', id });+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/update-blog-post.action.ts b/packages/pieces/community/wordpress/src/lib/actions/update-blog-post.action.tsnew file mode 100644index 00000000000..ae22a69b848--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/update-blog-post.action.ts@@ -0,0 +1,42 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { postEditOutputSchema } from '../output-schemas';++export const updateBlogPostAction = createAction({+ auth: wordpressAuth,+ name: 'update_blog_post',+ classification: 'WRITE',+ displayName: 'Update Blog Post',+ description: 'Changes only the fields you supply on an existing blog post.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing WordPress blog post by ID, sending only the fields you supply; everything else stays as it is. Category IDs and Tag IDs replace the current set. Also sets comments or pingbacks open or closed, and writes only the custom ACF fields you supply. To trash a post use trash_post. Safe to retry with the same input.',+ idempotent: true,+ },+ outputSchema: postEditOutputSchema,+ props: {+ post_id: Property.Number({+ displayName: 'Post ID',+ description: 'ID of the post to update, from list_posts.',+ required: true,+ }),+ ...wordpressContent.contentProps({ kind: 'post', mode: 'update' }),+ ...wordpressContent.postOnlyProps({ mode: 'update' }),+ },+ async run({ auth, propsValue }) {+ const postId = wordpressContent.requireWholeNumber({ value: propsValue.post_id, propName: 'Post ID' });+ const body = wordpressContent.buildContentBody({ kind: 'post', values: propsValue });+ wordpressContent.requirePatch({ body });+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.POST,+ path: `/posts/${postId}`,+ body,+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/update-media-details.action.ts b/packages/pieces/community/wordpress/src/lib/actions/update-media-details.action.tsnew file mode 100644index 00000000000..6b6e9292570--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/update-media-details.action.ts@@ -0,0 +1,65 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { mediaEditOutputSchema } from '../output-schemas';++export const updateMediaDetailsAction = createAction({+ auth: wordpressAuth,+ name: 'update_media_details',+ classification: 'WRITE',+ displayName: 'Update Media Details',+ description: 'Changes the title, alt text, caption, description or attached post of a media file.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates the details of an existing WordPress media item by ID, sending only the fields you supply; the file itself is not replaced. Use it to add alt text or a caption after upload_media. Safe to retry with the same input.',+ idempotent: true,+ },+ outputSchema: mediaEditOutputSchema,+ props: {+ media_id: Property.Number({+ displayName: 'Media ID',+ description: 'ID of the media item, from list_media or upload_media.',+ required: true,+ }),+ title: Property.ShortText({+ displayName: 'Title',+ description: 'New title. Leave empty to keep the current value.',+ required: false,+ }),+ alt_text: Property.ShortText({+ displayName: 'Alt Text',+ description: 'New alternative text. Leave empty to keep the current value.',+ required: false,+ }),+ caption: Property.LongText({+ displayName: 'Caption',+ description: 'New caption. Leave empty to keep the current value.',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'New description. Leave empty to keep the current value.',+ required: false,+ }),+ post: Property.Number({+ displayName: 'Attach To Post ID',+ description: 'ID of the post or page to attach the file to. Leave empty to keep the current value.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const id = wordpressContent.requireWholeNumber({ value: propsValue.media_id, propName: 'Media ID' });+ const body = wordpressContent.buildMediaDetailsBody({ values: propsValue });+ wordpressContent.requirePatch({ body });+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.POST,+ path: `/media/${id}`,+ body,+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/update-page.action.ts b/packages/pieces/community/wordpress/src/lib/actions/update-page.action.tsnew file mode 100644index 00000000000..c767a9b1f86--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/update-page.action.ts@@ -0,0 +1,42 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { pageEditOutputSchema } from '../output-schemas';++export const updatePageAction = createAction({+ auth: wordpressAuth,+ name: 'update_page',+ classification: 'WRITE',+ displayName: 'Update Page',+ description: 'Changes only the fields you supply on an existing page.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Updates an existing WordPress static page by ID, sending only the fields you supply; everything else stays as it is. To trash a page use trash_page; use update_blog_post for blog posts. Safe to retry with the same input.',+ idempotent: true,+ },+ outputSchema: pageEditOutputSchema,+ props: {+ page_id: Property.Number({+ displayName: 'Page ID',+ description: 'ID of the page to update, from list_pages.',+ required: true,+ }),+ ...wordpressContent.contentProps({ kind: 'page', mode: 'update' }),+ ...wordpressContent.pageOnlyProps({ mode: 'update' }),+ },+ async run({ auth, propsValue }) {+ const pageId = wordpressContent.requireWholeNumber({ value: propsValue.page_id, propName: 'Page ID' });+ const body = wordpressContent.buildContentBody({ kind: 'page', values: propsValue });+ wordpressContent.requirePatch({ body });+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.POST,+ path: `/pages/${pageId}`,+ body,+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/actions/update-post.action.ts b/packages/pieces/community/wordpress/src/lib/actions/update-post.action.tsindex b5203a7c231..d4b4e9fcc3b 100644--- a/packages/pieces/community/wordpress/src/lib/actions/update-post.action.ts+++ b/packages/pieces/community/wordpress/src/lib/actions/update-post.action.ts@@ -14,7 +14,7 @@ export const updateWordPressPost = createAction({name: 'update_post',classification: 'WRITE',description: 'Change the title, content or settings of an existing post',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Updates an existing WordPress post identified by its post ID, changing only the fields you supply (title, content, status, categories, tags, excerpt, featured image, or ACF fields). Choose this to edit or republish a known post rather than create a new one. Requires the target post ID; idempotent — repeating with the same input leaves the post in the same final state.', idempotent: true },displayName: 'Update Post',outputSchema: updatePostActionOutputSchema,diff --git a/packages/pieces/community/wordpress/src/lib/actions/upload-media.action.ts b/packages/pieces/community/wordpress/src/lib/actions/upload-media.action.tsnew file mode 100644index 00000000000..9acb29a52cc--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/actions/upload-media.action.ts@@ -0,0 +1,69 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import FormData from 'form-data';+import { wordpressAuth } from '../..';+import { wordpressApi, WordpressRecord } from '../common/client';+import { wordpressContent } from '../common/content-body';+import { mediaEditOutputSchema } from '../output-schemas';++export const uploadMediaAction = createAction({+ auth: wordpressAuth,+ name: 'upload_media',+ classification: 'WRITE',+ displayName: 'Upload Media',+ description: 'Uploads a file to the media library, with optional title, alt text, caption and description.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Uploads a file (image, PDF, video and so on) to the WordPress media library in one request, optionally setting its title, alt text, caption, description and the post it is attached to. Returns the media ID and public URL; pass the ID as featured_media to create_blog_post. Each call uploads a new copy, so retries duplicate. The site limits allowed file types and size.',+ idempotent: false,+ },+ outputSchema: mediaEditOutputSchema,+ props: {+ file: Property.File({+ displayName: 'File',+ description: 'The file to upload, as a URL or base64 data. The file name and extension decide its type.',+ required: true,+ }),+ title: Property.ShortText({+ displayName: 'Title',+ description: 'Media title. Defaults to the file name.',+ required: false,+ }),+ alt_text: Property.ShortText({+ displayName: 'Alt Text',+ description: 'Alternative text describing the image for screen readers.',+ required: false,+ }),+ caption: Property.LongText({+ displayName: 'Caption',+ description: 'Caption shown with the file.',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'Longer description of the file.',+ required: false,+ }),+ post: Property.Number({+ displayName: 'Attach To Post ID',+ description: 'ID of the post or page to attach the file to, from list_posts or list_pages.',+ required: false,+ }),+ },+ async run({ auth, propsValue }) {+ const form = new FormData();+ form.append('file', propsValue.file.data, { filename: propsValue.file.filename });+ const fields = wordpressContent.buildMediaDetailsBody({ values: propsValue });+ for (const [key, value] of Object.entries(fields)) {+ form.append(key, String(value));+ }+ const response = await wordpressApi.request<WordpressRecord>({+ auth,+ method: HttpMethod.POST,+ path: '/media',+ body: form,+ });+ return response.body;+ },+});diff --git a/packages/pieces/community/wordpress/src/lib/common/client.ts b/packages/pieces/community/wordpress/src/lib/common/client.tsnew file mode 100644index 00000000000..8de976a7433--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/common/client.ts@@ -0,0 +1,308 @@+import {+ AuthenticationType,+ httpClient,+ HttpError,+ HttpMethod,+ HttpResponse,+ QueryParams,+} from '@activepieces/pieces-common';+import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';+import { wordpressAuth } from '../..';++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function readErrorBody(body: unknown): {+ code: string;+ message: string;+ data: Record<string, unknown>;+} {+ if (isRecord(body)) {+ return {+ code: typeof body['code'] === 'string' ? body['code'] : 'unknown_error',+ message:+ typeof body['message'] === 'string' ? body['message'] : JSON.stringify(body),+ data: isRecord(body['data']) ? body['data'] : {},+ };+ }+ return {+ code: 'non_json_response',+ message: typeof body === 'string' ? body.slice(0, 200) : String(body),+ data: {},+ };+}++function unreachableMessage({ url }: { url: string }): string {+ return `WordPress did not return REST API JSON from ${url}. The REST API is not reachable at /wp-json: set Settings > Permalinks to any option other than "Plain", check the Website URL, and check that no security plugin blocks the REST API.`;+}++function describeError({+ status,+ code,+ message,+ data,+ path,+}: {+ status: number;+ code: string;+ message: string;+ data: Record<string, unknown>;+ path: string;+}): string {+ const suffix = ` [HTTP ${status}, code ${code}]`;+ switch (code) {+ case 'rest_no_route':+ return `The WordPress REST route ${path} was not found. Set Settings > Permalinks to any option other than "Plain" and check that no security plugin blocks /wp-json.${suffix}`;+ case 'rest_post_invalid_page_number':+ return `The requested page is past the last page of results. Use a lower page number; list outputs report total_pages.${suffix}`;+ case 'rest_already_trashed':+ return `The item is already in the trash.${suffix}`;+ case 'rest_trash_not_supported':+ case 'rest_trash_not_implemented':+ return `This item cannot be moved to the trash on this site. Use the permanent delete action instead.${suffix}`;+ case 'rest_comment_closed':+ return `Comments are closed on this post.${suffix}`;+ case 'rest_comment_draft_post':+ return `Comments can only be added to a published post.${suffix}`;+ case 'rest_comment_failed_edit':+ return `WordPress could not change the comment status.${suffix}`;+ case 'duplicate_term_slug':+ return `Another term already uses this slug. Use a different slug or omit it.${suffix}`;+ case 'term_exists':+ return `A term with this name already exists under the same parent (term ID ${String(data['term_id'])}).${suffix}`;+ }+ if (status === 401) {+ return `WordPress rejected the credentials: ${message} Check the username and use an Application Password (Users > Profile > Application Passwords).${suffix}`;+ }+ if (status === 403) {+ return `The connected WordPress user's role is not allowed to do this: ${message}${suffix}`;+ }+ if (status === 404) {+ return `WordPress could not find the requested item: ${message} Check the ID.${suffix}`;+ }+ if (status === 429) {+ return `The WordPress host is rate limiting requests. Wait and retry.${suffix}`;+ }+ const params = isRecord(data['params']) ? ` ${JSON.stringify(data['params'])}` : '';+ return `WordPress returned an error: ${message}${params}${suffix}`;+}++function siteBaseUrl({ auth }: { auth: WordpressAuthValue }): string {+ return `${auth.props.website_url.trim().replace(/\/+$/, '')}/wp-json/wp/v2`;+}++async function request<T>({+ auth,+ method,+ path,+ queryParams,+ body,+}: WordpressRequestParams): Promise<HttpResponse<T>> {+ const url = `${siteBaseUrl({ auth })}${path}`;+ try {+ const response = await httpClient.sendRequest<T>({+ method,+ url,+ queryParams,+ body,+ authentication: {+ type: AuthenticationType.BASIC,+ username: auth.props.username,+ password: auth.props.password,+ },+ });+ if (typeof response.body === 'string' || response.body === undefined) {+ throw new WordpressApiError({+ status: response.status,+ code: 'non_json_response',+ data: {},+ message: `${unreachableMessage({ url })} [HTTP ${response.status}, code non_json_response]`,+ });+ }+ return response;+ } catch (error) {+ if (error instanceof HttpError) {+ const status = error.response.status;+ const { code, message, data } = readErrorBody(error.response.body);+ throw new WordpressApiError({+ status,+ code,+ data,+ message:+ code === 'non_json_response'+ ? `${unreachableMessage({ url })} [HTTP ${status}, code ${code}]`+ : describeError({ status, code, message, data, path }),+ });+ }+ throw error;+ }+}++function readCountHeader({+ headers,+ name,+}: {+ headers: HttpResponse['headers'];+ name: string;+}): number | undefined {+ const raw = headers?.[name];+ const value = Array.isArray(raw) ? raw[0] : raw;+ if (value === undefined || value === '') {+ return undefined;+ }+ const parsed = Number(value);+ return Number.isFinite(parsed) ? parsed : undefined;+}++async function list<T>({+ auth,+ path,+ queryParams,+}: {+ auth: WordpressAuthValue;+ path: string;+ queryParams: QueryParams;+}): Promise<WordpressListResult<T>> {+ const response = await request<T[]>({+ auth,+ method: HttpMethod.GET,+ path,+ queryParams,+ });+ const items = Array.isArray(response.body) ? response.body : [];+ return {+ items,+ total: readCountHeader({ headers: response.headers, name: 'x-wp-total' }),+ total_pages: readCountHeader({+ headers: response.headers,+ name: 'x-wp-totalpages',+ }),+ };+}++async function trashItem({+ auth,+ collection,+ id,+}: {+ auth: WordpressAuthValue;+ collection: 'posts' | 'pages';+ id: number;+}): Promise<WordpressRecord> {+ try {+ const response = await request<WordpressRecord>({+ auth,+ method: HttpMethod.DELETE,+ path: `/${collection}/${id}`,+ });+ return response.body;+ } catch (error) {+ if (error instanceof WordpressApiError && error.code === 'rest_already_trashed') {+ const current = await request<WordpressRecord>({+ auth,+ method: HttpMethod.GET,+ path: `/${collection}/${id}`,+ queryParams: { context: 'edit' },+ });+ return current.body;+ }+ throw error;+ }+}++async function getOrCreateTerm({+ auth,+ taxonomy,+ body,+}: {+ auth: WordpressAuthValue;+ taxonomy: 'categories' | 'tags';+ body: Record<string, unknown>;+}): Promise<WordpressRecord> {+ try {+ const response = await request<WordpressRecord>({+ auth,+ method: HttpMethod.POST,+ path: `/${taxonomy}`,+ body,+ });+ return { ...response.body, created: true };+ } catch (error) {+ if (error instanceof WordpressApiError && error.code === 'term_exists') {+ const termId = error.data['term_id'];+ if (typeof termId !== 'number' && typeof termId !== 'string') {+ throw error;+ }+ const existing = await request<WordpressRecord>({+ auth,+ method: HttpMethod.GET,+ path: `/${taxonomy}/${termId}`,+ });+ return { ...existing.body, created: false };+ }+ throw error;+ }+}++async function forceDelete({+ auth,+ path,+}: {+ auth: WordpressAuthValue;+ path: string;+}): Promise<WordpressRecord> {+ const response = await request<WordpressRecord>({+ auth,+ method: HttpMethod.DELETE,+ path,+ queryParams: { force: 'true' },+ });+ return response.body;+}++export class WordpressApiError extends Error {+ public readonly status: number;+ public readonly code: string;+ public readonly data: Record<string, unknown>;++ constructor({+ status,+ code,+ data,+ message,+ }: {+ status: number;+ code: string;+ data: Record<string, unknown>;+ message: string;+ }) {+ super(message);+ this.name = 'WordpressApiError';+ this.status = status;+ this.code = code;+ this.data = data;+ }+}++export const wordpressApi = { request, list, trashItem, getOrCreateTerm, forceDelete };++export type WordpressAuthValue = AppConnectionValueForAuthProperty<+ typeof wordpressAuth+>;++export type WordpressRequestParams = {+ auth: WordpressAuthValue;+ method: HttpMethod;+ path: string;+ queryParams?: QueryParams;+ body?: unknown;+};++export type WordpressListResult<T> = {+ items: T[];+ total: number | undefined;+ total_pages: number | undefined;+};++export type WordpressRecord = Record<string, unknown>;diff --git a/packages/pieces/community/wordpress/src/lib/common/content-body.ts b/packages/pieces/community/wordpress/src/lib/common/content-body.tsnew file mode 100644index 00000000000..f856909730a--- /dev/null+++ b/packages/pieces/community/wordpress/src/lib/common/content-body.ts@@ -0,0 +1,437 @@+import { QueryParams } from '@activepieces/pieces-common';+import { Property } from '@activepieces/pieces-framework';++function isFilledText(value: string | null | undefined): value is string {+ return typeof value === 'string' && value.trim() !== '';+}++function isSetNumber(value: number | null | undefined): value is number {+ return typeof value === 'number' && Number.isFinite(value);+}++function requireWholeNumber({+ value,+ propName,+}: {+ value: number;+ propName: string;+}): number {+ if (!Number.isInteger(value) || value < 0) {+ throw new Error(`${propName} must be a whole-number ID; got "${value}".`);+ }+ return value;+}++function parseIdList({+ values,+ propName,+}: {+ values: unknown[] | null | undefined;+ propName: string;+}): number[] | undefined {+ if (!Array.isArray(values) || values.length === 0) {+ return undefined;+ }+ return values.map((item) => {+ const parsed = typeof item === 'string' ? Number(item.trim()) : item;+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed <= 0) {+ throw new Error(+ `${propName} must contain whole-number IDs only; got "${String(item)}".`+ );+ }+ return parsed;+ });+}++function parseStringList({+ values,+}: {+ values: unknown[] | null | undefined;+}): string[] | undefined {+ if (!Array.isArray(values)) {+ return undefined;+ }+ const items = values+ .map((item) => String(item).trim())+ .filter((item) => item !== '');+ return items.length > 0 ? items : undefined;+}++function buildPaging({+ perPage,+ page,+}: {+ perPage: number | null | undefined;+ page: number | null | undefined;+}): QueryParams {+ const resolvedPerPage = isSetNumber(perPage) ? perPage : 10;+ const resolvedPage = isSetNumber(page) ? page : 1;+ if (+ !Number.isInteger(resolvedPerPage) ||+ resolvedPerPage < 1 ||+ resolvedPerPage > 100+ ) {+ throw new Error(+ `Results Per Page must be a whole number from 1 to 100; got "${resolvedPerPage}".`+ );+ }+ if (!Number.isInteger(resolvedPage) || resolvedPage < 1) {+ throw new Error(+ `Page must be a whole number of 1 or more; got "${resolvedPage}".`+ );+ }+ return { per_page: String(resolvedPerPage), page: String(resolvedPage) };+}++function addText({+ target,+ key,+ value,+}: {+ target: Record<string, unknown>;+ key: string;+ value: string | null | undefined;+}): void {+ if (isFilledText(value)) {+ target[key] = value;+ }+}++function addNumber({+ target,+ key,+ value,+ propName,+}: {+ target: Record<string, unknown>;+ key: string;+ value: number | null | undefined;+ propName: string;+}): void {+ if (isSetNumber(value)) {+ target[key] = requireWholeNumber({ value, propName });+ }+}++function buildContentBody({+ kind,+ values,+}: {+ kind: 'post' | 'page';+ values: ContentValues;+}): Record<string, unknown> {+ const body: Record<string, unknown> = {};+ addText({ target: body, key: 'title', value: values.title });+ addText({ target: body, key: 'content', value: values.content });+ addText({ target: body, key: 'status', value: values.status });+ addText({ target: body, key: 'date', value: values.date });+ addText({ target: body, key: 'slug', value: values.slug });+ addText({ target: body, key: 'comment_status', value: values.comment_status });+ addText({ target: body, key: 'ping_status', value: values.ping_status });+ addNumber({+ target: body,+ key: 'featured_media',+ value: values.featured_media,+ propName: 'Featured Media ID',+ });+ addNumber({ target: body, key: 'author', value: values.author, propName: 'Author ID' });+ addText({ target: body, key: 'excerpt', value: values.excerpt });+ if (kind === 'post') {+ addText({ target: body, key: 'format', value: values.format });+ if (values.sticky === 'true' || values.sticky === 'false') {+ body['sticky'] = values.sticky === 'true';+ }+ const categories = parseIdList({ values: values.categories, propName: 'Category IDs' });+ if (categories) {+ body['categories'] = categories;+ }+ const tags = parseIdList({ values: values.tags, propName: 'Tag IDs' });+ if (tags) {+ body['tags'] = tags;+ }+ if (values.acf && Object.keys(values.acf).length > 0) {+ body['acf'] = values.acf;+ }+ }+ if (kind === 'page') {+ addNumber({ target: body, key: 'parent', value: values.parent, propName: 'Parent Page ID' });+ if (isSetNumber(values.menu_order)) {+ if (!Number.isInteger(values.menu_order)) {+ throw new Error(`Menu Order must be a whole number; got "${values.menu_order}".`);+ }+ body['menu_order'] = values.menu_order;+ }+ }+ return body;+}++function requireDateForFuture({ values }: { values: ContentValues }): void {+ if (values.status === 'future' && !isFilledText(values.date)) {+ throw new Error(+ 'Status "future" needs a Publish Date in the future (ISO 8601, e.g. 2030-01-31T09:00:00).'+ );+ }+}++function buildMediaDetailsBody({+ values,+}: {+ values: MediaDetailsValues;+}): Record<string, unknown> {+ const body: Record<string, unknown> = {};+ addText({ target: body, key: 'title', value: values.title });+ addText({ target: body, key: 'alt_text', value: values.alt_text });+ addText({ target: body, key: 'caption', value: values.caption });+ addText({ target: body, key: 'description', value: values.description });+ addNumber({ target: body, key: 'post', value: values.post, propName: 'Attached Post ID' });+ return body;+}++function requirePatch({ body }: { body: Record<string, unknown> }): void {+ if (Object.keys(body).length === 0) {+ throw new Error(+ 'Nothing to update: supply at least one field to change. Empty text fields are treated as "leave unchanged".'+ );+ }+}++const openClosedOptions = {+ disabled: false,+ options: [+ { label: 'Open', value: 'open' },+ { label: 'Closed', value: 'closed' },+ ],+};++const trueFalseOptions = {+ disabled: false,+ options: [+ { label: 'Yes', value: 'true' },+ { label: 'No', value: 'false' },+ ],+};++const contentStatusOptions = {+ disabled: false,+ options: [+ { label: 'Publish', value: 'publish' },+ { label: 'Draft', value: 'draft' },+ { label: 'Pending Review', value: 'pending' },+ { label: 'Private', value: 'private' },+ { label: 'Scheduled (future)', value: 'future' },+ ],+};++const postFormatOptions = {+ disabled: false,+ options: [+ { label: 'Standard', value: 'standard' },+ { label: 'Aside', value: 'aside' },+ { label: 'Chat', value: 'chat' },+ { label: 'Gallery', value: 'gallery' },+ { label: 'Link', value: 'link' },+ { label: 'Image', value: 'image' },+ { label: 'Quote', value: 'quote' },+ { label: 'Status', value: 'status' },+ { label: 'Video', value: 'video' },+ { label: 'Audio', value: 'audio' },+ ],+};++const orderOptions = {+ disabled: false,+ options: [+ { label: 'Descending', value: 'desc' },+ { label: 'Ascending', value: 'asc' },+ ],+};++function contentProps({+ kind,+ mode,+}: {+ kind: 'post' | 'page';+ mode: 'create' | 'update';+}) {+ const required = mode === 'create';+ const noun = kind === 'post' ? 'post' : 'page';+ const unchanged = mode === 'update' ? ' Leave empty to keep the current value.' : '';+ return {+ title: Property.ShortText({+ displayName: 'Title',+ description: `The ${noun} title.${unchanged}`,+ required,+ }),+ content: Property.LongText({+ displayName: 'Content',+ description: `The ${noun} body as HTML.${unchanged}`,+ required,+ }),+ status: Property.StaticDropdown({+ displayName: 'Status',+ description:+ mode === 'create'+ ? `Leave empty to save the ${noun} as a draft. "Scheduled (future)" needs a Publish Date.`+ : `New status.${unchanged} To trash the ${noun}, use the trash action instead.`,+ required: false,+ options: contentStatusOptions,+ }),+ date: Property.ShortText({+ displayName: 'Publish Date',+ description: `Publish date in the site's timezone, ISO 8601 (e.g. 2030-01-31T09:00:00). A past date with status "future" publishes immediately.${unchanged}`,+ required: false,+ }),+ slug: Property.ShortText({+ displayName: 'Slug',+ description: `URL slug.${unchanged}`,+ required: false,+ }),+ featured_media: Property.Number({+ displayName: 'Featured Media ID',+ description: `ID of an uploaded image to use as the featured image. Get it from upload_media or list_media.${unchanged}`,+ required: false,+ }),+ author: Property.Number({+ displayName: 'Author ID',+ description: `User ID of the author. Get it from list_users or get_current_user. Leave empty for the connected user.`,+ required: false,+ }),+ comment_status: Property.StaticDropdown({+ displayName: 'Comments',+ description: `Whether visitors can comment.${unchanged}`,+ required: false,+ options: openClosedOptions,+ }),+ ping_status: Property.StaticDropdown({+ displayName: 'Pingbacks',+ description: `Whether the ${noun} accepts pingbacks and trackbacks.${unchanged}`,+ required: false,+ options: openClosedOptions,+ }),+ };+}++function postOnlyProps({ mode }: { mode: 'create' | 'update' }) {+ const unchanged = mode === 'update' ? ' Leave empty to keep the current value.' : '';+ const replaces = mode === 'update' ? ' The list replaces the post\'s current set.' : '';+ return {+ excerpt: Property.LongText({+ displayName: 'Excerpt',+ description: `Short summary of the post.${unchanged}`,+ required: false,+ }),+ categories: Property.Array({+ displayName: 'Category IDs',+ description: `Category IDs from list_categories or create_category.${replaces}${unchanged}`,+ required: false,+ }),+ tags: Property.Array({+ displayName: 'Tag IDs',+ description: `Tag IDs from list_tags or create_tag.${replaces}${unchanged}`,+ required: false,+ }),+ sticky: Property.StaticDropdown({+ displayName: 'Sticky',+ description: `Whether the post is pinned to the top of the blog.${unchanged}`,+ required: false,+ options: trueFalseOptions,+ }),+ format: Property.StaticDropdown({+ displayName: 'Format',+ description: `Post format. Only formats the active theme supports are accepted.${unchanged}`,+ required: false,+ options: postFormatOptions,+ }),+ acf: Property.Object({+ displayName: 'Custom ACF Fields',+ description: `Advanced Custom Fields values as field name and value pairs; field names come from the ACF plugin menu. Only the fields you supply are written. Requires the site to expose ACF over the REST API.${unchanged}`,+ required: false,+ }),+ };+}++function pageOnlyProps({ mode }: { mode: 'create' | 'update' }) {+ const unchanged = mode === 'update' ? ' Leave empty to keep the current value.' : '';+ return {+ excerpt: Property.LongText({+ displayName: 'Excerpt',+ description: `Short summary of the page. Takes effect only when the theme or site supports page excerpts; WordPress silently ignores it otherwise.${unchanged}`,+ required: false,+ }),+ parent: Property.Number({+ displayName: 'Parent Page ID',+ description: `ID of the parent page, from list_pages.${unchanged}`,+ required: false,+ }),+ menu_order: Property.Number({+ displayName: 'Menu Order',+ description: `Position of the page among its siblings.${unchanged}`,+ required: false,+ }),+ };+}++function pagingProps() {+ return {+ per_page: Property.Number({+ displayName: 'Results Per Page',+ description: 'How many results to return, from 1 to 100. Defaults to 10.',+ required: false,+ defaultValue: 10,+ }),+ page: Property.Number({+ displayName: 'Page',+ description: 'Page of results to return, starting at 1. The output reports total_pages.',+ required: false,+ defaultValue: 1,+ }),+ };+}++export const wordpressContent = {+ isFilledText,+ isSetNumber,+ requireWholeNumber,+ parseIdList,+ parseStringList,+ buildPaging,+ buildContentBody,+ requireDateForFuture,+ buildMediaDetailsBody,+ requirePatch,+ contentProps,+ postOnlyProps,+ pageOnlyProps,+ pagingProps,+ openClosedOptions,+ trueFalseOptions,+ orderOptions,+};++export type ContentValues = {+ title?: string | null;+ content?: string | null;+ status?: string | null;+ date?: string | null;+ slug?: string | null;+ featured_media?: number | null;+ author?: number | null;+ comment_status?: string | null;+ ping_status?: string | null;+ excerpt?: string | null;+ categories?: unknown[] | null;+ tags?: unknown[] | null;+ sticky?: string | null;+ format?: string | null;+ acf?: Record<string, unknown> | null;+ parent?: number | null;+ menu_order?: number | null;+};++export type MediaDetailsValues = {+ title?: string | null;+ alt_text?: string | null;+ caption?: string | null;+ description?: string | null;+ post?: number | null;+};diff --git a/packages/pieces/community/wordpress/src/lib/output-schemas.ts b/packages/pieces/community/wordpress/src/lib/output-schemas.tsindex 70899cae39e..db267492fab 100644--- a/packages/pieces/community/wordpress/src/lib/output-schemas.ts+++ b/packages/pieces/community/wordpress/src/lib/output-schemas.ts@@ -13,6 +13,329 @@ const renderedBodyFields: OutputSchema['fields'] = [{ key: 'protected', label: 'Password Protected', format: 'boolean' },];+const postFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Post ID', format: 'number' },+ { key: 'title', label: 'Title', children: renderedTextFields },+ { key: 'link', label: 'Link', format: 'url' },+ { key: 'slug', label: 'Slug' },+ { key: 'status', label: 'Status' },+ { key: 'type', label: 'Type' },+ { key: 'date', label: 'Published Date', format: 'datetime' },+ { key: 'date_gmt', label: 'Published Date (GMT)', format: 'datetime' },+ { key: 'modified', label: 'Modified Date', format: 'datetime' },+ { key: 'modified_gmt', label: 'Modified Date (GMT)', format: 'datetime' },+ { key: 'content', label: 'Content', children: renderedBodyFields },+ { key: 'excerpt', label: 'Excerpt', children: renderedBodyFields },+ { key: 'guid', label: 'GUID', children: renderedUrlFields },+ { key: 'author', label: 'Author ID', format: 'number' },+ { key: 'featured_media', label: 'Featured Media ID', format: 'number' },+ { key: 'sticky', label: 'Sticky', format: 'boolean' },+ { key: 'format', label: 'Format' },+ {+ key: 'categories',+ label: 'Category IDs',+ description: 'Category term IDs assigned to the post, as a list of numbers.',+ },+ {+ key: 'tags',+ label: 'Tag IDs',+ description: 'Tag term IDs assigned to the post, as a list of numbers.',+ },+ { key: 'comment_status', label: 'Comment Status' },+ { key: 'ping_status', label: 'Ping Status' },+];++const renderedRawTextFields: OutputSchema['fields'] = [+ { key: 'rendered', label: 'Rendered', format: 'html' },+ { key: 'raw', label: 'Raw' },+];++const renderedRawUrlFields: OutputSchema['fields'] = [+ { key: 'rendered', label: 'Rendered', format: 'url' },+ { key: 'raw', label: 'Raw', format: 'url' },+];++const renderedRawBodyFields: OutputSchema['fields'] = [+ { key: 'rendered', label: 'Rendered', format: 'html' },+ { key: 'raw', label: 'Raw' },+ { key: 'protected', label: 'Password Protected', format: 'boolean' },+];++const renderedRawContentFields: OutputSchema['fields'] = [+ ...renderedRawBodyFields,+ { key: 'block_version', label: 'Block Version', format: 'number' },+];++const itemDateFields: OutputSchema['fields'] = [+ { key: 'date', label: 'Published Date', format: 'datetime' },+ { key: 'date_gmt', label: 'Published Date (GMT)', format: 'datetime' },+ { key: 'modified', label: 'Modified Date', format: 'datetime' },+ { key: 'modified_gmt', label: 'Modified Date (GMT)', format: 'datetime' },+];++const itemCommonFields: OutputSchema['fields'] = [+ ...itemDateFields,+ { key: 'link', label: 'Link', format: 'url' },+ { key: 'slug', label: 'Slug' },+ { key: 'status', label: 'Status' },+ { key: 'type', label: 'Type' },+ { key: 'author', label: 'Author ID', format: 'number' },+ { key: 'featured_media', label: 'Featured Media ID', format: 'number' },+ { key: 'comment_status', label: 'Comment Status' },+ { key: 'ping_status', label: 'Ping Status' },+ { key: 'template', label: 'Template' },+ { key: 'meta', label: 'Meta', description: 'Registered meta fields; the keys depend on the site.' },+ { key: 'class_list', label: 'CSS Classes', description: 'CSS classes WordPress assigns to the item, as a list of strings.' },+];++const editOnlyFields: OutputSchema['fields'] = [+ { key: 'permalink_template', label: 'Permalink Template' },+ { key: 'generated_slug', label: 'Generated Slug' },+];++const postTermFields: OutputSchema['fields'] = [+ { key: 'sticky', label: 'Sticky', format: 'boolean' },+ { key: 'format', label: 'Format' },+ {+ key: 'categories',+ label: 'Category IDs',+ description: 'Category term IDs assigned to the post, as a list of numbers.',+ },+ {+ key: 'tags',+ label: 'Tag IDs',+ description: 'Tag term IDs assigned to the post, as a list of numbers.',+ },+];++const postViewFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Post ID', format: 'number' },+ { key: 'title', label: 'Title', children: renderedTextFields },+ { key: 'content', label: 'Content', children: renderedBodyFields },+ { key: 'excerpt', label: 'Excerpt', children: renderedBodyFields },+ { key: 'guid', label: 'GUID', children: renderedUrlFields },+ ...itemCommonFields,+ ...postTermFields,+];++const postEditFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Post ID', format: 'number' },+ { key: 'title', label: 'Title', children: renderedRawTextFields },+ { key: 'content', label: 'Content', children: renderedRawContentFields },+ { key: 'excerpt', label: 'Excerpt', children: renderedRawBodyFields },+ { key: 'guid', label: 'GUID', children: renderedRawUrlFields },+ { key: 'password', label: 'Post Password' },+ ...itemCommonFields,+ ...postTermFields,+ ...editOnlyFields,+];++const pageOnlyFields: OutputSchema['fields'] = [+ { key: 'parent', label: 'Parent Page ID', format: 'number' },+ { key: 'menu_order', label: 'Menu Order', format: 'number' },+];++const pageViewFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Page ID', format: 'number' },+ { key: 'title', label: 'Title', children: renderedTextFields },+ { key: 'content', label: 'Content', children: renderedBodyFields },+ { key: 'excerpt', label: 'Excerpt', description: 'Present only when the theme or site supports page excerpts.', children: renderedBodyFields },+ { key: 'guid', label: 'GUID', children: renderedUrlFields },+ ...itemCommonFields,+ ...pageOnlyFields,+];++const pageEditFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Page ID', format: 'number' },+ { key: 'title', label: 'Title', children: renderedRawTextFields },+ { key: 'content', label: 'Content', children: renderedRawContentFields },+ { key: 'excerpt', label: 'Excerpt', description: 'Present only when the theme or site supports page excerpts.', children: renderedRawBodyFields },+ { key: 'guid', label: 'GUID', children: renderedRawUrlFields },+ { key: 'password', label: 'Page Password' },+ ...itemCommonFields,+ ...pageOnlyFields,+ ...editOnlyFields,+];++const termFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Term ID', format: 'number' },+ { key: 'name', label: 'Name' },+ { key: 'slug', label: 'Slug' },+ { key: 'description', label: 'Description' },+ { key: 'count', label: 'Published Post Count', format: 'number' },+ { key: 'link', label: 'Archive Link', format: 'url' },+ { key: 'taxonomy', label: 'Taxonomy' },+ { key: 'meta', label: 'Meta', description: 'Registered term meta; usually an empty list.' },+];++const categoryFields: OutputSchema['fields'] = [+ ...termFields,+ { key: 'parent', label: 'Parent Category ID', format: 'number', description: '0 when the category has no parent.' },+];++const avatarFields: OutputSchema['fields'] = [+ { key: '24', label: 'Avatar 24px', format: 'image' },+ { key: '48', label: 'Avatar 48px', format: 'image' },+ { key: '96', label: 'Avatar 96px', format: 'image' },+];++const commentViewFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Comment ID', format: 'number' },+ { key: 'post', label: 'Post ID', format: 'number' },+ { key: 'parent', label: 'Parent Comment ID', format: 'number' },+ { key: 'author', label: 'Author User ID', format: 'number', description: '0 for a guest comment.' },+ { key: 'author_name', label: 'Author Name' },+ { key: 'author_url', label: 'Author URL', format: 'url' },+ { key: 'date', label: 'Date', format: 'datetime' },+ { key: 'date_gmt', label: 'Date (GMT)', format: 'datetime' },+ { key: 'content', label: 'Content', children: renderedTextFields },+ { key: 'link', label: 'Link', format: 'url' },+ { key: 'status', label: 'Status', description: 'approved, hold, spam or trash.' },+ { key: 'type', label: 'Type' },+ { key: 'author_avatar_urls', label: 'Author Avatars', children: avatarFields },+ { key: 'meta', label: 'Meta', description: 'Registered comment meta; the keys depend on the site.' },+];++const commentEditFields: OutputSchema['fields'] = [+ ...commentViewFields.filter((field) => field.key !== 'content'),+ { key: 'content', label: 'Content', children: renderedRawTextFields },+ { key: 'author_email', label: 'Author Email', format: 'email' },+ { key: 'author_ip', label: 'Author IP' },+ { key: 'author_user_agent', label: 'Author User Agent' },+];++const mediaViewFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Media ID', format: 'number' },+ { key: 'title', label: 'Title', children: renderedTextFields },+ { key: 'guid', label: 'GUID', children: renderedUrlFields },+ { key: 'description', label: 'Description', children: renderedTextFields },+ { key: 'caption', label: 'Caption', children: renderedTextFields },+ ...itemCommonFields,+ { key: 'alt_text', label: 'Alt Text' },+ { key: 'media_type', label: 'Media Type' },+ { key: 'mime_type', label: 'MIME Type' },+ { key: 'source_url', label: 'File URL', format: 'url' },+ { key: 'filename', label: 'File Name' },+ { key: 'filesize', label: 'File Size', format: 'filesize' },+ { key: 'post', label: 'Attached Post ID', format: 'number', description: 'null when the file is not attached to a post.' },+ {+ key: 'media_details',+ label: 'Media Details',+ description: 'File details; images also carry sizes and image_meta.',+ children: [+ { key: 'width', label: 'Width', format: 'number' },+ { key: 'height', label: 'Height', format: 'number' },+ { key: 'file', label: 'Relative File Path' },+ { key: 'filesize', label: 'File Size', format: 'filesize' },+ { key: 'sizes', label: 'Sizes', dynamicKey: true, description: 'Generated image sizes keyed by size name.' },+ { key: 'image_meta', label: 'Image Metadata', description: 'EXIF-style metadata extracted from the image.' },+ ],+ },+];++const mediaEditFields: OutputSchema['fields'] = [+ ...mediaViewFields.filter(+ (field) => !['title', 'guid', 'description', 'caption'].includes(field.key)+ ),+ { key: 'title', label: 'Title', children: renderedRawTextFields },+ { key: 'guid', label: 'GUID', children: renderedRawUrlFields },+ { key: 'description', label: 'Description', children: renderedRawTextFields },+ { key: 'caption', label: 'Caption', children: renderedRawTextFields },+ ...editOnlyFields,+ { key: 'missing_image_sizes', label: 'Missing Image Sizes', description: 'Image sizes WordPress has not generated yet.' },+ { key: 'exif_orientation', label: 'EXIF Orientation', format: 'number' },+ { key: 'image_output_format', label: 'Image Output Format' },+ { key: 'image_save_progressive', label: 'Save Progressive', format: 'boolean' },+ { key: 'image_quality', label: 'Image Quality', description: 'Default quality and per-size quality.' },+];++const userPublicFields: OutputSchema['fields'] = [+ { key: 'id', label: 'User ID', format: 'number' },+ { key: 'name', label: 'Display Name' },+ { key: 'slug', label: 'Slug' },+ { key: 'url', label: 'Website', format: 'url' },+ { key: 'description', label: 'Biography' },+ { key: 'link', label: 'Author Archive Link', format: 'url' },+ { key: 'avatar_urls', label: 'Avatars', children: avatarFields },+ { key: 'meta', label: 'Meta', description: 'Registered user meta; the keys depend on the site.' },+ { key: 'is_super_admin', label: 'Is Super Admin', format: 'boolean' },+];++const currentUserFields: OutputSchema['fields'] = [+ ...userPublicFields,+ { key: 'username', label: 'Username' },+ { key: 'first_name', label: 'First Name' },+ { key: 'last_name', label: 'Last Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'nickname', label: 'Nickname' },+ { key: 'locale', label: 'Locale' },+ { key: 'registered_date', label: 'Registered Date', format: 'datetime' },+ { key: 'roles', label: 'Roles', description: 'Role slugs, e.g. administrator, editor, author.' },+ { key: 'capabilities', label: 'Capabilities', dynamicKey: true, description: 'Capability name to true/false for this user.' },+ { key: 'extra_capabilities', label: 'Extra Capabilities', dynamicKey: true },+];++const searchResultFields: OutputSchema['fields'] = [+ { key: 'id', label: 'ID', format: 'number' },+ { key: 'title', label: 'Title' },+ { key: 'url', label: 'URL', format: 'url' },+ { key: 'type', label: 'Type', description: 'post for posts and pages; the taxonomy (category, post_tag) for terms.' },+ { key: 'subtype', label: 'Subtype', description: 'post or page; present for post results only.' },+];++const settingsFields: OutputSchema['fields'] = [+ { key: 'title', label: 'Site Title' },+ { key: 'description', label: 'Tagline' },+ { key: 'url', label: 'Site URL', format: 'url' },+ { key: 'email', label: 'Admin Email', format: 'email' },+ { key: 'timezone', label: 'Timezone', description: 'Empty when the site uses a UTC offset instead of a named zone.' },+ { key: 'date_format', label: 'Date Format' },+ { key: 'time_format', label: 'Time Format' },+ { key: 'start_of_week', label: 'Start of Week', format: 'number' },+ { key: 'language', label: 'Language' },+ { key: 'use_smilies', label: 'Convert Emoticons', format: 'boolean' },+ { key: 'default_category', label: 'Default Category ID', format: 'number' },+ { key: 'default_post_format', label: 'Default Post Format' },+ { key: 'posts_per_page', label: 'Posts Per Page', format: 'number' },+ { key: 'show_on_front', label: 'Front Page Shows' },+ { key: 'page_on_front', label: 'Front Page ID', format: 'number' },+ { key: 'page_for_posts', label: 'Posts Page ID', format: 'number' },+ { key: 'default_ping_status', label: 'Default Ping Status' },+ { key: 'default_comment_status', label: 'Default Comment Status' },+ { key: 'site_logo', label: 'Site Logo Media ID', format: 'number', description: 'null when no logo is set.' },+ { key: 'site_icon', label: 'Site Icon Media ID', format: 'number' },+];++function listSchema({+ key,+ label,+ itemFields,+ itemLabel,+}: {+ key: string;+ label: string;+ itemFields: OutputSchema['fields'];+ itemLabel: string;+}): OutputSchema {+ return {+ fields: [+ { key, label, labelKey: itemLabel, listItems: itemFields },+ { key: 'count', label: 'Returned Count', format: 'number' },+ { key: 'total', label: 'Total Matches', format: 'number', description: 'From the X-WP-Total header; absent when the host strips it.' },+ { key: 'total_pages', label: 'Total Pages', format: 'number', description: 'From the X-WP-TotalPages header; absent when the host strips it.' },+ ],+ };+}++function deleteSchema({ itemFields }: { itemFields: OutputSchema['fields'] }): OutputSchema {+ return {+ fields: [+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'previous', label: 'Deleted Item', children: itemFields },+ ],+ };+}+export const createPostActionOutputSchema: OutputSchema = {fields: [{ key: 'id', label: 'Post ID', value: 'body.id', format: 'number' },@@ -109,40 +432,64 @@ export const getPostActionOutputSchema: OutputSchema = {],};-const postFields: OutputSchema['fields'] = [- { key: 'id', label: 'Post ID', format: 'number' },- { key: 'title', label: 'Title', children: renderedTextFields },- { key: 'link', label: 'Link', format: 'url' },- { key: 'slug', label: 'Slug' },- { key: 'status', label: 'Status' },- { key: 'type', label: 'Type' },- { key: 'date', label: 'Published Date', format: 'datetime' },- { key: 'date_gmt', label: 'Published Date (GMT)', format: 'datetime' },- { key: 'modified', label: 'Modified Date', format: 'datetime' },- { key: 'modified_gmt', label: 'Modified Date (GMT)', format: 'datetime' },- { key: 'content', label: 'Content', children: renderedBodyFields },- { key: 'excerpt', label: 'Excerpt', children: renderedBodyFields },- { key: 'guid', label: 'GUID', children: renderedUrlFields },- { key: 'author', label: 'Author ID', format: 'number' },- { key: 'featured_media', label: 'Featured Media ID', format: 'number' },- { key: 'sticky', label: 'Sticky', format: 'boolean' },- { key: 'format', label: 'Format' },- {- key: 'categories',- label: 'Category IDs',- description: 'Category term IDs assigned to the post, as a list of numbers.',- },- {- key: 'tags',- label: 'Tag IDs',- description: 'Tag term IDs assigned to the post, as a list of numbers.',- },- { key: 'comment_status', label: 'Comment Status' },- { key: 'ping_status', label: 'Ping Status' },-];--// update_post returns response.body, so its paths are bare — unlike the create/get-// actions above, which return the full HttpResponse and address the post under body.export const updatePostActionOutputSchema: OutputSchema = { fields: postFields };export const newPostTriggerOutputSchema: OutputSchema = { fields: postFields };++export const listPostsOutputSchema: OutputSchema = listSchema({ key: 'posts', label: 'Posts', itemFields: postViewFields, itemLabel: 'slug' });++export const getPostByIdOutputSchema: OutputSchema = { fields: postViewFields };++export const postEditOutputSchema: OutputSchema = { fields: postEditFields };++export const deletePostOutputSchema: OutputSchema = deleteSchema({ itemFields: postEditFields });++export const listPagesOutputSchema: OutputSchema = listSchema({ key: 'pages', label: 'Pages', itemFields: pageViewFields, itemLabel: 'slug' });++export const getPageOutputSchema: OutputSchema = { fields: pageViewFields };++export const pageEditOutputSchema: OutputSchema = { fields: pageEditFields };++export const listCategoriesOutputSchema: OutputSchema = listSchema({ key: 'categories', label: 'Categories', itemFields: categoryFields, itemLabel: 'name' });++export const createCategoryOutputSchema: OutputSchema = {+ fields: [+ ...categoryFields,+ { key: 'created', label: 'Created', format: 'boolean', description: 'false when a category with this name already existed under the same parent and was returned instead.' },+ ],+};++export const deleteCategoryOutputSchema: OutputSchema = deleteSchema({ itemFields: categoryFields });++export const listTagsOutputSchema: OutputSchema = listSchema({ key: 'tags', label: 'Tags', itemFields: termFields, itemLabel: 'name' });++export const createTagOutputSchema: OutputSchema = {+ fields: [+ ...termFields,+ { key: 'created', label: 'Created', format: 'boolean', description: 'false when a tag with this name already existed and was returned instead.' },+ ],+};++export const deleteTagOutputSchema: OutputSchema = deleteSchema({ itemFields: termFields });++export const listCommentsOutputSchema: OutputSchema = listSchema({ key: 'comments', label: 'Comments', itemFields: commentViewFields, itemLabel: 'author_name' });++export const commentEditOutputSchema: OutputSchema = { fields: commentEditFields };++export const deleteCommentOutputSchema: OutputSchema = deleteSchema({ itemFields: commentEditFields });++export const listMediaOutputSchema: OutputSchema = listSchema({ key: 'media', label: 'Media', itemFields: mediaViewFields, itemLabel: 'filename' });++export const getMediaOutputSchema: OutputSchema = { fields: mediaViewFields };++export const mediaEditOutputSchema: OutputSchema = { fields: mediaEditFields };++export const deleteMediaOutputSchema: OutputSchema = deleteSchema({ itemFields: mediaEditFields });++export const getCurrentUserOutputSchema: OutputSchema = { fields: currentUserFields };++export const listUsersOutputSchema: OutputSchema = listSchema({ key: 'users', label: 'Users', itemFields: userPublicFields, itemLabel: 'name' });++export const searchSiteContentOutputSchema: OutputSchema = listSchema({ key: 'results', label: 'Results', itemFields: searchResultFields, itemLabel: 'title' });++export const getSiteSettingsOutputSchema: OutputSchema = { fields: settingsFields };diff --git a/packages/pieces/community/wordpress/src/lib/trigger/new-post.trigger.ts b/packages/pieces/community/wordpress/src/lib/trigger/new-post.trigger.tsindex 0a07f6d818c..fb242ce4c4f 100644--- a/packages/pieces/community/wordpress/src/lib/trigger/new-post.trigger.ts+++ b/packages/pieces/community/wordpress/src/lib/trigger/new-post.trigger.ts@@ -129,34 +129,16 @@ export const wordpressNewPost = createTrigger({},type: TriggerStrategy.POLLING,async test(ctx) {- return await pollingHelper.test(polling, {- auth: ctx.auth,- store: ctx.store,- propsValue: ctx.propsValue,- files: ctx.files,- });+ return await pollingHelper.test(polling, ctx);},async onEnable(ctx) {- await pollingHelper.onEnable(polling, {- auth: ctx.auth,- store: ctx.store,- propsValue: ctx.propsValue,- });+ await pollingHelper.onEnable(polling, ctx);},async onDisable(ctx) {- await pollingHelper.onDisable(polling, {- auth: ctx.auth,- store: ctx.store,- propsValue: ctx.propsValue,- });+ await pollingHelper.onDisable(polling, ctx);},async run(ctx) {- return await pollingHelper.poll(polling, {- auth: ctx.auth,- store: ctx.store,- propsValue: ctx.propsValue,- files: ctx.files,- });+ return await pollingHelper.poll(polling, ctx);},});