Skip to content

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

feat(gitlab): manage issues, merge requests, repository files and users from flows and AI agents (#16395)

Odai Ahmad986e72e01f60
diff --git a/bun.lock b/bun.lock
index 03be0fa37fc..04eaf322f8e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -3726,12 +3726,13 @@
},
"packages/pieces/community/gitlab": {
"name": "@activepieces/piece-gitlab",
- "version": "0.2.1",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "2.6.2",
diff --git a/packages/pieces/community/gitlab/package.json b/packages/pieces/community/gitlab/package.json
index 4d9808fdb17..f5f972445c1 100644
--- a/packages/pieces/community/gitlab/package.json
+++ b/packages/pieces/community/gitlab/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-gitlab",
- "version": "0.2.1",
+ "version": "0.3.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
@@ -13,7 +13,8 @@
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
"tslib": "2.6.2",
diff --git a/packages/pieces/community/gitlab/src/i18n/de.json b/packages/pieces/community/gitlab/src/i18n/de.json
index 0e2a5a43bb1..4f7f4c26658 100644
--- a/packages/pieces/community/gitlab/src/i18n/de.json
+++ b/packages/pieces/community/gitlab/src/i18n/de.json
@@ -36,4 +36,4 @@
"Opened": "Geöffnet",
"Closed": "Geschlossen",
"Updated": "Updated"
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/gitlab/src/i18n/es.json b/packages/pieces/community/gitlab/src/i18n/es.json
index 275052d4cb6..44affe93fdd 100644
--- a/packages/pieces/community/gitlab/src/i18n/es.json
+++ b/packages/pieces/community/gitlab/src/i18n/es.json
@@ -36,4 +36,4 @@
"Opened": "Abierto",
"Closed": "Cerrado",
"Updated": "Actualizado"
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/gitlab/src/i18n/fr.json b/packages/pieces/community/gitlab/src/i18n/fr.json
index 7b81313c97d..9367e43b2c3 100644
--- a/packages/pieces/community/gitlab/src/i18n/fr.json
+++ b/packages/pieces/community/gitlab/src/i18n/fr.json
@@ -36,4 +36,4 @@
"Opened": "Ouvert",
"Closed": "Fermé",
"Updated": "Mis à jour"
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/gitlab/src/i18n/ja.json b/packages/pieces/community/gitlab/src/i18n/ja.json
index 8b84be83fe7..1024b985aa7 100644
--- a/packages/pieces/community/gitlab/src/i18n/ja.json
+++ b/packages/pieces/community/gitlab/src/i18n/ja.json
@@ -36,4 +36,4 @@
"Opened": "開放済み",
"Closed": "クローズ済み",
"Updated": "更新日時"
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/gitlab/src/i18n/nl.json b/packages/pieces/community/gitlab/src/i18n/nl.json
index 586ab998057..3392809a387 100644
--- a/packages/pieces/community/gitlab/src/i18n/nl.json
+++ b/packages/pieces/community/gitlab/src/i18n/nl.json
@@ -36,4 +36,4 @@
"Opened": "Geopend",
"Closed": "gesloten",
"Updated": "Gewijzigd"
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/gitlab/src/i18n/pt.json b/packages/pieces/community/gitlab/src/i18n/pt.json
index a047cb85422..6c238f2ca83 100644
--- a/packages/pieces/community/gitlab/src/i18n/pt.json
+++ b/packages/pieces/community/gitlab/src/i18n/pt.json
@@ -36,4 +36,4 @@
"Opened": "Aberto",
"Closed": "Fechado",
"Updated": "Atualizado"
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/gitlab/src/i18n/ru.json b/packages/pieces/community/gitlab/src/i18n/ru.json
index 1e8106753a7..51f3b4b02f5 100644
--- a/packages/pieces/community/gitlab/src/i18n/ru.json
+++ b/packages/pieces/community/gitlab/src/i18n/ru.json
@@ -29,4 +29,4 @@
"Opened": "Открыт",
"Closed": "Закрыто",
"Updated": "Updated"
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/gitlab/src/i18n/translation.json b/packages/pieces/community/gitlab/src/i18n/translation.json
index 861976bf59e..c7e673b86c9 100644
--- a/packages/pieces/community/gitlab/src/i18n/translation.json
+++ b/packages/pieces/community/gitlab/src/i18n/translation.json
@@ -1,12 +1,207 @@
{
"Collaboration tool for developers": "Collaboration tool for developers",
"Create Issue": "Create Issue",
+ "Add Spent Time": "Add Spent Time",
+ "Add Issue Comment": "Add Issue Comment",
+ "Create Project Issue": "Create Project Issue",
+ "Delete Issue Comment": "Delete Issue Comment",
+ "Get Issue Comment": "Get Issue Comment",
+ "Get Time Tracking Stats": "Get Time Tracking Stats",
+ "Get Issue": "Get Issue",
+ "List Issue Comments": "List Issue Comments",
+ "List Issues": "List Issues",
+ "Move Issue": "Move Issue",
+ "Reset Spent Time": "Reset Spent Time",
+ "Reset Time Estimate": "Reset Time Estimate",
+ "Set Time Estimate": "Set Time Estimate",
+ "Update Issue Comment": "Update Issue Comment",
+ "Update Issue": "Update Issue",
+ "Approve Merge Request": "Approve Merge Request",
+ "Create Merge Request Draft Comment": "Create Merge Request Draft Comment",
+ "Create Merge Request": "Create Merge Request",
+ "Delete Merge Request": "Delete Merge Request",
+ "Get Merge Request Approvals": "Get Merge Request Approvals",
+ "Get Merge Request": "Get Merge Request",
+ "List Merge Request Commits": "List Merge Request Commits",
+ "List Merge Request Diff Versions": "List Merge Request Diff Versions",
+ "List Merge Request Diffs": "List Merge Request Diffs",
+ "List Merge Request Discussions": "List Merge Request Discussions",
+ "List Merge Request Comments": "List Merge Request Comments",
+ "List Merge Requests": "List Merge Requests",
+ "Merge Merge Request": "Merge Merge Request",
+ "Unapprove Merge Request": "Unapprove Merge Request",
+ "Update Merge Request": "Update Merge Request",
+ "Create Branch": "Create Branch",
+ "Add Commit Comment": "Add Commit Comment",
+ "Create Commit": "Create Commit",
+ "Create File": "Create File",
+ "Delete Branch": "Delete Branch",
+ "Delete File": "Delete File",
+ "Get Branch": "Get Branch",
+ "Get Commit Branches and Tags": "Get Commit Branches and Tags",
+ "Get Commit Sequence Number": "Get Commit Sequence Number",
+ "Get Commit": "Get Commit",
+ "Get File": "Get File",
+ "List Branches": "List Branches",
+ "List Commit Comments": "List Commit Comments",
+ "List Commits": "List Commits",
+ "List Repository Files": "List Repository Files",
+ "List Tags": "List Tags",
+ "Protect Branch": "Protect Branch",
+ "Unprotect Branch": "Unprotect Branch",
+ "Update File": "Update File",
+ "Get Current User": "Get Current User",
+ "Get User Status": "Get User Status",
+ "Get User": "Get User",
+ "List Users": "List Users",
+ "Set User Status": "Set User Status",
"Custom API Call": "Custom API Call",
"Create a project issue": "Create a project issue",
+ "Logs time spent on an issue.": "Logs time spent on an issue.",
+ "Adds a comment (note) to an issue.": "Adds a comment (note) to an issue.",
+ "Creates an issue in a project given by ID or path.": "Creates an issue in a project given by ID or path.",
+ "Permanently deletes a comment from an issue.": "Permanently deletes a comment from an issue.",
+ "Gets one comment (note) of an issue.": "Gets one comment (note) of an issue.",
+ "Gets the time estimate and time spent of an issue.": "Gets the time estimate and time spent of an issue.",
+ "Gets one issue of a project by its IID.": "Gets one issue of a project by its IID.",
+ "Lists the comments (notes) of an issue, one page at a time.": "Lists the comments (notes) of an issue, one page at a time.",
+ "Lists or searches the issues of a project, one page at a time.": "Lists or searches the issues of a project, one page at a time.",
+ "Moves an issue to another project.": "Moves an issue to another project.",
+ "Clears all time spent logged on an issue.": "Clears all time spent logged on an issue.",
+ "Removes the time estimate of an issue.": "Removes the time estimate of an issue.",
+ "Sets the time estimate of an issue.": "Sets the time estimate of an issue.",
+ "Replaces the text of an issue comment.": "Replaces the text of an issue comment.",
+ "Updates the fields of an issue. Fields left empty are not changed.": "Updates the fields of an issue. Fields left empty are not changed.",
+ "Approves a merge request as the connected user.": "Approves a merge request as the connected user.",
+ "Adds an unpublished review comment to a merge request.": "Adds an unpublished review comment to a merge request.",
+ "Opens a merge request from a source branch into a target branch.": "Opens a merge request from a source branch into a target branch.",
+ "Permanently deletes a merge request. Requires the Owner role or admin.": "Permanently deletes a merge request. Requires the Owner role or admin.",
+ "Gets who approved a merge request and whether it is approved.": "Gets who approved a merge request and whether it is approved.",
+ "Gets one merge request of a project by its IID.": "Gets one merge request of a project by its IID.",
+ "Lists the commits of a merge request.": "Lists the commits of a merge request.",
+ "Lists the diff versions (pushes) of a merge request.": "Lists the diff versions (pushes) of a merge request.",
+ "Lists the changed files of a merge request with their diffs.": "Lists the changed files of a merge request with their diffs.",
+ "Lists the discussion threads of a merge request.": "Lists the discussion threads of a merge request.",
+ "Lists the comments (notes) of a merge request.": "Lists the comments (notes) of a merge request.",
+ "Lists or searches merge requests in one project, or across projects when no project is given.": "Lists or searches merge requests in one project, or across projects when no project is given.",
+ "Merges a merge request into its target branch.": "Merges a merge request into its target branch.",
+ "Removes the connected user's approval from a merge request.": "Removes the connected user's approval from a merge request.",
+ "Updates the fields of a merge request. Fields left empty are not changed.": "Updates the fields of a merge request. Fields left empty are not changed.",
+ "Creates a branch from a branch, tag or commit.": "Creates a branch from a branch, tag or commit.",
+ "Adds a comment to a commit, optionally on a line of a file.": "Adds a comment to a commit, optionally on a line of a file.",
+ "Creates a commit that adds, changes, moves or deletes several files at once.": "Creates a commit that adds, changes, moves or deletes several files at once.",
+ "Creates a new file in the repository with a commit.": "Creates a new file in the repository with a commit.",
+ "Deletes a branch from the repository.": "Deletes a branch from the repository.",
+ "Deletes a file from a branch with a commit.": "Deletes a file from a branch with a commit.",
+ "Gets one branch with its latest commit.": "Gets one branch with its latest commit.",
+ "Lists the branches and tags that contain a commit.": "Lists the branches and tags that contain a commit.",
+ "Gets how many commits lead up to a commit.": "Gets how many commits lead up to a commit.",
+ "Gets one commit by SHA, branch or tag.": "Gets one commit by SHA, branch or tag.",
+ "Gets a file from the repository with its decoded text content.": "Gets a file from the repository with its decoded text content.",
+ "Lists or searches the branches of the repository.": "Lists or searches the branches of the repository.",
+ "Lists the comments on a commit.": "Lists the comments on a commit.",
+ "Lists the commits of a branch, tag or path, newest first.": "Lists the commits of a branch, tag or path, newest first.",
+ "Lists files and folders in the repository.": "Lists files and folders in the repository.",
+ "Lists or searches the tags of the repository.": "Lists or searches the tags of the repository.",
+ "Protects a branch or wildcard pattern.": "Protects a branch or wildcard pattern.",
+ "Removes the protection from a branch or pattern.": "Removes the protection from a branch or pattern.",
+ "Replaces the content of an existing file with a commit.": "Replaces the content of an existing file with a commit.",
+ "Gets the GitLab user the connection belongs to.": "Gets the GitLab user the connection belongs to.",
+ "Gets the status (emoji, message, availability) of a user.": "Gets the status (emoji, message, availability) of a user.",
+ "Gets a user by numeric ID.": "Gets a user by numeric ID.",
+ "Searches users by name, username or public email.": "Searches users by name, username or public email.",
+ "Sets the status of the connected user. Fields left empty keep their current value.": "Sets the status of the connected user. Fields left empty keep their current value.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Project": "Project",
"Issue Title": "Issue Title",
"Issue Description": "Issue Description",
+ "Project ID or Path": "Project ID or Path",
+ "Issue IID": "Issue IID",
+ "Duration": "Duration",
+ "Summary": "Summary",
+ "Comment": "Comment",
+ "Internal": "Internal",
+ "Title": "Title",
+ "Description": "Description",
+ "Labels": "Labels",
+ "Assignee User IDs": "Assignee User IDs",
+ "Milestone ID": "Milestone ID",
+ "Due Date": "Due Date",
+ "Confidential": "Confidential",
+ "Note ID": "Note ID",
+ "Order By": "Order By",
+ "Sort": "Sort",
+ "Page": "Page",
+ "Per Page": "Per Page",
+ "State": "State",
+ "Search": "Search",
+ "Assignee User ID": "Assignee User ID",
+ "Author User ID": "Author User ID",
+ "Milestone Title": "Milestone Title",
+ "Updated After": "Updated After",
+ "Target Project ID": "Target Project ID",
+ "Estimate": "Estimate",
+ "Clear Description": "Clear Description",
+ "State Change": "State Change",
+ "Add Labels": "Add Labels",
+ "Remove Labels": "Remove Labels",
+ "Remove All Assignees": "Remove All Assignees",
+ "Remove Milestone": "Remove Milestone",
+ "Clear Due Date": "Clear Due Date",
+ "Discussion Locked": "Discussion Locked",
+ "Merge Request IID": "Merge Request IID",
+ "Expected Head SHA": "Expected Head SHA",
+ "Source Branch": "Source Branch",
+ "Target Branch": "Target Branch",
+ "Reviewer User IDs": "Reviewer User IDs",
+ "Delete Source Branch on Merge": "Delete Source Branch on Merge",
+ "Squash Commits on Merge": "Squash Commits on Merge",
+ "Scope": "Scope",
+ "Reviewer User ID": "Reviewer User ID",
+ "Squash Commits": "Squash Commits",
+ "Delete Source Branch": "Delete Source Branch",
+ "Merge Commit Message": "Merge Commit Message",
+ "Squash Commit Message": "Squash Commit Message",
+ "Auto Merge": "Auto Merge",
+ "Remove All Reviewers": "Remove All Reviewers",
+ "Branch Name": "Branch Name",
+ "Create From": "Create From",
+ "Commit SHA": "Commit SHA",
+ "File Path": "File Path",
+ "Line": "Line",
+ "Line Type": "Line Type",
+ "Branch": "Branch",
+ "Commit Message": "Commit Message",
+ "File Actions": "File Actions",
+ "Start Branch": "Start Branch",
+ "Author Name": "Author Name",
+ "Author Email": "Author Email",
+ "Content": "Content",
+ "Content Encoding": "Content Encoding",
+ "Last Commit ID": "Last Commit ID",
+ "Type": "Type",
+ "First Parent Only": "First Parent Only",
+ "Branch, Tag or Commit": "Branch, Tag or Commit",
+ "Branch or Tag": "Branch or Tag",
+ "Author": "Author",
+ "Since": "Since",
+ "Until": "Until",
+ "Folder Path": "Folder Path",
+ "Recursive": "Recursive",
+ "Branch or Pattern": "Branch or Pattern",
+ "Allowed to Push": "Allowed to Push",
+ "Allowed to Merge": "Allowed to Merge",
+ "Allow Force Push": "Allow Force Push",
+ "User ID or Username": "User ID or Username",
+ "User ID": "User ID",
+ "Username": "Username",
+ "Message": "Message",
+ "Clear Message": "Clear Message",
+ "Emoji": "Emoji",
+ "Clear Emoji": "Clear Emoji",
+ "Availability": "Availability",
+ "Clear Status After": "Clear Status After",
+ "Clear Whole Status": "Clear Whole Status",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
@@ -16,12 +211,110 @@
"Return Error as Output": "Return Error as Output",
"Timeout": "Timeout",
"Follow redirects": "Follow redirects",
+ "Numeric project ID or full path, e.g. `my-group/my-project`. Shown on the project overview page.": "Numeric project ID or full path, e.g. `my-group/my-project`. Shown on the project overview page.",
+ "The issue number inside the project (the `iid`, shown as #12 in GitLab), not the global issue ID.": "The issue number inside the project (the `iid`, shown as #12 in GitLab), not the global issue ID.",
+ "GitLab duration such as 1h30m, 2d or 1w.": "GitLab duration such as 1h30m, 2d or 1w.",
+ "Internal notes are visible only to project members with at least Reporter role.": "Internal notes are visible only to project members with at least Reporter role.",
+ "Markdown body of the issue.": "Markdown body of the issue.",
+ "Label names. Labels that do not exist yet are created.": "Label names. Labels that do not exist yet are created.",
+ "Numeric user IDs. Resolve a username with List Users.": "Numeric user IDs. Resolve a username with List Users.",
+ "Global milestone ID (not the iid).": "Global milestone ID (not the iid).",
+ "YYYY-MM-DD.": "YYYY-MM-DD.",
+ "Make the issue visible only to project members with at least Planner role.": "Make the issue visible only to project members with at least Planner role.",
+ "Numeric ID of the comment (note).": "Numeric ID of the comment (note).",
+ "Page number to fetch, starting at 1. Use `nextPage` from the previous result to continue.": "Page number to fetch, starting at 1. Use `nextPage` from the previous result to continue.",
+ "Items per page, 1 to 100. Defaults to 20.": "Items per page, 1 to 100. Defaults to 20.",
+ "Matches title and description.": "Matches title and description.",
+ "Issues must have all of these labels.": "Issues must have all of these labels.",
+ "ISO 8601 date-time.": "ISO 8601 date-time.",
+ "Numeric ID or full path of the project the issue is in now.": "Numeric ID or full path of the project the issue is in now.",
+ "Numeric ID of the destination project.": "Numeric ID of the destination project.",
+ "GitLab duration such as 3h30m, 2d or 1w.": "GitLab duration such as 3h30m, 2d or 1w.",
+ "Replaces the current assignees.": "Replaces the current assignees.",
+ "Leave empty to keep the current value.": "Leave empty to keep the current value.",
+ "The merge request number inside the project (the `iid`, shown as !12 in GitLab), not the global ID.": "The merge request number inside the project (the `iid`, shown as !12 in GitLab), not the global ID.",
+ "If set, the approval fails when the source branch head is not this SHA.": "If set, the approval fails when the source branch head is not this SHA.",
+ "Branch with the changes.": "Branch with the changes.",
+ "Branch to merge into, e.g. main.": "Branch to merge into, e.g. main.",
+ "Prefix with \"Draft:\" to open it as a draft.": "Prefix with \"Draft:\" to open it as a draft.",
+ "Leave empty to use the project default.": "Leave empty to use the project default.",
+ "Optional. Leave empty to search across projects.": "Optional. Leave empty to search across projects.",
+ "Whose merge requests to return. Without a project GitLab defaults to Created by Me; in a project it defaults to All.": "Whose merge requests to return. Without a project GitLab defaults to Created by Me; in a project it defaults to All.",
+ "If set, the merge fails when the source branch head is not this SHA.": "If set, the merge fails when the source branch head is not this SHA.",
+ "Leave empty to use the merge request setting.": "Leave empty to use the merge request setting.",
+ "Merge when the pipeline succeeds instead of immediately.": "Merge when the pipeline succeeds instead of immediately.",
+ "Replaces the current reviewers.": "Replaces the current reviewers.",
+ "Name of the new branch.": "Name of the new branch.",
+ "Branch, tag or commit SHA to start from.": "Branch, tag or commit SHA to start from.",
+ "Commit SHA, or a branch or tag name that resolves to a commit.": "Commit SHA, or a branch or tag name that resolves to a commit.",
+ "Branch to commit to. It must exist unless Start Branch is set.": "Branch to commit to. It must exist unless Start Branch is set.",
+ "JSON array, e.g. [{\"action\":\"create\",\"file_path\":\"docs/a.md\",\"content\":\"Hello\"},{\"action\":\"delete\",\"file_path\":\"old.txt\"}]. Each entry: action (create, update, delete, move, chmod), file_path, and as needed content, previous_path, encoding (text or base64), execute_filemode, last_commit_id.": "JSON array, e.g. [{\"action\":\"create\",\"file_path\":\"docs/a.md\",\"content\":\"Hello\"},{\"action\":\"delete\",\"file_path\":\"old.txt\"}]. Each entry: action (create, update, delete, move, chmod), file_path, and as needed content, previous_path, encoding (text or base64), execute_filemode, last_commit_id.",
+ "Create Branch from this branch first.": "Create Branch from this branch first.",
+ "Path from the repository root, e.g. docs/readme.md.": "Path from the repository root, e.g. docs/readme.md.",
+ "Branch name.": "Branch name.",
+ "last_commit_id from Get File. The delete fails if the file changed since.": "last_commit_id from Get File. The delete fails if the file changed since.",
+ "Count only first-parent commits.": "Count only first-parent commits.",
+ "Path from the repository root, e.g. src/index.ts.": "Path from the repository root, e.g. src/index.ts.",
+ "Defaults to the default branch.": "Defaults to the default branch.",
+ "Only commits that touch this path.": "Only commits that touch this path.",
+ "Author name or email.": "Author name or email.",
+ "Defaults to the repository root.": "Defaults to the repository root.",
+ "Include everything below the folder.": "Include everything below the folder.",
+ "Branch name or wildcard such as release/*.": "Branch name or wildcard such as release/*.",
+ "Leave empty for the GitLab default (Maintainers).": "Leave empty for the GitLab default (Maintainers).",
+ "Leave empty for the GitLab default (no).": "Leave empty for the GitLab default (no).",
+ "Exactly as it was protected, e.g. release/*.": "Exactly as it was protected, e.g. release/*.",
+ "last_commit_id from Get File. The update fails if the file changed since.": "last_commit_id from Get File. The update fails if the file changed since.",
+ "Leave empty for the connected user.": "Leave empty for the connected user.",
+ "Numeric user ID. Usernames are not accepted here.": "Numeric user ID. Usernames are not accepted here.",
+ "Name, username or public email.": "Name, username or public email.",
+ "Exact username, without @.": "Exact username, without @.",
+ "Up to 100 characters.": "Up to 100 characters.",
+ "Emoji name without colons, e.g. coffee or palm_tree.": "Emoji name without colons, e.g. coffee or palm_tree.",
+ "Removes message, emoji and availability. Other fields are ignored.": "Removes message, emoji and availability. Other fields are ignored.",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
"Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
"On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
"Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
"Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "Yes": "Yes",
+ "No": "No",
+ "Created At": "Created At",
+ "Updated At": "Updated At",
+ "Descending": "Descending",
+ "Ascending": "Ascending",
+ "Opened": "Opened",
+ "Closed": "Closed",
+ "All": "All",
+ "Priority": "Priority",
+ "Close": "Close",
+ "Reopen": "Reopen",
+ "Created by Me": "Created by Me",
+ "Assigned to Me": "Assigned to Me",
+ "Locked": "Locked",
+ "Merged": "Merged",
+ "New (added or unchanged line)": "New (added or unchanged line)",
+ "Old (removed line)": "Old (removed line)",
+ "Text": "Text",
+ "Base64": "Base64",
+ "Branches": "Branches",
+ "Tags": "Tags",
+ "Updated": "Updated",
+ "Name": "Name",
+ "Version": "Version",
+ "No one": "No one",
+ "Developers and Maintainers": "Developers and Maintainers",
+ "Maintainers": "Maintainers",
+ "Busy": "Busy",
+ "Not set": "Not set",
+ "30 minutes": "30 minutes",
+ "3 hours": "3 hours",
+ "8 hours": "8 hours",
+ "1 day": "1 day",
+ "3 days": "3 days",
+ "7 days": "7 days",
+ "30 days": "30 days",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
@@ -29,11 +322,8 @@
"DELETE": "DELETE",
"HEAD": "HEAD",
"New Project Issue Event": "New Project Issue Event",
- "Triggers on project issue events when an issue is created or when an existing issue is updated, closed, or reopened.": "Triggers on project issue events when an issue is created or when an existing issue is updated, closed, or reopened.",
+ "Triggers on project issue events (including confidential issues) when an issue is created or when an existing issue is updated, closed, or reopened.": "Triggers on project issue events (including confidential issues) when an issue is created or when an existing issue is updated, closed, or reopened.",
"Issue Event": "Issue Event",
"Issue Event type for trigger": "Issue Event type for trigger",
- "All": "All",
- "Opened": "Opened",
- "Closed": "Closed",
- "Updated": "Updated"
-}
\ No newline at end of file
+ "Reopened": "Reopened"
+}
diff --git a/packages/pieces/community/gitlab/src/i18n/vi.json b/packages/pieces/community/gitlab/src/i18n/vi.json
index 5073cb686a5..fcc61715602 100644
--- a/packages/pieces/community/gitlab/src/i18n/vi.json
+++ b/packages/pieces/community/gitlab/src/i18n/vi.json
@@ -29,4 +29,4 @@
"Opened": "Opened",
"Closed": "Closed",
"Updated": "Updated"
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/gitlab/src/i18n/zh.json b/packages/pieces/community/gitlab/src/i18n/zh.json
index 31d7b93d1b7..ae49c397e9e 100644
--- a/packages/pieces/community/gitlab/src/i18n/zh.json
+++ b/packages/pieces/community/gitlab/src/i18n/zh.json
@@ -36,4 +36,4 @@
"Opened": "Opened",
"Closed": "Closed",
"Updated": "Updated"
-}
\ No newline at end of file
+}
diff --git a/packages/pieces/community/gitlab/src/index.ts b/packages/pieces/community/gitlab/src/index.ts
index 2575996723e..aabfd444ae6 100644
--- a/packages/pieces/community/gitlab/src/index.ts
+++ b/packages/pieces/community/gitlab/src/index.ts
@@ -1,30 +1,135 @@
import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import {
- createPiece,
- OAuth2PropertyValue,
- PieceAuth,
-} from '@activepieces/pieces-framework';
+import { createPiece } from '@activepieces/pieces-framework';
import { PieceCategory } from '@activepieces/pieces-framework';
import { createIssueAction } from './lib/actions/create-issue-action';
+import { addIssueSpentTimeAction } from './lib/actions/issues/add-issue-spent-time';
+import { createIssueNoteAction } from './lib/actions/issues/create-issue-note';
+import { createProjectIssueAction } from './lib/actions/issues/create-project-issue';
+import { deleteIssueNoteAction } from './lib/actions/issues/delete-issue-note';
+import { getIssueNoteAction } from './lib/actions/issues/get-issue-note';
+import { getIssueTimeStatsAction } from './lib/actions/issues/get-issue-time-stats';
+import { getIssueAction } from './lib/actions/issues/get-issue';
+import { listIssueNotesAction } from './lib/actions/issues/list-issue-notes';
+import { listIssuesAction } from './lib/actions/issues/list-issues';
+import { moveIssueAction } from './lib/actions/issues/move-issue';
+import { resetIssueSpentTimeAction } from './lib/actions/issues/reset-issue-spent-time';
+import { resetIssueTimeEstimateAction } from './lib/actions/issues/reset-issue-time-estimate';
+import { setIssueTimeEstimateAction } from './lib/actions/issues/set-issue-time-estimate';
+import { updateIssueNoteAction } from './lib/actions/issues/update-issue-note';
+import { updateIssueAction } from './lib/actions/issues/update-issue';
+import { approveMergeRequestAction } from './lib/actions/merge-requests/approve-merge-request';
+import { createMergeRequestDraftNoteAction } from './lib/actions/merge-requests/create-merge-request-draft-note';
+import { createMergeRequestAction } from './lib/actions/merge-requests/create-merge-request';
+import { deleteMergeRequestAction } from './lib/actions/merge-requests/delete-merge-request';
+import { getMergeRequestApprovalsAction } from './lib/actions/merge-requests/get-merge-request-approvals';
+import { getMergeRequestAction } from './lib/actions/merge-requests/get-merge-request';
+import { listMergeRequestCommitsAction } from './lib/actions/merge-requests/list-merge-request-commits';
+import { listMergeRequestDiffVersionsAction } from './lib/actions/merge-requests/list-merge-request-diff-versions';
+import { listMergeRequestDiffsAction } from './lib/actions/merge-requests/list-merge-request-diffs';
+import { listMergeRequestDiscussionsAction } from './lib/actions/merge-requests/list-merge-request-discussions';
+import { listMergeRequestNotesAction } from './lib/actions/merge-requests/list-merge-request-notes';
+import { listMergeRequestsAction } from './lib/actions/merge-requests/list-merge-requests';
+import { mergeMergeRequestAction } from './lib/actions/merge-requests/merge-merge-request';
+import { unapproveMergeRequestAction } from './lib/actions/merge-requests/unapprove-merge-request';
+import { updateMergeRequestAction } from './lib/actions/merge-requests/update-merge-request';
+import { createBranchAction } from './lib/actions/repository/create-branch';
+import { createCommitCommentAction } from './lib/actions/repository/create-commit-comment';
+import { createCommitAction } from './lib/actions/repository/create-commit';
+import { createFileAction } from './lib/actions/repository/create-file';
+import { deleteBranchAction } from './lib/actions/repository/delete-branch';
+import { deleteFileAction } from './lib/actions/repository/delete-file';
+import { getBranchAction } from './lib/actions/repository/get-branch';
+import { getCommitRefsAction } from './lib/actions/repository/get-commit-refs';
+import { getCommitSequenceAction } from './lib/actions/repository/get-commit-sequence';
+import { getCommitAction } from './lib/actions/repository/get-commit';
+import { getFileAction } from './lib/actions/repository/get-file';
+import { listBranchesAction } from './lib/actions/repository/list-branches';
+import { listCommitCommentsAction } from './lib/actions/repository/list-commit-comments';
+import { listCommitsAction } from './lib/actions/repository/list-commits';
+import { listRepositoryTreeAction } from './lib/actions/repository/list-repository-tree';
+import { listTagsAction } from './lib/actions/repository/list-tags';
+import { protectBranchAction } from './lib/actions/repository/protect-branch';
+import { unprotectBranchAction } from './lib/actions/repository/unprotect-branch';
+import { updateFileAction } from './lib/actions/repository/update-file';
+import { getCurrentUserAction } from './lib/actions/users/get-current-user';
+import { getUserStatusAction } from './lib/actions/users/get-user-status';
+import { getUserAction } from './lib/actions/users/get-user';
+import { listUsersAction } from './lib/actions/users/list-users';
+import { setUserStatusAction } from './lib/actions/users/set-user-status';
import { issuesEventTrigger } from './lib/trigger/issue-event';
import { gitlabAuth } from './lib/auth';
+import { GITLAB_API_BASE } from './lib/common/constants';
export const gitlab = createPiece({
displayName: 'GitLab',
description: 'Collaboration tool for developers',
auth: gitlabAuth,
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/gitlab.png',
categories: [PieceCategory.DEVELOPER_TOOLS],
- authors: ["kishanprmr","MoShizzle","khaledmashaly","abuaboud"],
+ authors: ['kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud'],
actions: [
createIssueAction,
+ addIssueSpentTimeAction,
+ createIssueNoteAction,
+ createProjectIssueAction,
+ deleteIssueNoteAction,
+ getIssueNoteAction,
+ getIssueTimeStatsAction,
+ getIssueAction,
+ listIssueNotesAction,
+ listIssuesAction,
+ moveIssueAction,
+ resetIssueSpentTimeAction,
+ resetIssueTimeEstimateAction,
+ setIssueTimeEstimateAction,
+ updateIssueNoteAction,
+ updateIssueAction,
+ approveMergeRequestAction,
+ createMergeRequestDraftNoteAction,
+ createMergeRequestAction,
+ deleteMergeRequestAction,
+ getMergeRequestApprovalsAction,
+ getMergeRequestAction,
+ listMergeRequestCommitsAction,
+ listMergeRequestDiffVersionsAction,
+ listMergeRequestDiffsAction,
+ listMergeRequestDiscussionsAction,
+ listMergeRequestNotesAction,
+ listMergeRequestsAction,
+ mergeMergeRequestAction,
+ unapproveMergeRequestAction,
+ updateMergeRequestAction,
+ createBranchAction,
+ createCommitCommentAction,
+ createCommitAction,
+ createFileAction,
+ deleteBranchAction,
+ deleteFileAction,
+ getBranchAction,
+ getCommitRefsAction,
+ getCommitSequenceAction,
+ getCommitAction,
+ getFileAction,
+ listBranchesAction,
+ listCommitCommentsAction,
+ listCommitsAction,
+ listRepositoryTreeAction,
+ listTagsAction,
+ protectBranchAction,
+ unprotectBranchAction,
+ updateFileAction,
+ getCurrentUserAction,
+ getUserStatusAction,
+ getUserAction,
+ listUsersAction,
+ setUserStatusAction,
createCustomApiCallAction({
- baseUrl: () => 'https://gitlab.com/api/v4',
+ baseUrl: () => GITLAB_API_BASE,
auth: gitlabAuth,
authMapping: async (auth) => ({
- Authorization: `Bearer ${(auth).access_token}`,
+ Authorization: `Bearer ${auth.access_token}`,
}),
}),
],
diff --git a/packages/pieces/community/gitlab/src/lib/actions/create-issue-action.ts b/packages/pieces/community/gitlab/src/lib/actions/create-issue-action.ts
index 9caa2fbcdfe..b38d19b4c9e 100644
--- a/packages/pieces/community/gitlab/src/lib/actions/create-issue-action.ts
+++ b/packages/pieces/community/gitlab/src/lib/actions/create-issue-action.ts
@@ -1,14 +1,21 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { gitlabAuth } from '../auth';
-import { gitlabCommon, makeClient } from '../common';
+import { gitlabCommon } from '../common';
+import { gitlabRequest, projectPath } from '../common/client';
+import { optionalText, requireText } from '../common/props';
+import { issueOutputSchema } from '../output-schemas';
export const createIssueAction = createAction({
auth: gitlabAuth,
name: 'create_issue',
classification: 'WRITE',
description: 'Create a project issue',
- audience: 'both',
- aiMetadata: { description: 'Creates a new issue in a GitLab project, identified by its numeric project ID, with a title and optional description. Use to open a bug report, feature request, or task. Not idempotent: each call creates a separate issue even with identical inputs.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Creates a new issue in a GitLab project chosen from a dropdown, with a title and optional description. Not idempotent: each call creates a separate issue even with identical inputs.',
+ idempotent: false,
+ },
displayName: 'Create Issue',
props: {
projectId: gitlabCommon.projectId(),
@@ -21,12 +28,16 @@ export const createIssueAction = createAction({
required: false,
}),
},
+ outputSchema: issueOutputSchema,
async run({ propsValue, auth }) {
- const { projectId, title, description } = propsValue;
- const client = makeClient({ auth });
- return await client.createProjectIssue(projectId as string, {
- title: title,
- description: description,
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(String(propsValue.projectId))}/issues`,
+ body: {
+ title: requireText({ value: propsValue.title, label: 'Issue Title' }),
+ description: optionalText(propsValue.description),
+ },
});
},
});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/add-issue-spent-time.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/add-issue-spent-time.ts
new file mode 100644
index 00000000000..f26acd95de9
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/add-issue-spent-time.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import {
+ requireDuration,
+ optionalText,
+ gitlabProps,
+ requirePositiveInt,
+} from '../../common/props';
+import { timeStatsOutputSchema } from '../../output-schemas';
+
+export const addIssueSpentTimeAction = createAction({
+ auth: gitlabAuth,
+ name: 'add_issue_spent_time',
+ displayName: 'Add Spent Time',
+ description: 'Logs time spent on an issue.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Adds a time-spent entry to a GitLab issue, e.g. 1h30m, with an optional summary. Not idempotent: each call adds to the total; use Reset Spent Time to wipe it.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ duration: Property.ShortText({
+ displayName: 'Duration',
+ description: 'GitLab duration such as 1h30m, 2d or 1w.',
+ required: true,
+ }),
+ summary: Property.ShortText({ displayName: 'Summary', required: false }),
+ },
+ outputSchema: timeStatsOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(propsValue.projectId)}/issues/${iid}/add_spent_time`,
+ body: {
+ duration: requireDuration({
+ value: propsValue.duration,
+ label: 'Duration',
+ }),
+ summary: optionalText(propsValue.summary),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/create-issue-note.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/create-issue-note.ts
new file mode 100644
index 00000000000..368579f61ce
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/create-issue-note.ts
@@ -0,0 +1,49 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ requirePositiveInt,
+ requireText,
+ triStateValue,
+} from '../../common/props';
+import { noteOutputSchema } from '../../output-schemas';
+
+export const createIssueNoteAction = createAction({
+ auth: gitlabAuth,
+ name: 'create_issue_note',
+ displayName: 'Add Issue Comment',
+ description: 'Adds a comment (note) to an issue.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Posts a Markdown comment on a GitLab issue. Quick actions such as /label or /close in the body are executed by GitLab. Not idempotent: each call posts a new comment.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ body: Property.LongText({ displayName: 'Comment', required: true }),
+ internal: gitlabProps.triState(
+ 'Internal',
+ 'Internal notes are visible only to project members with at least Reporter role.'
+ ),
+ },
+ outputSchema: noteOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(propsValue.projectId)}/issues/${iid}/notes`,
+ body: {
+ body: requireText({ value: propsValue.body, label: 'Comment' }),
+ internal: triStateValue(propsValue.internal),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/create-project-issue.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/create-project-issue.ts
new file mode 100644
index 00000000000..f200e16844d
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/create-project-issue.ts
@@ -0,0 +1,88 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ idList,
+ optionalIsoDate,
+ optionalPositiveInt,
+ optionalText,
+ requireText,
+ stringList,
+ triStateValue,
+} from '../../common/props';
+import { issueOutputSchema } from '../../output-schemas';
+
+export const createProjectIssueAction = createAction({
+ auth: gitlabAuth,
+ name: 'create_project_issue',
+ displayName: 'Create Project Issue',
+ description: 'Creates an issue in a project given by ID or path.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Creates a new issue in a GitLab project identified by numeric ID or full path, with optional labels, assignees, milestone, due date and confidentiality. Use to open a bug, task or feature request. Not idempotent: each call creates a separate issue.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ title: Property.ShortText({ displayName: 'Title', required: true }),
+ description: Property.LongText({
+ displayName: 'Description',
+ description: 'Markdown body of the issue.',
+ required: false,
+ }),
+ labels: Property.Array({
+ displayName: 'Labels',
+ description: 'Label names. Labels that do not exist yet are created.',
+ required: false,
+ }),
+ assigneeIds: Property.Array({
+ displayName: 'Assignee User IDs',
+ description: 'Numeric user IDs. Resolve a username with List Users.',
+ required: false,
+ }),
+ milestoneId: Property.Number({
+ displayName: 'Milestone ID',
+ description: 'Global milestone ID (not the iid).',
+ required: false,
+ }),
+ dueDate: Property.ShortText({
+ displayName: 'Due Date',
+ description: 'YYYY-MM-DD.',
+ required: false,
+ }),
+ confidential: gitlabProps.triState(
+ 'Confidential',
+ 'Make the issue visible only to project members with at least Planner role.'
+ ),
+ },
+ outputSchema: issueOutputSchema,
+ async run({ auth, propsValue }) {
+ const labels = stringList({ value: propsValue.labels, label: 'Labels' });
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(propsValue.projectId)}/issues`,
+ body: {
+ title: requireText({ value: propsValue.title, label: 'Title' }),
+ description: optionalText(propsValue.description),
+ labels: labels?.join(','),
+ assignee_ids: idList({
+ value: propsValue.assigneeIds,
+ label: 'Assignee User IDs',
+ }),
+ milestone_id: optionalPositiveInt({
+ value: propsValue.milestoneId,
+ label: 'Milestone ID',
+ }),
+ due_date: optionalIsoDate({
+ value: propsValue.dueDate,
+ label: 'Due Date',
+ }),
+ confidential: triStateValue(propsValue.confidential),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/delete-issue-note.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/delete-issue-note.ts
new file mode 100644
index 00000000000..d22a8ac9fb3
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/delete-issue-note.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { deletedNoteOutputSchema } from '../../output-schemas';
+
+export const deleteIssueNoteAction = createAction({
+ auth: gitlabAuth,
+ name: 'delete_issue_note',
+ displayName: 'Delete Issue Comment',
+ description: 'Permanently deletes a comment from an issue.',
+ audience: 'ai',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description:
+ 'Permanently deletes one comment from a GitLab issue; it cannot be restored. A second call for the same note fails with not found.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ noteId: gitlabProps.noteId(),
+ },
+ outputSchema: deletedNoteOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ const noteId = requirePositiveInt({
+ value: propsValue.noteId,
+ label: 'Note ID',
+ });
+ await gitlabRequest({
+ auth,
+ method: 'DELETE',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/issues/${iid}/notes/${noteId}`,
+ });
+ return { deleted: true, noteId, issueIid: iid };
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/get-issue-note.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/get-issue-note.ts
new file mode 100644
index 00000000000..651fff6d36d
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/get-issue-note.ts
@@ -0,0 +1,42 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { noteOutputSchema } from '../../output-schemas';
+
+export const getIssueNoteAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_issue_note',
+ displayName: 'Get Issue Comment',
+ description: 'Gets one comment (note) of an issue.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Returns one comment on a GitLab issue by note ID, including author, body, timestamps and whether it is a system note. Use List Issue Comments to find the note ID.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ noteId: gitlabProps.noteId(),
+ },
+ outputSchema: noteOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ const noteId = requirePositiveInt({
+ value: propsValue.noteId,
+ label: 'Note ID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'GET',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/issues/${iid}/notes/${noteId}`,
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/get-issue-time-stats.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/get-issue-time-stats.ts
new file mode 100644
index 00000000000..705347f841f
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/get-issue-time-stats.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { timeStatsOutputSchema } from '../../output-schemas';
+
+export const getIssueTimeStatsAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_issue_time_stats',
+ displayName: 'Get Time Tracking Stats',
+ description: 'Gets the time estimate and time spent of an issue.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Returns the time estimate and total time spent on a GitLab issue, in seconds and in human-readable form.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ },
+ outputSchema: timeStatsOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'GET',
+ path: `${projectPath(propsValue.projectId)}/issues/${iid}/time_stats`,
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/get-issue.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/get-issue.ts
new file mode 100644
index 00000000000..f7cd20a7ae4
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/get-issue.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { issueOutputSchema } from '../../output-schemas';
+
+export const getIssueAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_issue',
+ displayName: 'Get Issue',
+ description: 'Gets one issue of a project by its IID.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Returns one GitLab issue (title, description, state, labels, assignees, milestone, dates, web URL) by project ID/path and issue IID. Use when the issue number is known; use List Issues to find it by text or filters.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ },
+ outputSchema: issueOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'GET',
+ path: `${projectPath(propsValue.projectId)}/issues/${iid}`,
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/list-issue-notes.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/list-issue-notes.ts
new file mode 100644
index 00000000000..f206a1d85c2
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/list-issue-notes.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ pagingInput,
+ requirePositiveInt,
+} from '../../common/props';
+import { noteListOutputSchema } from '../../output-schemas';
+
+export const listIssueNotesAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_issue_notes',
+ displayName: 'List Issue Comments',
+ description: 'Lists the comments (notes) of an issue, one page at a time.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists comments on a GitLab issue, including system notes such as label or state changes. Returns one page plus nextPage/hasMore. Use to read a discussion or find a note ID for Update or Delete Issue Comment.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ orderBy: Property.StaticDropdown({
+ displayName: 'Order By',
+ required: false,
+ options: {
+ options: [
+ { label: 'Created At', value: 'created_at' },
+ { label: 'Updated At', value: 'updated_at' },
+ ],
+ },
+ }),
+ sort: gitlabProps.sort(),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: noteListOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(propsValue.projectId)}/issues/${iid}/notes`,
+ query: { order_by: propsValue.orderBy, sort: propsValue.sort },
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/list-issues.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/list-issues.ts
new file mode 100644
index 00000000000..e94ee10a90f
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/list-issues.ts
@@ -0,0 +1,112 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ optionalIsoDate,
+ optionalPositiveInt,
+ optionalText,
+ pagingInput,
+ stringList,
+} from '../../common/props';
+import { issueListOutputSchema } from '../../output-schemas';
+
+export const listIssuesAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_issues',
+ displayName: 'List Issues',
+ description: 'Lists or searches the issues of a project, one page at a time.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists issues in a GitLab project with optional filters (state, labels, text search, assignee, author, milestone, updated after). Returns one page plus nextPage/hasMore; call again with nextPage to continue. Use to find an issue IID before Get Issue or Update Issue.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ state: Property.StaticDropdown({
+ displayName: 'State',
+ required: false,
+ options: {
+ options: [
+ { label: 'Opened', value: 'opened' },
+ { label: 'Closed', value: 'closed' },
+ { label: 'All', value: 'all' },
+ ],
+ },
+ }),
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: 'Matches title and description.',
+ required: false,
+ }),
+ labels: Property.Array({
+ displayName: 'Labels',
+ description: 'Issues must have all of these labels.',
+ required: false,
+ }),
+ assigneeId: Property.Number({
+ displayName: 'Assignee User ID',
+ required: false,
+ }),
+ authorId: Property.Number({
+ displayName: 'Author User ID',
+ required: false,
+ }),
+ milestone: Property.ShortText({
+ displayName: 'Milestone Title',
+ required: false,
+ }),
+ updatedAfter: Property.ShortText({
+ displayName: 'Updated After',
+ description: 'ISO 8601 date-time.',
+ required: false,
+ }),
+ orderBy: Property.StaticDropdown({
+ displayName: 'Order By',
+ required: false,
+ options: {
+ options: [
+ { label: 'Created At', value: 'created_at' },
+ { label: 'Updated At', value: 'updated_at' },
+ { label: 'Due Date', value: 'due_date' },
+ { label: 'Priority', value: 'priority' },
+ ],
+ },
+ }),
+ sort: gitlabProps.sort(),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: issueListOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(propsValue.projectId)}/issues`,
+ query: {
+ state: propsValue.state,
+ search: optionalText(propsValue.search),
+ labels: stringList({ value: propsValue.labels, label: 'Labels' })?.join(
+ ','
+ ),
+ assignee_id: optionalPositiveInt({
+ value: propsValue.assigneeId,
+ label: 'Assignee User ID',
+ }),
+ author_id: optionalPositiveInt({
+ value: propsValue.authorId,
+ label: 'Author User ID',
+ }),
+ milestone: optionalText(propsValue.milestone),
+ updated_after: optionalIsoDate({
+ value: propsValue.updatedAfter,
+ label: 'Updated After',
+ }),
+ order_by: propsValue.orderBy,
+ sort: propsValue.sort,
+ },
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/move-issue.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/move-issue.ts
new file mode 100644
index 00000000000..7de5e35a137
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/move-issue.ts
@@ -0,0 +1,51 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { issueOutputSchema } from '../../output-schemas';
+
+export const moveIssueAction = createAction({
+ auth: gitlabAuth,
+ name: 'move_issue',
+ displayName: 'Move Issue',
+ description: 'Moves an issue to another project.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Moves a GitLab issue to another project; the returned issue has a new IID in the target project and the original is closed. Not idempotent: a second call on the original IID fails because it was already moved.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(
+ 'Numeric ID or full path of the project the issue is in now.'
+ ),
+ issueIid: gitlabProps.issueIid(),
+ toProjectId: Property.Number({
+ displayName: 'Target Project ID',
+ description: 'Numeric ID of the destination project.',
+ required: true,
+ }),
+ },
+ outputSchema: issueOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(propsValue.projectId)}/issues/${iid}/move`,
+ body: {
+ to_project_id: requirePositiveInt({
+ value: propsValue.toProjectId,
+ label: 'Target Project ID',
+ }),
+ },
+ statusMessages: {
+ 400: 'GitLab refused to move the issue (it may already be moved, or the target is the same project)',
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/reset-issue-spent-time.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/reset-issue-spent-time.ts
new file mode 100644
index 00000000000..3879af7cc1d
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/reset-issue-spent-time.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { resetIssueSpentTime } from '../../common/irreversible';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { timeStatsOutputSchema } from '../../output-schemas';
+
+export const resetIssueSpentTimeAction = createAction({
+ auth: gitlabAuth,
+ name: 'reset_issue_spent_time',
+ displayName: 'Reset Spent Time',
+ description: 'Clears all time spent logged on an issue.',
+ audience: 'ai',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description:
+ 'Deletes every time-spent entry on a GitLab issue and sets the total to zero; the logged history cannot be restored. Calling it again leaves the total at zero.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ },
+ outputSchema: timeStatsOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ return resetIssueSpentTime({
+ auth,
+ projectId: propsValue.projectId,
+ issueIid: iid,
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/reset-issue-time-estimate.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/reset-issue-time-estimate.ts
new file mode 100644
index 00000000000..febca72e691
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/reset-issue-time-estimate.ts
@@ -0,0 +1,37 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { timeStatsOutputSchema } from '../../output-schemas';
+
+export const resetIssueTimeEstimateAction = createAction({
+ auth: gitlabAuth,
+ name: 'reset_issue_time_estimate',
+ displayName: 'Reset Time Estimate',
+ description: 'Removes the time estimate of an issue.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Removes the time estimate of a GitLab issue (sets it to zero). Logged time spent is not affected.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ },
+ outputSchema: timeStatsOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/issues/${iid}/reset_time_estimate`,
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/set-issue-time-estimate.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/set-issue-time-estimate.ts
new file mode 100644
index 00000000000..0e920daf81a
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/set-issue-time-estimate.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import {
+ requireDuration,
+ gitlabProps,
+ requirePositiveInt,
+} from '../../common/props';
+import { timeStatsOutputSchema } from '../../output-schemas';
+
+export const setIssueTimeEstimateAction = createAction({
+ auth: gitlabAuth,
+ name: 'set_issue_time_estimate',
+ displayName: 'Set Time Estimate',
+ description: 'Sets the time estimate of an issue.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Sets the time estimate of a GitLab issue to a duration such as 3h30m, replacing any previous estimate. Use Reset Time Estimate to remove it.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ duration: Property.ShortText({
+ displayName: 'Estimate',
+ description: 'GitLab duration such as 3h30m, 2d or 1w.',
+ required: true,
+ }),
+ },
+ outputSchema: timeStatsOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(propsValue.projectId)}/issues/${iid}/time_estimate`,
+ body: {
+ duration: requireDuration({
+ value: propsValue.duration,
+ label: 'Estimate',
+ }),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/update-issue-note.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/update-issue-note.ts
new file mode 100644
index 00000000000..61eb689d457
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/update-issue-note.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ requirePositiveInt,
+ requireText,
+} from '../../common/props';
+import { noteOutputSchema } from '../../output-schemas';
+
+export const updateIssueNoteAction = createAction({
+ auth: gitlabAuth,
+ name: 'update_issue_note',
+ displayName: 'Update Issue Comment',
+ description: 'Replaces the text of an issue comment.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Replaces the body of an existing comment on a GitLab issue. Only the author (or an admin) can edit a note. Re-sending the same text leaves the note unchanged.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ noteId: gitlabProps.noteId(),
+ body: Property.LongText({ displayName: 'Comment', required: true }),
+ },
+ outputSchema: noteOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ const noteId = requirePositiveInt({
+ value: propsValue.noteId,
+ label: 'Note ID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'PUT',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/issues/${iid}/notes/${noteId}`,
+ body: { body: requireText({ value: propsValue.body, label: 'Comment' }) },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/issues/update-issue.ts b/packages/pieces/community/gitlab/src/lib/actions/issues/update-issue.ts
new file mode 100644
index 00000000000..142cee0d22f
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/issues/update-issue.ts
@@ -0,0 +1,161 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ idList,
+ optionalIsoDate,
+ optionalPositiveInt,
+ optionalText,
+ requirePositiveInt,
+ stringList,
+ triStateValue,
+} from '../../common/props';
+import { issueOutputSchema } from '../../output-schemas';
+
+export const updateIssueAction = createAction({
+ auth: gitlabAuth,
+ name: 'update_issue',
+ displayName: 'Update Issue',
+ description:
+ 'Updates the fields of an issue. Fields left empty are not changed.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Changes an existing GitLab issue: title, description, close or reopen, add or remove labels, assignees, milestone, due date, confidential, discussion lock. Only the fields you set are sent; use the Clear options to blank a field. Use Move Issue to change its project.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ issueIid: gitlabProps.issueIid(),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ description: Property.LongText({
+ displayName: 'Description',
+ required: false,
+ }),
+ clearDescription: Property.Checkbox({
+ displayName: 'Clear Description',
+ required: false,
+ defaultValue: false,
+ }),
+ stateEvent: Property.StaticDropdown({
+ displayName: 'State Change',
+ required: false,
+ options: {
+ options: [
+ { label: 'Close', value: 'close' },
+ { label: 'Reopen', value: 'reopen' },
+ ],
+ },
+ }),
+ addLabels: Property.Array({ displayName: 'Add Labels', required: false }),
+ removeLabels: Property.Array({
+ displayName: 'Remove Labels',
+ required: false,
+ }),
+ assigneeIds: Property.Array({
+ displayName: 'Assignee User IDs',
+ description: 'Replaces the current assignees.',
+ required: false,
+ }),
+ clearAssignees: Property.Checkbox({
+ displayName: 'Remove All Assignees',
+ required: false,
+ defaultValue: false,
+ }),
+ milestoneId: Property.Number({
+ displayName: 'Milestone ID',
+ description: 'Global milestone ID (not the iid).',
+ required: false,
+ }),
+ clearMilestone: Property.Checkbox({
+ displayName: 'Remove Milestone',
+ required: false,
+ defaultValue: false,
+ }),
+ dueDate: Property.ShortText({
+ displayName: 'Due Date',
+ description: 'YYYY-MM-DD.',
+ required: false,
+ }),
+ clearDueDate: Property.Checkbox({
+ displayName: 'Clear Due Date',
+ required: false,
+ defaultValue: false,
+ }),
+ confidential: gitlabProps.triState(
+ 'Confidential',
+ 'Leave empty to keep the current value.'
+ ),
+ discussionLocked: gitlabProps.triState(
+ 'Discussion Locked',
+ 'Leave empty to keep the current value.'
+ ),
+ },
+ outputSchema: issueOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.issueIid,
+ label: 'Issue IID',
+ });
+ const body: Record<string, unknown> = {};
+ const title = optionalText(propsValue.title);
+ if (title !== undefined) body['title'] = title;
+ if (propsValue.clearDescription === true) body['description'] = '';
+ else if (optionalText(propsValue.description) !== undefined)
+ body['description'] = propsValue.description;
+ if (propsValue.stateEvent) body['state_event'] = propsValue.stateEvent;
+ const addLabels = stringList({
+ value: propsValue.addLabels,
+ label: 'Add Labels',
+ });
+ if (addLabels) body['add_labels'] = addLabels.join(',');
+ const removeLabels = stringList({
+ value: propsValue.removeLabels,
+ label: 'Remove Labels',
+ });
+ if (removeLabels) body['remove_labels'] = removeLabels.join(',');
+ if (propsValue.clearAssignees === true) body['assignee_ids'] = [0];
+ else {
+ const assignees = idList({
+ value: propsValue.assigneeIds,
+ label: 'Assignee User IDs',
+ });
+ if (assignees) body['assignee_ids'] = assignees;
+ }
+ if (propsValue.clearMilestone === true) body['milestone_id'] = 0;
+ else {
+ const milestone = optionalPositiveInt({
+ value: propsValue.milestoneId,
+ label: 'Milestone ID',
+ });
+ if (milestone !== undefined) body['milestone_id'] = milestone;
+ }
+ if (propsValue.clearDueDate === true) body['due_date'] = '';
+ else {
+ const due = optionalIsoDate({
+ value: propsValue.dueDate,
+ label: 'Due Date',
+ });
+ if (due !== undefined) body['due_date'] = due;
+ }
+ const confidential = triStateValue(propsValue.confidential);
+ if (confidential !== undefined) body['confidential'] = confidential;
+ const locked = triStateValue(propsValue.discussionLocked);
+ if (locked !== undefined) body['discussion_locked'] = locked;
+ if (Object.keys(body).length === 0) {
+ throw new Error('Set at least one field to update.');
+ }
+ const path = `${projectPath(propsValue.projectId)}/issues/${iid}`;
+ if (locked === false && body['state_event'] !== undefined) {
+ await gitlabRequest({
+ auth,
+ method: 'PUT',
+ path,
+ body: { discussion_locked: false },
+ });
+ }
+ return gitlabRequest({ auth, method: 'PUT', path, body });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/approve-merge-request.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/approve-merge-request.ts
new file mode 100644
index 00000000000..61623f598a2
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/approve-merge-request.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ optionalText,
+ requirePositiveInt,
+} from '../../common/props';
+import { approvalsOutputSchema } from '../../output-schemas';
+
+export const approveMergeRequestAction = createAction({
+ auth: gitlabAuth,
+ name: 'approve_merge_request',
+ displayName: 'Approve Merge Request',
+ description: 'Approves a merge request as the connected user.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ "Adds the connected user's approval to a GitLab merge request. GitLab answers 401 if this user already approved it or may not approve it (on gitlab.com authors usually cannot approve their own merge request), so check user_can_approve with Get Merge Request Approvals first. Undo with Unapprove Merge Request.",
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ sha: Property.ShortText({
+ displayName: 'Expected Head SHA',
+ description:
+ 'If set, the approval fails when the source branch head is not this SHA.',
+ required: false,
+ }),
+ },
+ outputSchema: approvalsOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/merge_requests/${iid}/approve`,
+ body: { sha: optionalText(propsValue.sha) },
+ statusMessages: {
+ 401: 'GitLab refused the approval: the connected user already approved this merge request or is not allowed to approve it (authors usually cannot approve their own)',
+ 409: 'The source branch head does not match the expected SHA',
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/create-merge-request-draft-note.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/create-merge-request-draft-note.ts
new file mode 100644
index 00000000000..895b55e6499
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/create-merge-request-draft-note.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ requirePositiveInt,
+ requireText,
+} from '../../common/props';
+import { draftNoteOutputSchema } from '../../output-schemas';
+
+export const createMergeRequestDraftNoteAction = createAction({
+ auth: gitlabAuth,
+ name: 'create_merge_request_draft_note',
+ displayName: 'Create Merge Request Draft Comment',
+ description: 'Adds an unpublished review comment to a merge request.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Adds a draft (unpublished, pending review) comment to a GitLab merge request; it is visible only to its author until the review is submitted in GitLab. Not idempotent: each call adds another draft.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ note: Property.LongText({ displayName: 'Comment', required: true }),
+ },
+ outputSchema: draftNoteOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/merge_requests/${iid}/draft_notes`,
+ body: { note: requireText({ value: propsValue.note, label: 'Comment' }) },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/create-merge-request.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/create-merge-request.ts
new file mode 100644
index 00000000000..9f9d75fcedd
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/create-merge-request.ts
@@ -0,0 +1,110 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ idList,
+ optionalPositiveInt,
+ optionalText,
+ requireText,
+ stringList,
+ triStateValue,
+} from '../../common/props';
+import { mergeRequestOutputSchema } from '../../output-schemas';
+
+export const createMergeRequestAction = createAction({
+ auth: gitlabAuth,
+ name: 'create_merge_request',
+ displayName: 'Create Merge Request',
+ description:
+ 'Opens a merge request from a source branch into a target branch.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Opens a GitLab merge request from a source branch into a target branch, with optional description, labels, assignees, reviewers and milestone. GitLab refuses a second open merge request for the same branch pair, so a retry fails with a conflict rather than duplicating.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ sourceBranch: gitlabProps.branch(
+ 'Source Branch',
+ 'Branch with the changes.'
+ ),
+ targetBranch: gitlabProps.branch(
+ 'Target Branch',
+ 'Branch to merge into, e.g. main.'
+ ),
+ title: Property.ShortText({
+ displayName: 'Title',
+ description: 'Prefix with "Draft:" to open it as a draft.',
+ required: true,
+ }),
+ description: Property.LongText({
+ displayName: 'Description',
+ required: false,
+ }),
+ labels: Property.Array({ displayName: 'Labels', required: false }),
+ assigneeIds: Property.Array({
+ displayName: 'Assignee User IDs',
+ required: false,
+ }),
+ reviewerIds: Property.Array({
+ displayName: 'Reviewer User IDs',
+ required: false,
+ }),
+ milestoneId: Property.Number({
+ displayName: 'Milestone ID',
+ description: 'Global milestone ID (not the iid).',
+ required: false,
+ }),
+ removeSourceBranch: gitlabProps.triState(
+ 'Delete Source Branch on Merge',
+ 'Leave empty to use the project default.'
+ ),
+ squash: gitlabProps.triState(
+ 'Squash Commits on Merge',
+ 'Leave empty to use the project default.'
+ ),
+ },
+ outputSchema: mergeRequestOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(propsValue.projectId)}/merge_requests`,
+ body: {
+ source_branch: requireText({
+ value: propsValue.sourceBranch,
+ label: 'Source Branch',
+ }),
+ target_branch: requireText({
+ value: propsValue.targetBranch,
+ label: 'Target Branch',
+ }),
+ title: requireText({ value: propsValue.title, label: 'Title' }),
+ description: optionalText(propsValue.description),
+ labels: stringList({ value: propsValue.labels, label: 'Labels' })?.join(
+ ','
+ ),
+ assignee_ids: idList({
+ value: propsValue.assigneeIds,
+ label: 'Assignee User IDs',
+ }),
+ reviewer_ids: idList({
+ value: propsValue.reviewerIds,
+ label: 'Reviewer User IDs',
+ }),
+ milestone_id: optionalPositiveInt({
+ value: propsValue.milestoneId,
+ label: 'Milestone ID',
+ }),
+ remove_source_branch: triStateValue(propsValue.removeSourceBranch),
+ squash: triStateValue(propsValue.squash),
+ },
+ statusMessages: {
+ 409: 'An open merge request already exists for this source and target branch',
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/delete-merge-request.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/delete-merge-request.ts
new file mode 100644
index 00000000000..c5947d24a5c
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/delete-merge-request.ts
@@ -0,0 +1,40 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { deletedMergeRequestOutputSchema } from '../../output-schemas';
+
+export const deleteMergeRequestAction = createAction({
+ auth: gitlabAuth,
+ name: 'delete_merge_request',
+ displayName: 'Delete Merge Request',
+ description:
+ 'Permanently deletes a merge request. Requires the Owner role or admin.',
+ audience: 'ai',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a GitLab merge request with its discussion; only project Owners or admins may do it. To stop a merge request without losing it, use Update Merge Request with State Change Close instead.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ },
+ outputSchema: deletedMergeRequestOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ await gitlabRequest({
+ auth,
+ method: 'DELETE',
+ path: `${projectPath(propsValue.projectId)}/merge_requests/${iid}`,
+ statusMessages: {
+ 403: 'Only project Owners or admins can delete merge requests',
+ },
+ });
+ return { deleted: true, mergeRequestIid: iid };
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/get-merge-request-approvals.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/get-merge-request-approvals.ts
new file mode 100644
index 00000000000..e5a802ca9aa
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/get-merge-request-approvals.ts
@@ -0,0 +1,37 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { approvalsOutputSchema } from '../../output-schemas';
+
+export const getMergeRequestApprovalsAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_merge_request_approvals',
+ displayName: 'Get Merge Request Approvals',
+ description: 'Gets who approved a merge request and whether it is approved.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Returns the approval status of a GitLab merge request: whether it is approved, approvals required and left, and the users who approved. Works on every GitLab tier. Check it before Approve Merge Request to avoid a duplicate-approval error.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ },
+ outputSchema: approvalsOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'GET',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/merge_requests/${iid}/approvals`,
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/get-merge-request.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/get-merge-request.ts
new file mode 100644
index 00000000000..5ee105cd283
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/get-merge-request.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { mergeRequestOutputSchema } from '../../output-schemas';
+
+export const getMergeRequestAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_merge_request',
+ displayName: 'Get Merge Request',
+ description: 'Gets one merge request of a project by its IID.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Returns one GitLab merge request by project and IID: title, description, branches, state, merge status, author, assignees, reviewers, SHA and web URL. Use List Merge Requests to find the IID.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ },
+ outputSchema: mergeRequestOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'GET',
+ path: `${projectPath(propsValue.projectId)}/merge_requests/${iid}`,
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-commits.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-commits.ts
new file mode 100644
index 00000000000..635a418f536
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-commits.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ pagingInput,
+ requirePositiveInt,
+} from '../../common/props';
+import { commitListOutputSchema } from '../../output-schemas';
+
+export const listMergeRequestCommitsAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_merge_request_commits',
+ displayName: 'List Merge Request Commits',
+ description: 'Lists the commits of a merge request.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists the commits in a GitLab merge request, newest first. Returns one page plus nextPage/hasMore.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: commitListOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(
+ propsValue.projectId
+ )}/merge_requests/${iid}/commits`,
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-diff-versions.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-diff-versions.ts
new file mode 100644
index 00000000000..cd5bc34a6f8
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-diff-versions.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ pagingInput,
+ requirePositiveInt,
+} from '../../common/props';
+import { diffVersionListOutputSchema } from '../../output-schemas';
+
+export const listMergeRequestDiffVersionsAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_merge_request_diff_versions',
+ displayName: 'List Merge Request Diff Versions',
+ description: 'Lists the diff versions (pushes) of a merge request.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists the diff versions of a GitLab merge request (one per push), with head, base and start SHAs. Returns one page plus nextPage/hasMore. Use List Merge Request Diffs for the file changes themselves.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: diffVersionListOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(
+ propsValue.projectId
+ )}/merge_requests/${iid}/versions`,
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-diffs.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-diffs.ts
new file mode 100644
index 00000000000..b7de9409c59
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-diffs.ts
@@ -0,0 +1,55 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import { GitlabDiff } from '../../common/models';
+import {
+ gitlabProps,
+ pagingInput,
+ requirePositiveInt,
+} from '../../common/props';
+import { diffListOutputSchema } from '../../output-schemas';
+
+export const MAX_DIFF_CHARS = 20_000;
+
+export function capDiff(
+ diff: GitlabDiff
+): GitlabDiff & { diffTruncated: boolean } {
+ const text = typeof diff.diff === 'string' ? diff.diff : '';
+ if (text.length <= MAX_DIFF_CHARS) {
+ return { ...diff, diffTruncated: false };
+ }
+ return { ...diff, diff: text.slice(0, MAX_DIFF_CHARS), diffTruncated: true };
+}
+
+export const listMergeRequestDiffsAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_merge_request_diffs',
+ displayName: 'List Merge Request Diffs',
+ description: 'Lists the changed files of a merge request with their diffs.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists the files changed in a GitLab merge request with old/new paths, new/renamed/deleted flags and the unified diff text. Each diff is cut at 20,000 characters (diffTruncated tells you); read the full file with Get File. Returns one page plus nextPage/hasMore.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: diffListOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ const result = await gitlabListPage<GitlabDiff>({
+ auth,
+ path: `${projectPath(propsValue.projectId)}/merge_requests/${iid}/diffs`,
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ return { ...result, items: result.items.map(capDiff) };
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-discussions.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-discussions.ts
new file mode 100644
index 00000000000..ca6d87a8dc3
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-discussions.ts
@@ -0,0 +1,43 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ pagingInput,
+ requirePositiveInt,
+} from '../../common/props';
+import { discussionListOutputSchema } from '../../output-schemas';
+
+export const listMergeRequestDiscussionsAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_merge_request_discussions',
+ displayName: 'List Merge Request Discussions',
+ description: 'Lists the discussion threads of a merge request.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists discussion threads on a GitLab merge request, each with its notes and, for diff comments, the file position and resolved state. Returns one page plus nextPage/hasMore.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: discussionListOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(
+ propsValue.projectId
+ )}/merge_requests/${iid}/discussions`,
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-notes.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-notes.ts
new file mode 100644
index 00000000000..efd33e58077
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-request-notes.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ pagingInput,
+ requirePositiveInt,
+} from '../../common/props';
+import { noteListOutputSchema } from '../../output-schemas';
+
+export const listMergeRequestNotesAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_merge_request_notes',
+ displayName: 'List Merge Request Comments',
+ description: 'Lists the comments (notes) of a merge request.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists comments on a GitLab merge request, including system notes. Returns one page plus nextPage/hasMore. Use List Merge Request Discussions to see comments grouped into threads.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ orderBy: Property.StaticDropdown({
+ displayName: 'Order By',
+ required: false,
+ options: {
+ options: [
+ { label: 'Created At', value: 'created_at' },
+ { label: 'Updated At', value: 'updated_at' },
+ ],
+ },
+ }),
+ sort: gitlabProps.sort(),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: noteListOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(propsValue.projectId)}/merge_requests/${iid}/notes`,
+ query: { order_by: propsValue.orderBy, sort: propsValue.sort },
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-requests.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-requests.ts
new file mode 100644
index 00000000000..5f44dbb0d78
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/list-merge-requests.ts
@@ -0,0 +1,128 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ optionalIsoDate,
+ optionalPositiveInt,
+ optionalText,
+ pagingInput,
+ stringList,
+} from '../../common/props';
+import { mergeRequestListOutputSchema } from '../../output-schemas';
+
+export const listMergeRequestsAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_merge_requests',
+ displayName: 'List Merge Requests',
+ description:
+ 'Lists or searches merge requests in one project, or across projects when no project is given.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ "Lists GitLab merge requests in one project, or across every project the user can see when Project is empty. Without a project, Scope decides whose merge requests are returned and GitLab defaults to only those created by the connected user, so set Scope to All to see everyone's. Scope All without a project returns public merge requests from all of gitlab.com and can time out, so give a project for that. Returns one page plus nextPage/hasMore.",
+ idempotent: true,
+ },
+ props: {
+ projectId: Property.ShortText({
+ displayName: 'Project ID or Path',
+ description: 'Optional. Leave empty to search across projects.',
+ required: false,
+ }),
+ scope: Property.StaticDropdown({
+ displayName: 'Scope',
+ description:
+ 'Whose merge requests to return. Without a project GitLab defaults to Created by Me; in a project it defaults to All.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Created by Me', value: 'created_by_me' },
+ { label: 'Assigned to Me', value: 'assigned_to_me' },
+ { label: 'All', value: 'all' },
+ ],
+ },
+ }),
+ state: Property.StaticDropdown({
+ displayName: 'State',
+ required: false,
+ options: {
+ options: [
+ { label: 'Opened', value: 'opened' },
+ { label: 'Closed', value: 'closed' },
+ { label: 'Locked', value: 'locked' },
+ { label: 'Merged', value: 'merged' },
+ { label: 'All', value: 'all' },
+ ],
+ },
+ }),
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: 'Matches title and description.',
+ required: false,
+ }),
+ labels: Property.Array({ displayName: 'Labels', required: false }),
+ sourceBranch: Property.ShortText({
+ displayName: 'Source Branch',
+ required: false,
+ }),
+ targetBranch: Property.ShortText({
+ displayName: 'Target Branch',
+ required: false,
+ }),
+ authorId: Property.Number({
+ displayName: 'Author User ID',
+ required: false,
+ }),
+ reviewerId: Property.Number({
+ displayName: 'Reviewer User ID',
+ required: false,
+ }),
+ updatedAfter: Property.ShortText({
+ displayName: 'Updated After',
+ description: 'ISO 8601 date-time.',
+ required: false,
+ }),
+ sort: gitlabProps.sort(),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: mergeRequestListOutputSchema,
+ async run({ auth, propsValue }) {
+ const project = optionalText(propsValue.projectId);
+ return gitlabListPage({
+ auth,
+ path:
+ project === undefined
+ ? '/merge_requests'
+ : `${projectPath(project)}/merge_requests`,
+ query: {
+ scope: propsValue.scope,
+ state: propsValue.state,
+ search: optionalText(propsValue.search),
+ labels: stringList({ value: propsValue.labels, label: 'Labels' })?.join(
+ ','
+ ),
+ source_branch: optionalText(propsValue.sourceBranch),
+ target_branch: optionalText(propsValue.targetBranch),
+ author_id: optionalPositiveInt({
+ value: propsValue.authorId,
+ label: 'Author User ID',
+ }),
+ reviewer_id: optionalPositiveInt({
+ value: propsValue.reviewerId,
+ label: 'Reviewer User ID',
+ }),
+ updated_after: optionalIsoDate({
+ value: propsValue.updatedAfter,
+ label: 'Updated After',
+ }),
+ sort: propsValue.sort,
+ },
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ statusMessages: {
+ 408: 'GitLab timed out listing merge requests across all projects. Set Project, or use Scope Created by Me or Assigned to Me',
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/merge-merge-request.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/merge-merge-request.ts
new file mode 100644
index 00000000000..d1fe057b763
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/merge-merge-request.ts
@@ -0,0 +1,83 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { mergeMergeRequest } from '../../common/irreversible';
+import {
+ gitlabProps,
+ optionalText,
+ requirePositiveInt,
+ triStateValue,
+} from '../../common/props';
+import { mergeRequestOutputSchema } from '../../output-schemas';
+
+export const mergeMergeRequestAction = createAction({
+ auth: gitlabAuth,
+ name: 'merge_merge_request',
+ displayName: 'Merge Merge Request',
+ description: 'Merges a merge request into its target branch.',
+ audience: 'ai',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description:
+ 'Merges a GitLab merge request into its target branch, optionally squashing and deleting the source branch; this changes the target branch and cannot be undone through the API. Pass the expected head SHA to refuse the merge if new commits were pushed. With Auto Merge, GitLab merges once the pipeline succeeds instead of now.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ sha: Property.ShortText({
+ displayName: 'Expected Head SHA',
+ description:
+ 'If set, the merge fails when the source branch head is not this SHA.',
+ required: false,
+ }),
+ squash: gitlabProps.triState(
+ 'Squash Commits',
+ 'Leave empty to use the merge request setting.'
+ ),
+ shouldRemoveSourceBranch: gitlabProps.triState(
+ 'Delete Source Branch',
+ 'Leave empty to use the merge request setting.'
+ ),
+ mergeCommitMessage: Property.LongText({
+ displayName: 'Merge Commit Message',
+ required: false,
+ }),
+ squashCommitMessage: Property.LongText({
+ displayName: 'Squash Commit Message',
+ required: false,
+ }),
+ autoMerge: gitlabProps.triState(
+ 'Auto Merge',
+ 'Merge when the pipeline succeeds instead of immediately.'
+ ),
+ },
+ outputSchema: mergeRequestOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ return mergeMergeRequest({
+ auth,
+ projectId: propsValue.projectId,
+ mergeRequestIid: iid,
+ body: {
+ sha: optionalText(propsValue.sha),
+ squash: triStateValue(propsValue.squash),
+ should_remove_source_branch: triStateValue(
+ propsValue.shouldRemoveSourceBranch
+ ),
+ merge_commit_message: optionalText(propsValue.mergeCommitMessage),
+ squash_commit_message: optionalText(propsValue.squashCommitMessage),
+ auto_merge: triStateValue(propsValue.autoMerge),
+ },
+ statusMessages: {
+ 401: 'The connected user is not allowed to merge this merge request',
+ 405: 'The merge request cannot be merged now (draft, closed, already merged, conflicts or blocked by required approvals or pipelines)',
+ 406: 'The merge request has conflicts and cannot be merged',
+ 409: 'The source branch head does not match the expected SHA',
+ 422: 'GitLab could not merge the merge request',
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/unapprove-merge-request.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/unapprove-merge-request.ts
new file mode 100644
index 00000000000..312288b3112
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/unapprove-merge-request.ts
@@ -0,0 +1,40 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requirePositiveInt } from '../../common/props';
+import { approvalsOutputSchema } from '../../output-schemas';
+
+export const unapproveMergeRequestAction = createAction({
+ auth: gitlabAuth,
+ name: 'unapprove_merge_request',
+ displayName: 'Unapprove Merge Request',
+ description: "Removes the connected user's approval from a merge request.",
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ "Withdraws the connected user's approval from a GitLab merge request. GitLab answers 404 if the user had not approved it, so a second call fails.",
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ },
+ outputSchema: approvalsOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/merge_requests/${iid}/unapprove`,
+ statusMessages: {
+ 404: 'The connected user has not approved this merge request, or it was not found',
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/merge-requests/update-merge-request.ts b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/update-merge-request.ts
new file mode 100644
index 00000000000..dfa2371ef3f
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/merge-requests/update-merge-request.ts
@@ -0,0 +1,172 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ idList,
+ optionalPositiveInt,
+ optionalText,
+ requirePositiveInt,
+ stringList,
+ triStateValue,
+} from '../../common/props';
+import { mergeRequestOutputSchema } from '../../output-schemas';
+
+export const updateMergeRequestAction = createAction({
+ auth: gitlabAuth,
+ name: 'update_merge_request',
+ displayName: 'Update Merge Request',
+ description:
+ 'Updates the fields of a merge request. Fields left empty are not changed.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Changes an open GitLab merge request: title, description, target branch, close or reopen, add or remove labels, assignees, reviewers, milestone, squash and delete-source-branch settings. Only the fields you set are sent; use the Clear options to blank a field. Use Merge Merge Request to merge it.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ mergeRequestIid: gitlabProps.mergeRequestIid(),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ description: Property.LongText({
+ displayName: 'Description',
+ required: false,
+ }),
+ clearDescription: Property.Checkbox({
+ displayName: 'Clear Description',
+ required: false,
+ defaultValue: false,
+ }),
+ targetBranch: Property.ShortText({
+ displayName: 'Target Branch',
+ required: false,
+ }),
+ stateEvent: Property.StaticDropdown({
+ displayName: 'State Change',
+ required: false,
+ options: {
+ options: [
+ { label: 'Close', value: 'close' },
+ { label: 'Reopen', value: 'reopen' },
+ ],
+ },
+ }),
+ addLabels: Property.Array({ displayName: 'Add Labels', required: false }),
+ removeLabels: Property.Array({
+ displayName: 'Remove Labels',
+ required: false,
+ }),
+ assigneeIds: Property.Array({
+ displayName: 'Assignee User IDs',
+ description: 'Replaces the current assignees.',
+ required: false,
+ }),
+ clearAssignees: Property.Checkbox({
+ displayName: 'Remove All Assignees',
+ required: false,
+ defaultValue: false,
+ }),
+ reviewerIds: Property.Array({
+ displayName: 'Reviewer User IDs',
+ description: 'Replaces the current reviewers.',
+ required: false,
+ }),
+ clearReviewers: Property.Checkbox({
+ displayName: 'Remove All Reviewers',
+ required: false,
+ defaultValue: false,
+ }),
+ milestoneId: Property.Number({
+ displayName: 'Milestone ID',
+ description: 'Global milestone ID (not the iid).',
+ required: false,
+ }),
+ clearMilestone: Property.Checkbox({
+ displayName: 'Remove Milestone',
+ required: false,
+ defaultValue: false,
+ }),
+ removeSourceBranch: gitlabProps.triState(
+ 'Delete Source Branch on Merge',
+ 'Leave empty to keep the current value.'
+ ),
+ squash: gitlabProps.triState(
+ 'Squash Commits on Merge',
+ 'Leave empty to keep the current value.'
+ ),
+ discussionLocked: gitlabProps.triState(
+ 'Discussion Locked',
+ 'Leave empty to keep the current value.'
+ ),
+ },
+ outputSchema: mergeRequestOutputSchema,
+ async run({ auth, propsValue }) {
+ const iid = requirePositiveInt({
+ value: propsValue.mergeRequestIid,
+ label: 'Merge Request IID',
+ });
+ const body: Record<string, unknown> = {};
+ const title = optionalText(propsValue.title);
+ if (title !== undefined) body['title'] = title;
+ if (propsValue.clearDescription === true) body['description'] = '';
+ else if (optionalText(propsValue.description) !== undefined)
+ body['description'] = propsValue.description;
+ const target = optionalText(propsValue.targetBranch);
+ if (target !== undefined) body['target_branch'] = target;
+ if (propsValue.stateEvent) body['state_event'] = propsValue.stateEvent;
+ const addLabels = stringList({
+ value: propsValue.addLabels,
+ label: 'Add Labels',
+ });
+ if (addLabels) body['add_labels'] = addLabels.join(',');
+ const removeLabels = stringList({
+ value: propsValue.removeLabels,
+ label: 'Remove Labels',
+ });
+ if (removeLabels) body['remove_labels'] = removeLabels.join(',');
+ if (propsValue.clearAssignees === true) body['assignee_ids'] = [0];
+ else {
+ const assignees = idList({
+ value: propsValue.assigneeIds,
+ label: 'Assignee User IDs',
+ });
+ if (assignees) body['assignee_ids'] = assignees;
+ }
+ if (propsValue.clearReviewers === true) body['reviewer_ids'] = [0];
+ else {
+ const reviewers = idList({
+ value: propsValue.reviewerIds,
+ label: 'Reviewer User IDs',
+ });
+ if (reviewers) body['reviewer_ids'] = reviewers;
+ }
+ if (propsValue.clearMilestone === true) body['milestone_id'] = 0;
+ else {
+ const milestone = optionalPositiveInt({
+ value: propsValue.milestoneId,
+ label: 'Milestone ID',
+ });
+ if (milestone !== undefined) body['milestone_id'] = milestone;
+ }
+ const removeSource = triStateValue(propsValue.removeSourceBranch);
+ if (removeSource !== undefined) body['remove_source_branch'] = removeSource;
+ const squash = triStateValue(propsValue.squash);
+ if (squash !== undefined) body['squash'] = squash;
+ const locked = triStateValue(propsValue.discussionLocked);
+ if (locked !== undefined) body['discussion_locked'] = locked;
+ if (Object.keys(body).length === 0) {
+ throw new Error('Set at least one field to update.');
+ }
+ const path = `${projectPath(propsValue.projectId)}/merge_requests/${iid}`;
+ if (locked === false && body['state_event'] !== undefined) {
+ await gitlabRequest({
+ auth,
+ method: 'PUT',
+ path,
+ body: { discussion_locked: false },
+ });
+ }
+ return gitlabRequest({ auth, method: 'PUT', path, body });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/create-branch.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/create-branch.ts
new file mode 100644
index 00000000000..e39f6c03fd5
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/create-branch.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requireText } from '../../common/props';
+import { branchOutputSchema } from '../../output-schemas';
+
+export const createBranchAction = createAction({
+ auth: gitlabAuth,
+ name: 'create_branch',
+ displayName: 'Create Branch',
+ description: 'Creates a branch from a branch, tag or commit.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Creates a new branch in a GitLab repository from an existing branch, tag or commit SHA. GitLab answers 400 if the branch already exists, so a second call fails; use Get Branch to check first.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ branch: gitlabProps.branch('Branch Name', 'Name of the new branch.'),
+ ref: Property.ShortText({
+ displayName: 'Create From',
+ description: 'Branch, tag or commit SHA to start from.',
+ required: true,
+ }),
+ },
+ outputSchema: branchOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(propsValue.projectId)}/repository/branches`,
+ body: {
+ branch: requireText({ value: propsValue.branch, label: 'Branch Name' }),
+ ref: requireText({ value: propsValue.ref, label: 'Create From' }),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/create-commit-comment.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/create-commit-comment.ts
new file mode 100644
index 00000000000..366fc2d9d20
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/create-commit-comment.ts
@@ -0,0 +1,78 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { encodeSegment, gitlabRequest, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ optionalPositiveInt,
+ optionalText,
+ requireText,
+} from '../../common/props';
+import { commitCommentOutputSchema } from '../../output-schemas';
+
+export const createCommitCommentAction = createAction({
+ auth: gitlabAuth,
+ name: 'create_commit_comment',
+ displayName: 'Add Commit Comment',
+ description: 'Adds a comment to a commit, optionally on a line of a file.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ "Posts a comment on a GitLab commit, either on the whole commit or on one line of a changed file (set File Path, Line and Line Type together; the line must be part of that commit's diff, otherwise GitLab posts it as a general comment and lineAnchored is false). Not idempotent: each call posts a new comment.",
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ sha: gitlabProps.sha(),
+ note: Property.LongText({ displayName: 'Comment', required: true }),
+ path: Property.ShortText({ displayName: 'File Path', required: false }),
+ line: Property.Number({ displayName: 'Line', required: false }),
+ lineType: Property.StaticDropdown({
+ displayName: 'Line Type',
+ required: false,
+ options: {
+ options: [
+ { label: 'New (added or unchanged line)', value: 'new' },
+ { label: 'Old (removed line)', value: 'old' },
+ ],
+ },
+ }),
+ },
+ outputSchema: commitCommentOutputSchema,
+ async run({ auth, propsValue }) {
+ const path = optionalText(propsValue.path);
+ const line = optionalPositiveInt({ value: propsValue.line, label: 'Line' });
+ const lineType = propsValue.lineType;
+ const anchored = [path, line, lineType].filter(
+ (value) => value !== undefined && value !== null && value !== ''
+ ).length;
+ if (anchored !== 0 && anchored !== 3) {
+ throw new Error(
+ 'Set File Path, Line and Line Type together, or none of them.'
+ );
+ }
+ const comment = await gitlabRequest<Record<string, unknown>>({
+ auth,
+ method: 'POST',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/repository/commits/${encodeSegment({
+ value: propsValue.sha,
+ label: 'Commit SHA',
+ })}/comments`,
+ body: {
+ note: requireText({ value: propsValue.note, label: 'Comment' }),
+ path,
+ line,
+ line_type: lineType || undefined,
+ },
+ });
+ return {
+ ...comment,
+ lineAnchored:
+ anchored === 3 &&
+ comment?.['path'] !== null &&
+ comment?.['path'] !== undefined,
+ };
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/create-commit.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/create-commit.ts
new file mode 100644
index 00000000000..fa7cd25241f
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/create-commit.ts
@@ -0,0 +1,141 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { isRecord } from '../../common/secret-request';
+import { gitlabProps, optionalText, requireText } from '../../common/props';
+import { commitOutputSchema } from '../../output-schemas';
+
+const COMMIT_ACTIONS = ['create', 'delete', 'move', 'update', 'chmod'];
+const MAX_COMMIT_ACTIONS = 100;
+
+export function parseCommitActions(value: unknown): Record<string, unknown>[] {
+ let raw = value;
+ if (typeof raw === 'string') {
+ try {
+ raw = JSON.parse(raw);
+ } catch {
+ throw new Error('File Actions must be a JSON array.');
+ }
+ }
+ if (!Array.isArray(raw) || raw.length === 0) {
+ throw new Error('File Actions must be a non-empty JSON array.');
+ }
+ if (raw.length > MAX_COMMIT_ACTIONS) {
+ throw new Error(
+ `File Actions can hold at most ${MAX_COMMIT_ACTIONS} entries.`
+ );
+ }
+ return raw.map((entry, index) => {
+ if (!isRecord(entry)) {
+ throw new Error(`File Actions entry ${index + 1} must be an object.`);
+ }
+ const item = entry;
+ const action = item['action'];
+ if (typeof action !== 'string' || !COMMIT_ACTIONS.includes(action)) {
+ throw new Error(
+ `File Actions entry ${
+ index + 1
+ }: action must be one of ${COMMIT_ACTIONS.join(', ')}.`
+ );
+ }
+ if (
+ typeof item['file_path'] !== 'string' ||
+ item['file_path'].trim() === ''
+ ) {
+ throw new Error(
+ `File Actions entry ${index + 1}: file_path is required.`
+ );
+ }
+ if (
+ action === 'move' &&
+ (typeof item['previous_path'] !== 'string' ||
+ item['previous_path'].trim() === '')
+ ) {
+ throw new Error(
+ `File Actions entry ${index + 1}: previous_path is required for move.`
+ );
+ }
+ if (
+ (action === 'create' || action === 'update') &&
+ typeof item['content'] !== 'string'
+ ) {
+ throw new Error(
+ `File Actions entry ${index + 1}: content is required for ${action}.`
+ );
+ }
+ if (
+ item['encoding'] !== undefined &&
+ item['encoding'] !== 'text' &&
+ item['encoding'] !== 'base64'
+ ) {
+ throw new Error(
+ `File Actions entry ${index + 1}: encoding must be text or base64.`
+ );
+ }
+ return item;
+ });
+}
+
+export const createCommitAction = createAction({
+ auth: gitlabAuth,
+ name: 'create_commit',
+ displayName: 'Create Commit',
+ description:
+ 'Creates a commit that adds, changes, moves or deletes several files at once.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Creates one GitLab commit on a branch that applies several file operations together (create, update, delete, move, chmod). Set Start Branch to create the branch from another one in the same call. Not idempotent: a second call makes another commit or fails because files already exist. For a single file, Create File or Update File is simpler.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ branch: gitlabProps.branch(
+ 'Branch',
+ 'Branch to commit to. It must exist unless Start Branch is set.'
+ ),
+ commitMessage: Property.LongText({
+ displayName: 'Commit Message',
+ required: true,
+ }),
+ actions: Property.Json({
+ displayName: 'File Actions',
+ description:
+ 'JSON array, e.g. [{"action":"create","file_path":"docs/a.md","content":"Hello"},{"action":"delete","file_path":"old.txt"}]. Each entry: action (create, update, delete, move, chmod), file_path, and as needed content, previous_path, encoding (text or base64), execute_filemode, last_commit_id.',
+ required: true,
+ }),
+ startBranch: Property.ShortText({
+ displayName: 'Start Branch',
+ description: 'Create Branch from this branch first.',
+ required: false,
+ }),
+ authorName: Property.ShortText({
+ displayName: 'Author Name',
+ required: false,
+ }),
+ authorEmail: Property.ShortText({
+ displayName: 'Author Email',
+ required: false,
+ }),
+ },
+ outputSchema: commitOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(propsValue.projectId)}/repository/commits`,
+ body: {
+ branch: requireText({ value: propsValue.branch, label: 'Branch' }),
+ commit_message: requireText({
+ value: propsValue.commitMessage,
+ label: 'Commit Message',
+ }),
+ actions: parseCommitActions(propsValue.actions),
+ start_branch: optionalText(propsValue.startBranch),
+ author_name: optionalText(propsValue.authorName),
+ author_email: optionalText(propsValue.authorEmail),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/create-file.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/create-file.ts
new file mode 100644
index 00000000000..b8481e6c8b1
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/create-file.ts
@@ -0,0 +1,89 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import {
+ filePathSegment,
+ gitlabRequest,
+ projectPath,
+} from '../../common/client';
+import { gitlabProps, optionalText, requireText } from '../../common/props';
+import { fileCommitOutputSchema } from '../../output-schemas';
+
+export const createFileAction = createAction({
+ auth: gitlabAuth,
+ name: 'create_file',
+ displayName: 'Create File',
+ description: 'Creates a new file in the repository with a commit.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Creates a new file on a branch of a GitLab repository as one commit. GitLab answers 400 if the file already exists, so a second call fails; use Update File to change it. Use Create Commit for several files at once.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ filePath: Property.ShortText({
+ displayName: 'File Path',
+ description: 'Path from the repository root, e.g. docs/readme.md.',
+ required: true,
+ }),
+ branch: gitlabProps.branch(
+ 'Branch',
+ 'Branch to commit to. It must exist unless Start Branch is set.'
+ ),
+ content: Property.LongText({ displayName: 'Content', required: true }),
+ commitMessage: Property.ShortText({
+ displayName: 'Commit Message',
+ required: true,
+ }),
+ encoding: Property.StaticDropdown({
+ displayName: 'Content Encoding',
+ required: false,
+ defaultValue: 'text',
+ options: {
+ options: [
+ { label: 'Text', value: 'text' },
+ { label: 'Base64', value: 'base64' },
+ ],
+ },
+ }),
+ startBranch: Property.ShortText({
+ displayName: 'Start Branch',
+ description: 'Create Branch from this branch first.',
+ required: false,
+ }),
+ authorName: Property.ShortText({
+ displayName: 'Author Name',
+ required: false,
+ }),
+ authorEmail: Property.ShortText({
+ displayName: 'Author Email',
+ required: false,
+ }),
+ },
+ outputSchema: fileCommitOutputSchema,
+ async run({ auth, propsValue }) {
+ if (typeof propsValue.content !== 'string') {
+ throw new Error('Content is required.');
+ }
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/repository/files/${filePathSegment(propsValue.filePath)}`,
+ body: {
+ branch: requireText({ value: propsValue.branch, label: 'Branch' }),
+ content: propsValue.content,
+ commit_message: requireText({
+ value: propsValue.commitMessage,
+ label: 'Commit Message',
+ }),
+ encoding: propsValue.encoding ?? 'text',
+ start_branch: optionalText(propsValue.startBranch),
+ author_name: optionalText(propsValue.authorName),
+ author_email: optionalText(propsValue.authorEmail),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/delete-branch.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/delete-branch.ts
new file mode 100644
index 00000000000..3b3bd29a9c7
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/delete-branch.ts
@@ -0,0 +1,41 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { encodeSegment, gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requireText } from '../../common/props';
+import { deletedBranchOutputSchema } from '../../output-schemas';
+
+export const deleteBranchAction = createAction({
+ auth: gitlabAuth,
+ name: 'delete_branch',
+ displayName: 'Delete Branch',
+ description: 'Deletes a branch from the repository.',
+ audience: 'ai',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description:
+ 'Deletes one branch from a GitLab repository; commits only on that branch become unreachable. Protected and default branches cannot be deleted. A second call fails with not found.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ branch: gitlabProps.branch(),
+ },
+ outputSchema: deletedBranchOutputSchema,
+ async run({ auth, propsValue }) {
+ const branch = requireText({ value: propsValue.branch, label: 'Branch' });
+ await gitlabRequest({
+ auth,
+ method: 'DELETE',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/repository/branches/${encodeSegment({
+ value: branch,
+ label: 'Branch',
+ })}`,
+ statusMessages: {
+ 403: 'GitLab refused to delete the branch: it is protected or the default branch, or the user lacks permission',
+ },
+ });
+ return { deleted: true, branch };
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/delete-file.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/delete-file.ts
new file mode 100644
index 00000000000..41d8476f35b
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/delete-file.ts
@@ -0,0 +1,59 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import {
+ filePathSegment,
+ gitlabRequest,
+ projectPath,
+} from '../../common/client';
+import { gitlabProps, optionalText, requireText } from '../../common/props';
+import { deletedFileOutputSchema } from '../../output-schemas';
+
+export const deleteFileAction = createAction({
+ auth: gitlabAuth,
+ name: 'delete_file',
+ displayName: 'Delete File',
+ description: 'Deletes a file from a branch with a commit.',
+ audience: 'ai',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description:
+ 'Deletes one file from a branch of a GitLab repository as a new commit. The file stays in history but is gone from the branch. A second call fails because the file no longer exists.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ filePath: Property.ShortText({ displayName: 'File Path', required: true }),
+ branch: gitlabProps.branch(),
+ commitMessage: Property.ShortText({
+ displayName: 'Commit Message',
+ required: true,
+ }),
+ lastCommitId: Property.ShortText({
+ displayName: 'Last Commit ID',
+ description:
+ 'last_commit_id from Get File. The delete fails if the file changed since.',
+ required: false,
+ }),
+ },
+ outputSchema: deletedFileOutputSchema,
+ async run({ auth, propsValue }) {
+ const filePath = propsValue.filePath;
+ const branch = requireText({ value: propsValue.branch, label: 'Branch' });
+ await gitlabRequest({
+ auth,
+ method: 'DELETE',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/repository/files/${filePathSegment(filePath)}`,
+ body: {
+ branch,
+ commit_message: requireText({
+ value: propsValue.commitMessage,
+ label: 'Commit Message',
+ }),
+ last_commit_id: optionalText(propsValue.lastCommitId),
+ },
+ });
+ return { deleted: true, file_path: filePath, branch };
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/get-branch.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/get-branch.ts
new file mode 100644
index 00000000000..492a6620c4a
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/get-branch.ts
@@ -0,0 +1,36 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { encodeSegment, gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps } from '../../common/props';
+import { branchOutputSchema } from '../../output-schemas';
+
+export const getBranchAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_branch',
+ displayName: 'Get Branch',
+ description: 'Gets one branch with its latest commit.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Returns one GitLab branch by name: latest commit, whether it is merged, protected or the default branch, and push/merge permissions for the connected user.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ branch: gitlabProps.branch(),
+ },
+ outputSchema: branchOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabRequest({
+ auth,
+ method: 'GET',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/repository/branches/${encodeSegment({
+ value: propsValue.branch,
+ label: 'Branch',
+ })}`,
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/get-commit-refs.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/get-commit-refs.ts
new file mode 100644
index 00000000000..d3217bf01c9
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/get-commit-refs.ts
@@ -0,0 +1,55 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import {
+ encodeSegment,
+ gitlabListPage,
+ projectPath,
+} from '../../common/client';
+import { gitlabProps, pagingInput } from '../../common/props';
+import { commitRefListOutputSchema } from '../../output-schemas';
+
+export const getCommitRefsAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_commit_refs',
+ displayName: 'Get Commit Branches and Tags',
+ description: 'Lists the branches and tags that contain a commit.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists the branches and/or tags of a GitLab repository that contain a given commit, e.g. to check whether a fix reached a release branch. Returns one page plus nextPage/hasMore.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ sha: gitlabProps.sha(),
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: false,
+ defaultValue: 'all',
+ options: {
+ options: [
+ { label: 'All', value: 'all' },
+ { label: 'Branches', value: 'branch' },
+ { label: 'Tags', value: 'tag' },
+ ],
+ },
+ }),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: commitRefListOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(
+ propsValue.projectId
+ )}/repository/commits/${encodeSegment({
+ value: propsValue.sha,
+ label: 'Commit SHA',
+ })}/refs`,
+ query: { type: propsValue.type ?? 'all' },
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/get-commit-sequence.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/get-commit-sequence.ts
new file mode 100644
index 00000000000..66787effc45
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/get-commit-sequence.ts
@@ -0,0 +1,41 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { encodeSegment, gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, triStateValue } from '../../common/props';
+import { commitSequenceOutputSchema } from '../../output-schemas';
+
+export const getCommitSequenceAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_commit_sequence',
+ displayName: 'Get Commit Sequence Number',
+ description: 'Gets how many commits lead up to a commit.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Returns the sequence number of a GitLab commit: the count of commits reachable from it, following first parents only when that option is set. Useful for build numbers.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ sha: gitlabProps.sha(),
+ firstParent: gitlabProps.triState(
+ 'First Parent Only',
+ 'Count only first-parent commits.'
+ ),
+ },
+ outputSchema: commitSequenceOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabRequest({
+ auth,
+ method: 'GET',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/repository/commits/${encodeSegment({
+ value: propsValue.sha,
+ label: 'Commit SHA',
+ })}/sequence`,
+ query: { first_parent: triStateValue(propsValue.firstParent) },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/get-commit.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/get-commit.ts
new file mode 100644
index 00000000000..e4b53b8c70c
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/get-commit.ts
@@ -0,0 +1,37 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { encodeSegment, gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps } from '../../common/props';
+import { commitOutputSchema } from '../../output-schemas';
+
+export const getCommitAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_commit',
+ displayName: 'Get Commit',
+ description: 'Gets one commit by SHA, branch or tag.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Returns one GitLab commit (message, author, dates, parent SHAs, line stats, web URL) by SHA or by a branch or tag name, which resolves to its latest commit.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ sha: gitlabProps.sha(),
+ },
+ outputSchema: commitOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabRequest({
+ auth,
+ method: 'GET',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/repository/commits/${encodeSegment({
+ value: propsValue.sha,
+ label: 'Commit SHA',
+ })}`,
+ query: { stats: true },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/get-file.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/get-file.ts
new file mode 100644
index 00000000000..30b9ac6647c
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/get-file.ts
@@ -0,0 +1,117 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { filePathSegment, gitlabToken, projectPath } from '../../common/client';
+import {
+ readGitlabRawPrefix,
+ sendGitlabRequest,
+} from '../../common/secret-request';
+import { gitlabProps, requireText } from '../../common/props';
+import { fileOutputSchema } from '../../output-schemas';
+
+export const MAX_FILE_TEXT_BYTES = 1_000_000;
+
+const UTF8_MAX_CHAR_BYTES = 4;
+
+export function decodeFilePrefix({
+ bytes,
+ complete,
+}: {
+ bytes: Buffer;
+ complete: boolean;
+}): {
+ content: string | null;
+ isBinary: boolean;
+ truncated: boolean;
+} {
+ if (bytes.subarray(0, 8000).includes(0)) {
+ return { content: null, isBinary: true, truncated: false };
+ }
+ const truncated = !complete || bytes.length > MAX_FILE_TEXT_BYTES;
+ let cut = Math.min(bytes.length, MAX_FILE_TEXT_BYTES);
+ if (truncated) {
+ const floor = Math.max(0, cut - (UTF8_MAX_CHAR_BYTES - 1));
+ while (cut > floor && (bytes[cut] & 0xc0) === 0x80) {
+ cut--;
+ }
+ }
+ try {
+ const content = new TextDecoder('utf-8', { fatal: true }).decode(
+ bytes.subarray(0, cut)
+ );
+ return { content, isBinary: false, truncated };
+ } catch {
+ return { content: null, isBinary: true, truncated: false };
+ }
+}
+
+function headerText({
+ headers,
+ name,
+}: {
+ headers: Headers;
+ name: string;
+}): string | null {
+ return headers.get(`x-gitlab-${name}`);
+}
+
+export const getFileAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_file',
+ displayName: 'Get File',
+ description: 'Gets a file from the repository with its decoded text content.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Reads one file from a GitLab repository at a branch, tag or commit and returns its text content plus metadata (size, blob ID, last commit ID). Text over 1 MB is cut (truncated is true); binary files return isBinary true and no content. Pass last_commit_id to Update File to guard against concurrent edits.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ filePath: Property.ShortText({
+ displayName: 'File Path',
+ description: 'Path from the repository root, e.g. src/index.ts.',
+ required: true,
+ }),
+ ref: Property.ShortText({
+ displayName: 'Branch, Tag or Commit',
+ required: true,
+ }),
+ },
+ outputSchema: fileOutputSchema,
+ async run({ auth, propsValue }) {
+ const filePath = `${projectPath(
+ propsValue.projectId
+ )}/repository/files/${filePathSegment(propsValue.filePath)}`;
+ const ref = requireText({
+ value: propsValue.ref,
+ label: 'Branch, Tag or Commit',
+ });
+ const query = { ref };
+ const token = gitlabToken(auth);
+ const meta = await sendGitlabRequest<undefined>({
+ token,
+ method: 'HEAD',
+ path: filePath,
+ query,
+ });
+ const raw = await readGitlabRawPrefix({
+ request: { token, method: 'GET', path: `${filePath}/raw`, query },
+ maxBytes: MAX_FILE_TEXT_BYTES + UTF8_MAX_CHAR_BYTES,
+ });
+ const headers = meta.headers;
+ const sizeHeader = headerText({ headers, name: 'size' });
+ const size = sizeHeader === null ? NaN : Number(sizeHeader);
+ return {
+ file_name: propsValue.filePath.split('/').pop() ?? propsValue.filePath,
+ file_path: propsValue.filePath,
+ size: Number.isFinite(size) ? size : raw.bytes.length,
+ ref,
+ blob_id: headerText({ headers, name: 'blob-id' }),
+ commit_id: headerText({ headers, name: 'commit-id' }),
+ last_commit_id: headerText({ headers, name: 'last-commit-id' }),
+ content_sha256: headerText({ headers, name: 'content-sha256' }),
+ ...decodeFilePrefix(raw),
+ };
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/list-branches.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/list-branches.ts
new file mode 100644
index 00000000000..ce5ccf337f9
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/list-branches.ts
@@ -0,0 +1,34 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import { gitlabProps, optionalText, pagingInput } from '../../common/props';
+import { branchListOutputSchema } from '../../output-schemas';
+
+export const listBranchesAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_branches',
+ displayName: 'List Branches',
+ description: 'Lists or searches the branches of the repository.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists branches of a GitLab repository, optionally filtered by a search term (use ^term or term$ to match the start or end). Returns one page plus nextPage/hasMore.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ search: Property.ShortText({ displayName: 'Search', required: false }),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: branchListOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(propsValue.projectId)}/repository/branches`,
+ query: { search: optionalText(propsValue.search) },
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/list-commit-comments.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/list-commit-comments.ts
new file mode 100644
index 00000000000..3f7e10831fc
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/list-commit-comments.ts
@@ -0,0 +1,42 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import {
+ encodeSegment,
+ gitlabListPage,
+ projectPath,
+} from '../../common/client';
+import { gitlabProps, pagingInput } from '../../common/props';
+import { commitCommentListOutputSchema } from '../../output-schemas';
+
+export const listCommitCommentsAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_commit_comments',
+ displayName: 'List Commit Comments',
+ description: 'Lists the comments on a commit.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists comments on a GitLab commit, including line comments with their file path and line. Returns one page plus nextPage/hasMore.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ sha: gitlabProps.sha(),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: commitCommentListOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(
+ propsValue.projectId
+ )}/repository/commits/${encodeSegment({
+ value: propsValue.sha,
+ label: 'Commit SHA',
+ })}/comments`,
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/list-commits.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/list-commits.ts
new file mode 100644
index 00000000000..9a980c1b9c7
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/list-commits.ts
@@ -0,0 +1,69 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ optionalIsoDate,
+ optionalText,
+ pagingInput,
+} from '../../common/props';
+import { commitListOutputSchema } from '../../output-schemas';
+
+export const listCommitsAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_commits',
+ displayName: 'List Commits',
+ description: 'Lists the commits of a branch, tag or path, newest first.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists commits in a GitLab repository, newest first, optionally limited to a branch or tag, a file path, an author and a date range. Defaults to the default branch. Returns one page plus nextPage/hasMore.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ refName: Property.ShortText({
+ displayName: 'Branch or Tag',
+ description: 'Defaults to the default branch.',
+ required: false,
+ }),
+ path: Property.ShortText({
+ displayName: 'File Path',
+ description: 'Only commits that touch this path.',
+ required: false,
+ }),
+ author: Property.ShortText({
+ displayName: 'Author',
+ description: 'Author name or email.',
+ required: false,
+ }),
+ since: Property.ShortText({
+ displayName: 'Since',
+ description: 'ISO 8601 date-time.',
+ required: false,
+ }),
+ until: Property.ShortText({
+ displayName: 'Until',
+ description: 'ISO 8601 date-time.',
+ required: false,
+ }),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: commitListOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(propsValue.projectId)}/repository/commits`,
+ query: {
+ ref_name: optionalText(propsValue.refName),
+ path: optionalText(propsValue.path),
+ author: optionalText(propsValue.author),
+ since: optionalIsoDate({ value: propsValue.since, label: 'Since' }),
+ until: optionalIsoDate({ value: propsValue.until, label: 'Until' }),
+ },
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/list-repository-tree.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/list-repository-tree.ts
new file mode 100644
index 00000000000..5334ca1c6d5
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/list-repository-tree.ts
@@ -0,0 +1,56 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import {
+ gitlabProps,
+ optionalText,
+ pagingInput,
+ triStateValue,
+} from '../../common/props';
+import { treeListOutputSchema } from '../../output-schemas';
+
+export const listRepositoryTreeAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_repository_tree',
+ displayName: 'List Repository Files',
+ description: 'Lists files and folders in the repository.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists files (blob) and folders (tree) in a GitLab repository at a path and branch/tag/commit, optionally recursively. Returns one page plus nextPage/hasMore. Use Get File to read a file found here.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ path: Property.ShortText({
+ displayName: 'Folder Path',
+ description: 'Defaults to the repository root.',
+ required: false,
+ }),
+ ref: Property.ShortText({
+ displayName: 'Branch, Tag or Commit',
+ description: 'Defaults to the default branch.',
+ required: false,
+ }),
+ recursive: gitlabProps.triState(
+ 'Recursive',
+ 'Include everything below the folder.'
+ ),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: treeListOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(propsValue.projectId)}/repository/tree`,
+ query: {
+ path: optionalText(propsValue.path),
+ ref: optionalText(propsValue.ref),
+ recursive: triStateValue(propsValue.recursive),
+ },
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/list-tags.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/list-tags.ts
new file mode 100644
index 00000000000..0d39c2485cb
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/list-tags.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage, projectPath } from '../../common/client';
+import { gitlabProps, optionalText, pagingInput } from '../../common/props';
+import { tagListOutputSchema } from '../../output-schemas';
+
+export const listTagsAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_tags',
+ displayName: 'List Tags',
+ description: 'Lists or searches the tags of the repository.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Lists tags of a GitLab repository with their commit and release notes, optionally filtered by a search term (^term or term$ match the start or end). Returns one page plus nextPage/hasMore.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ search: Property.ShortText({ displayName: 'Search', required: false }),
+ orderBy: Property.StaticDropdown({
+ displayName: 'Order By',
+ required: false,
+ options: {
+ options: [
+ { label: 'Updated', value: 'updated' },
+ { label: 'Name', value: 'name' },
+ { label: 'Version', value: 'version' },
+ ],
+ },
+ }),
+ sort: gitlabProps.sort(),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: tagListOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabListPage({
+ auth,
+ path: `${projectPath(propsValue.projectId)}/repository/tags`,
+ query: {
+ search: optionalText(propsValue.search),
+ order_by: propsValue.orderBy,
+ sort: propsValue.sort,
+ },
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/protect-branch.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/protect-branch.ts
new file mode 100644
index 00000000000..c9eb0569f1a
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/protect-branch.ts
@@ -0,0 +1,65 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest, projectPath } from '../../common/client';
+import { gitlabProps, requireText, triStateValue } from '../../common/props';
+import { protectedBranchOutputSchema } from '../../output-schemas';
+
+const accessLevel = (displayName: string) =>
+ Property.StaticDropdown<number>({
+ displayName,
+ description: 'Leave empty for the GitLab default (Maintainers).',
+ required: false,
+ options: {
+ options: [
+ { label: 'No one', value: 0 },
+ { label: 'Developers and Maintainers', value: 30 },
+ { label: 'Maintainers', value: 40 },
+ ],
+ },
+ });
+
+export const protectBranchAction = createAction({
+ auth: gitlabAuth,
+ name: 'protect_branch',
+ displayName: 'Protect Branch',
+ description: 'Protects a branch or wildcard pattern.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ 'Protects a GitLab branch name or wildcard (e.g. release/*) and sets who may push and merge. Requires Maintainer role. GitLab answers 409 if it is already protected, so a second call fails; undo with Unprotect Branch.',
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ name: Property.ShortText({
+ displayName: 'Branch or Pattern',
+ description: 'Branch name or wildcard such as release/*.',
+ required: true,
+ }),
+ pushAccessLevel: accessLevel('Allowed to Push'),
+ mergeAccessLevel: accessLevel('Allowed to Merge'),
+ allowForcePush: gitlabProps.triState(
+ 'Allow Force Push',
+ 'Leave empty for the GitLab default (no).'
+ ),
+ },
+ outputSchema: protectedBranchOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabRequest({
+ auth,
+ method: 'POST',
+ path: `${projectPath(propsValue.projectId)}/protected_branches`,
+ body: {
+ name: requireText({
+ value: propsValue.name,
+ label: 'Branch or Pattern',
+ }),
+ push_access_level: propsValue.pushAccessLevel ?? undefined,
+ merge_access_level: propsValue.mergeAccessLevel ?? undefined,
+ allow_force_push: triStateValue(propsValue.allowForcePush),
+ },
+ statusMessages: { 409: 'This branch or pattern is already protected' },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/unprotect-branch.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/unprotect-branch.ts
new file mode 100644
index 00000000000..feb66acb8b4
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/unprotect-branch.ts
@@ -0,0 +1,53 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { encodeSegment, gitlabRequest, projectPath } from '../../common/client';
+import { GitlabApiError } from '../../common/secret-request';
+import { gitlabProps, requireText } from '../../common/props';
+import { unprotectedBranchOutputSchema } from '../../output-schemas';
+
+export const unprotectBranchAction = createAction({
+ auth: gitlabAuth,
+ name: 'unprotect_branch',
+ displayName: 'Unprotect Branch',
+ description: 'Removes the protection from a branch or pattern.',
+ audience: 'ai',
+ classification: 'DESTRUCTIVE',
+ aiMetadata: {
+ description:
+ 'Removes branch protection from a GitLab branch name or wildcard, so anyone with Developer role can push, force-push or delete it. Requires Maintainer role. If the branch is not protected the call succeeds with alreadyUnprotected true.',
+ idempotent: true,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ name: Property.ShortText({
+ displayName: 'Branch or Pattern',
+ description: 'Exactly as it was protected, e.g. release/*.',
+ required: true,
+ }),
+ },
+ outputSchema: unprotectedBranchOutputSchema,
+ async run({ auth, propsValue }) {
+ const name = requireText({
+ value: propsValue.name,
+ label: 'Branch or Pattern',
+ });
+ try {
+ await gitlabRequest({
+ auth,
+ method: 'DELETE',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/protected_branches/${encodeSegment({
+ value: name,
+ label: 'Branch or Pattern',
+ })}`,
+ });
+ return { unprotected: true, alreadyUnprotected: false, name };
+ } catch (error) {
+ if (error instanceof GitlabApiError && error.status === 404) {
+ return { unprotected: true, alreadyUnprotected: true, name };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/repository/update-file.ts b/packages/pieces/community/gitlab/src/lib/actions/repository/update-file.ts
new file mode 100644
index 00000000000..080eb22daf5
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/repository/update-file.ts
@@ -0,0 +1,96 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import {
+ filePathSegment,
+ gitlabRequest,
+ projectPath,
+} from '../../common/client';
+import { gitlabProps, optionalText, requireText } from '../../common/props';
+import { fileCommitOutputSchema } from '../../output-schemas';
+
+export const updateFileAction = createAction({
+ auth: gitlabAuth,
+ name: 'update_file',
+ displayName: 'Update File',
+ description: 'Replaces the content of an existing file with a commit.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ "Replaces the whole content of an existing file on a branch of a GitLab repository as one commit. Pass Last Commit ID (from Get File) to fail instead of overwriting someone else's newer change. Not idempotent: each call makes a new commit.",
+ idempotent: false,
+ },
+ props: {
+ projectId: gitlabProps.projectId(),
+ filePath: Property.ShortText({
+ displayName: 'File Path',
+ description: 'Path from the repository root, e.g. docs/readme.md.',
+ required: true,
+ }),
+ branch: gitlabProps.branch(
+ 'Branch',
+ 'Branch to commit to. It must exist unless Start Branch is set.'
+ ),
+ content: Property.LongText({ displayName: 'Content', required: true }),
+ commitMessage: Property.ShortText({
+ displayName: 'Commit Message',
+ required: true,
+ }),
+ encoding: Property.StaticDropdown({
+ displayName: 'Content Encoding',
+ required: false,
+ defaultValue: 'text',
+ options: {
+ options: [
+ { label: 'Text', value: 'text' },
+ { label: 'Base64', value: 'base64' },
+ ],
+ },
+ }),
+ startBranch: Property.ShortText({
+ displayName: 'Start Branch',
+ description: 'Create Branch from this branch first.',
+ required: false,
+ }),
+ lastCommitId: Property.ShortText({
+ displayName: 'Last Commit ID',
+ description:
+ 'last_commit_id from Get File. The update fails if the file changed since.',
+ required: false,
+ }),
+ authorName: Property.ShortText({
+ displayName: 'Author Name',
+ required: false,
+ }),
+ authorEmail: Property.ShortText({
+ displayName: 'Author Email',
+ required: false,
+ }),
+ },
+ outputSchema: fileCommitOutputSchema,
+ async run({ auth, propsValue }) {
+ if (typeof propsValue.content !== 'string') {
+ throw new Error('Content is required.');
+ }
+ return gitlabRequest({
+ auth,
+ method: 'PUT',
+ path: `${projectPath(
+ propsValue.projectId
+ )}/repository/files/${filePathSegment(propsValue.filePath)}`,
+ body: {
+ branch: requireText({ value: propsValue.branch, label: 'Branch' }),
+ content: propsValue.content,
+ commit_message: requireText({
+ value: propsValue.commitMessage,
+ label: 'Commit Message',
+ }),
+ encoding: propsValue.encoding ?? 'text',
+ start_branch: optionalText(propsValue.startBranch),
+ last_commit_id: optionalText(propsValue.lastCommitId),
+ author_name: optionalText(propsValue.authorName),
+ author_email: optionalText(propsValue.authorEmail),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/users/get-current-user.ts b/packages/pieces/community/gitlab/src/lib/actions/users/get-current-user.ts
new file mode 100644
index 00000000000..d50d06cd834
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/users/get-current-user.ts
@@ -0,0 +1,23 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest } from '../../common/client';
+import { currentUserOutputSchema } from '../../output-schemas';
+
+export const getCurrentUserAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_current_user',
+ displayName: 'Get Current User',
+ description: 'Gets the GitLab user the connection belongs to.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ 'Returns the GitLab user the connection authenticates as (ID, username, name, email, state, web URL). Use it to learn your own user ID for assignee, reviewer or author filters, or to confirm the connection works.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: currentUserOutputSchema,
+ async run({ auth }) {
+ return gitlabRequest({ auth, method: 'GET', path: '/user' });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/users/get-user-status.ts b/packages/pieces/community/gitlab/src/lib/actions/users/get-user-status.ts
new file mode 100644
index 00000000000..bb34d06e9ee
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/users/get-user-status.ts
@@ -0,0 +1,41 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { encodeSegment, gitlabRequest } from '../../common/client';
+import { optionalText } from '../../common/props';
+import { userStatusOutputSchema } from '../../output-schemas';
+
+export const getUserStatusAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_user_status',
+ displayName: 'Get User Status',
+ description: 'Gets the status (emoji, message, availability) of a user.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ "Returns a GitLab user's status: emoji, message, availability (busy or not set) and when it clears. Leave User empty for the connected user, or pass a numeric ID or username.",
+ idempotent: true,
+ },
+ props: {
+ user: Property.ShortText({
+ displayName: 'User ID or Username',
+ description: 'Leave empty for the connected user.',
+ required: false,
+ }),
+ },
+ outputSchema: userStatusOutputSchema,
+ async run({ auth, propsValue }) {
+ const user = optionalText(propsValue.user)?.replace(/^@/, '');
+ return gitlabRequest({
+ auth,
+ method: 'GET',
+ path:
+ user === undefined
+ ? '/user/status'
+ : `/users/${encodeSegment({
+ value: user,
+ label: 'User ID or Username',
+ })}/status`,
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/users/get-user.ts b/packages/pieces/community/gitlab/src/lib/actions/users/get-user.ts
new file mode 100644
index 00000000000..32f7f34dd8e
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/users/get-user.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest } from '../../common/client';
+import { requirePositiveInt } from '../../common/props';
+import { userOutputSchema } from '../../output-schemas';
+
+export const getUserAction = createAction({
+ auth: gitlabAuth,
+ name: 'get_user',
+ displayName: 'Get User',
+ description: 'Gets a user by numeric ID.',
+ audience: 'ai',
+ classification: 'READ',
+ aiMetadata: {
+ description:
+ "Returns a GitLab user's public profile by numeric user ID. To look a user up by username, use List Users with the Username filter instead.",
+ idempotent: true,
+ },
+ props: {
+ userId: Property.Number({
+ displayName: 'User ID',
+ description: 'Numeric user ID. Usernames are not accepted here.',
+ required: true,
+ }),
+ },
+ outputSchema: userOutputSchema,
+ async run({ auth, propsValue }) {
+ return gitlabRequest({
+ auth,
+ method: 'GET',
+ path: `/users/${requirePositiveInt({
+ value: propsValue.userId,
+ label: 'User ID',
+ })}`,
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/users/list-users.ts b/packages/pieces/community/gitlab/src/lib/actions/users/list-users.ts
new file mode 100644
index 00000000000..9b41d617d7a
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/users/list-users.ts
@@ -0,0 +1,47 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabListPage } from '../../common/client';
+import { gitlabProps, optionalText, pagingInput } from '../../common/props';
+import { userListOutputSchema } from '../../output-schemas';
+
+export const listUsersAction = createAction({
+ auth: gitlabAuth,
+ name: 'list_users',
+ displayName: 'List Users',
+ description: 'Searches users by name, username or public email.',
+ audience: 'ai',
+ classification: 'SEARCH',
+ aiMetadata: {
+ description:
+ 'Searches GitLab users by name, username or public email, or finds one user by exact username. Use it to turn a username into the numeric user ID other actions need. Set Search or Username: without either gitlab.com returns an unhelpful list of arbitrary users. Returns one page plus nextPage/hasMore.',
+ idempotent: true,
+ },
+ props: {
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: 'Name, username or public email.',
+ required: false,
+ }),
+ username: Property.ShortText({
+ displayName: 'Username',
+ description: 'Exact username, without @.',
+ required: false,
+ }),
+ page: gitlabProps.page(),
+ perPage: gitlabProps.perPage(),
+ },
+ outputSchema: userListOutputSchema,
+ async run({ auth, propsValue }) {
+ const search = optionalText(propsValue.search);
+ const username = optionalText(propsValue.username)?.replace(/^@/, '');
+ if (search === undefined && username === undefined) {
+ throw new Error('Set Search or Username.');
+ }
+ return gitlabListPage({
+ auth,
+ path: '/users',
+ query: { search, username },
+ ...pagingInput({ page: propsValue.page, perPage: propsValue.perPage }),
+ });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/actions/users/set-user-status.ts b/packages/pieces/community/gitlab/src/lib/actions/users/set-user-status.ts
new file mode 100644
index 00000000000..e696d4c5d3b
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/actions/users/set-user-status.ts
@@ -0,0 +1,111 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { gitlabAuth } from '../../auth';
+import { gitlabRequest } from '../../common/client';
+import { GitlabUserStatus } from '../../common/models';
+import { optionalText } from '../../common/props';
+import { userStatusOutputSchema } from '../../output-schemas';
+
+export const setUserStatusAction = createAction({
+ auth: gitlabAuth,
+ name: 'set_user_status',
+ displayName: 'Set User Status',
+ description:
+ 'Sets the status of the connected user. Fields left empty keep their current value.',
+ audience: 'ai',
+ classification: 'WRITE',
+ aiMetadata: {
+ description:
+ "Sets the connected GitLab user's status emoji, message, availability and auto-clear time. Fields you leave empty keep their current value (the action reads the status first and merges); use Clear Message, Clear Emoji or Clear Whole Status to blank them. GitLab shows the speech_balloon emoji when a message has no emoji, and any earlier auto-clear time is removed unless Clear Status After is set again.",
+ idempotent: true,
+ },
+ props: {
+ message: Property.ShortText({
+ displayName: 'Message',
+ description: 'Up to 100 characters.',
+ required: false,
+ }),
+ clearMessage: Property.Checkbox({
+ displayName: 'Clear Message',
+ required: false,
+ defaultValue: false,
+ }),
+ emoji: Property.ShortText({
+ displayName: 'Emoji',
+ description: 'Emoji name without colons, e.g. coffee or palm_tree.',
+ required: false,
+ }),
+ clearEmoji: Property.Checkbox({
+ displayName: 'Clear Emoji',
+ required: false,
+ defaultValue: false,
+ }),
+ availability: Property.StaticDropdown({
+ displayName: 'Availability',
+ required: false,
+ options: {
+ options: [
+ { label: 'Busy', value: 'busy' },
+ { label: 'Not set', value: 'not_set' },
+ ],
+ },
+ }),
+ clearStatusAfter: Property.StaticDropdown({
+ displayName: 'Clear Status After',
+ required: false,
+ options: {
+ options: [
+ { label: '30 minutes', value: '30_minutes' },
+ { label: '3 hours', value: '3_hours' },
+ { label: '8 hours', value: '8_hours' },
+ { label: '1 day', value: '1_day' },
+ { label: '3 days', value: '3_days' },
+ { label: '7 days', value: '7_days' },
+ { label: '30 days', value: '30_days' },
+ ],
+ },
+ }),
+ clearAll: Property.Checkbox({
+ displayName: 'Clear Whole Status',
+ description:
+ 'Removes message, emoji and availability. Other fields are ignored.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: userStatusOutputSchema,
+ async run({ auth, propsValue }) {
+ if (propsValue.clearAll === true) {
+ await gitlabRequest({
+ auth,
+ method: 'PUT',
+ path: '/user/status',
+ body: { emoji: '', message: '', availability: 'not_set' },
+ });
+ return gitlabRequest({ auth, method: 'GET', path: '/user/status' });
+ }
+ const message = optionalText(propsValue.message);
+ if (message !== undefined && message.length > 100) {
+ throw new Error('Message can be at most 100 characters.');
+ }
+ const emoji = optionalText(propsValue.emoji)?.replace(/^:|:$/g, '');
+ const current = await gitlabRequest<GitlabUserStatus>({
+ auth,
+ method: 'GET',
+ path: '/user/status',
+ });
+ const body: Record<string, unknown> = {
+ message:
+ propsValue.clearMessage === true
+ ? ''
+ : message ?? current?.message ?? '',
+ emoji:
+ propsValue.clearEmoji === true ? '' : emoji ?? current?.emoji ?? '',
+ availability:
+ propsValue.availability ?? current?.availability ?? 'not_set',
+ };
+ if (propsValue.clearStatusAfter) {
+ body['clear_status_after'] = propsValue.clearStatusAfter;
+ }
+ return gitlabRequest({ auth, method: 'PUT', path: '/user/status', body });
+ },
+});
diff --git a/packages/pieces/community/gitlab/src/lib/auth.test.ts b/packages/pieces/community/gitlab/src/lib/auth.test.ts
index d6791d622c8..47a346cc863 100644
--- a/packages/pieces/community/gitlab/src/lib/auth.test.ts
+++ b/packages/pieces/community/gitlab/src/lib/auth.test.ts
@@ -2,14 +2,22 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { httpClient } from '@activepieces/pieces-common';
import { gitlabAuth } from './auth';
-const server = { apiUrl: 'http://127.0.0.1:4200/api/', publicUrl: 'http://127.0.0.1:4200/api/' };
+const server = {
+ apiUrl: 'http://127.0.0.1:4200/api/',
+ publicUrl: 'http://127.0.0.1:4200/api/',
+};
function resolveIdentifier() {
- return gitlabAuth.getConnectionIdentifier?.({ auth: { access_token: 'token', data: {} }, server });
+ return gitlabAuth.getConnectionIdentifier?.({
+ auth: { access_token: 'token', data: {} },
+ server,
+ });
}
function mockCurrentUser(body: unknown) {
- return vi.spyOn(httpClient, 'sendRequest').mockResolvedValue({ status: 200, headers: {}, body });
+ return vi
+ .spyOn(httpClient, 'sendRequest')
+ .mockResolvedValue({ status: 200, headers: {}, body });
}
describe('gitlabAuth.getConnectionIdentifier', () => {
@@ -18,14 +26,17 @@ describe('gitlabAuth.getConnectionIdentifier', () => {
});
it('returns the email of the user GitLab says the token belongs to', async () => {
- const sendRequest = mockCurrentUser({ email: '[email protected]', username: 'dev' });
+ const sendRequest = mockCurrentUser({
+ email: '[email protected]',
+ username: 'dev',
+ });
expect(await resolveIdentifier()).toBe('[email protected]');
expect(sendRequest).toHaveBeenCalledWith(
expect.objectContaining({
url: 'https://gitlab.com/api/v4/user',
headers: { Authorization: 'Bearer token' },
- }),
+ })
);
});
@@ -36,7 +47,9 @@ describe('gitlabAuth.getConnectionIdentifier', () => {
});
it('returns undefined instead of throwing when the API call fails', async () => {
- vi.spyOn(httpClient, 'sendRequest').mockRejectedValue(new Error('401 Unauthorized'));
+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue(
+ new Error('401 Unauthorized')
+ );
expect(await resolveIdentifier()).toBeUndefined();
});
diff --git a/packages/pieces/community/gitlab/src/lib/auth.ts b/packages/pieces/community/gitlab/src/lib/auth.ts
index 9dd06da52cb..980162eb762 100644
--- a/packages/pieces/community/gitlab/src/lib/auth.ts
+++ b/packages/pieces/community/gitlab/src/lib/auth.ts
@@ -1,5 +1,6 @@
import { PieceAuth } from '@activepieces/pieces-framework';
import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { GITLAB_API_BASE } from './common/constants';
export const gitlabAuth = PieceAuth.OAuth2({
required: true,
@@ -8,9 +9,12 @@ export const gitlabAuth = PieceAuth.OAuth2({
scope: ['api', 'read_user'],
getConnectionIdentifier: async ({ auth }) => {
try {
- const response = await httpClient.sendRequest<{ email?: string; username?: string }>({
+ const response = await httpClient.sendRequest<{
+ email?: string;
+ username?: string;
+ }>({
method: HttpMethod.GET,
- url: 'https://gitlab.com/api/v4/user',
+ url: `${GITLAB_API_BASE}/user`,
headers: { Authorization: `Bearer ${auth.access_token}` },
timeout: 5000,
});
diff --git a/packages/pieces/community/gitlab/src/lib/common/client.ts b/packages/pieces/community/gitlab/src/lib/common/client.ts
index 2e9fdebd816..f98a5035666 100644
--- a/packages/pieces/community/gitlab/src/lib/common/client.ts
+++ b/packages/pieces/community/gitlab/src/lib/common/client.ts
@@ -1,96 +1,122 @@
+import { getAccessTokenOrThrow } from '@activepieces/pieces-common';
+import { OAuth2PropertyValue } from '@activepieces/pieces-framework';
import {
- AuthenticationType,
- HttpMessageBody,
- HttpMethod,
- QueryParams,
- httpClient,
-} from '@activepieces/pieces-common';
-import {
- ListProjectsRequest,
- CreateProjectIssueRequest,
- GitlabProject,
- ProjectWebhookRequest,
- ProjectWebhook,
-} from './models';
-export class GitlabApi {
- constructor(private accessToken: string) {}
+ GitlabQueryValue,
+ GitlabRequest,
+ sendGitlabRequest,
+} from './secret-request';
- async makeRequest<T extends HttpMessageBody>(
- method: HttpMethod,
- url: string,
- query?: QueryParams,
- body?: object
- ): Promise<T> {
- const res = await httpClient.sendRequest<T>({
- method,
- url: 'https://gitlab.com/api/v4' + url,
- queryParams: query,
- body,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: this.accessToken,
- },
- });
- return res.body;
- }
- async listProjects(request: ListProjectsRequest) {
- return this.makeRequest<GitlabProject[]>(
- HttpMethod.GET,
- '/projects',
- prepareQuery(request)
- );
+export type GitlabAuthValue = OAuth2PropertyValue;
+
+export type GitlabCall = Omit<GitlabRequest, 'token'>;
+
+export type GitlabPage<T> = {
+ items: T[];
+ count: number;
+ page: number;
+ nextPage: number | null;
+ hasMore: boolean;
+ total: number | null;
+};
+
+export function gitlabToken(auth: GitlabAuthValue): string {
+ return getAccessTokenOrThrow(auth);
+}
+
+export function encodeSegment({
+ value,
+ label,
+}: {
+ value: string | number;
+ label: string;
+}): string {
+ const text = String(value).trim();
+ if (text.length === 0) {
+ throw new Error(`${label} is required.`);
}
- async createProjectIssue(
- projectId: string,
- request: CreateProjectIssueRequest
- ) {
- return this.makeRequest(
- HttpMethod.POST,
- `/projects/${projectId}/issues`,
- undefined,
- request
- );
+ if (text === '.' || text === '..') {
+ throw new Error(`${label} is not valid.`);
}
- async subscribeProjectWebhook(
- projectId: string,
- request: ProjectWebhookRequest
- ) {
- return this.makeRequest<ProjectWebhook>(
- HttpMethod.POST,
- `/projects/${projectId}/hooks`,
- undefined,
- request
- );
+ return encodeURIComponent(text);
+}
+
+export function filePathSegment(value: unknown): string {
+ if (typeof value !== 'string' || value.trim().length === 0) {
+ throw new Error('File Path is required.');
}
- async unsubscribeProjectWebhook(projectId: string, webhookId: string) {
- return this.makeRequest(
- HttpMethod.DELETE,
- `/projects/${projectId}/hooks/${webhookId}`,
- undefined
- );
+ if (value === '.' || value === '..') {
+ throw new Error('File Path is not valid.');
}
+ return encodeURIComponent(value);
}
-function emptyValueFilter(
- accessor: (key: string) => any
-): (key: string) => boolean {
- return (key: string) => {
- const val = accessor(key);
- return (
- val !== null &&
- val !== undefined &&
- (typeof val != 'string' || val.length > 0)
- );
- };
+export function projectPath(projectId: string | number): string {
+ return `/projects/${encodeSegment({
+ value: projectId,
+ label: 'Project ID or path',
+ })}`;
+}
+
+export async function gitlabRequest<T>({
+ auth,
+ ...call
+}: GitlabCall & { auth: GitlabAuthValue }): Promise<T> {
+ const response = await sendGitlabRequest<T>({
+ ...call,
+ token: gitlabToken(auth),
+ });
+ return response.body;
}
-export function prepareQuery(request?: Record<string, any>): QueryParams {
- const params: QueryParams = {};
- if (!request) return params;
- Object.keys(request)
- .filter(emptyValueFilter((k) => request[k]))
- .forEach((k: string) => {
- params[k] = (request as Record<string, any>)[k].toString();
- });
- return params;
+function headerInt({
+ headers,
+ name,
+}: {
+ headers: Headers;
+ name: string;
+}): number | null {
+ const raw = headers.get(name);
+ if (raw === null || raw.trim() === '') {
+ return null;
+ }
+ const parsed = Number(raw);
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
+}
+
+export async function gitlabListPage<T>({
+ auth,
+ path,
+ query,
+ page,
+ perPage,
+ statusMessages,
+}: {
+ auth: GitlabAuthValue;
+ path: string;
+ query?: Record<string, GitlabQueryValue>;
+ page?: number;
+ perPage?: number;
+ statusMessages?: Partial<Record<number, string>>;
+}): Promise<GitlabPage<T>> {
+ const currentPage = page ?? 1;
+ const response = await sendGitlabRequest<T[]>({
+ token: gitlabToken(auth),
+ method: 'GET',
+ path,
+ query: { ...query, page: currentPage, per_page: perPage ?? 20 },
+ statusMessages,
+ });
+ const items = Array.isArray(response.body) ? response.body : [];
+ const nextPage = headerInt({
+ headers: response.headers,
+ name: 'x-next-page',
+ });
+ return {
+ items,
+ count: items.length,
+ page: currentPage,
+ nextPage,
+ hasMore: nextPage !== null,
+ total: headerInt({ headers: response.headers, name: 'x-total' }),
+ };
}
diff --git a/packages/pieces/community/gitlab/src/lib/common/constants.ts b/packages/pieces/community/gitlab/src/lib/common/constants.ts
new file mode 100644
index 00000000000..b236af44113
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/common/constants.ts
@@ -0,0 +1 @@
+export const GITLAB_API_BASE = 'https://gitlab.com/api/v4';
diff --git a/packages/pieces/community/gitlab/src/lib/common/index.ts b/packages/pieces/community/gitlab/src/lib/common/index.ts
index cab36824926..3b5094575f6 100644
--- a/packages/pieces/community/gitlab/src/lib/common/index.ts
+++ b/packages/pieces/community/gitlab/src/lib/common/index.ts
@@ -1,7 +1,50 @@
-import { getAccessTokenOrThrow } from '@activepieces/pieces-common';
-import { OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';
-import { GitlabApi } from './client';
+import { Property } from '@activepieces/pieces-framework';
import { gitlabAuth } from '../auth';
+import { GitlabAuthValue, gitlabListPage } from './client';
+import { GitlabProjectSummary } from './models';
+
+export const PROJECT_DROPDOWN_PAGE_CAP = 10;
+
+export async function listProjectOptions({
+ auth,
+ searchValue,
+}: {
+ auth: GitlabAuthValue;
+ searchValue?: string;
+}): Promise<{
+ options: { label: string; value: number }[];
+ truncated: boolean;
+}> {
+ const options: { label: string; value: number }[] = [];
+ const search = searchValue?.trim();
+ let page: number | null = 1;
+ let fetched = 0;
+ while (page !== null && fetched < PROJECT_DROPDOWN_PAGE_CAP) {
+ const result: Awaited<
+ ReturnType<typeof gitlabListPage<GitlabProjectSummary>>
+ > = await gitlabListPage<GitlabProjectSummary>({
+ auth,
+ path: '/projects',
+ query: {
+ simple: true,
+ membership: true,
+ order_by: 'last_activity_at',
+ search: search || undefined,
+ },
+ page,
+ perPage: 100,
+ });
+ for (const project of result.items) {
+ options.push({
+ label: project.name_with_namespace ?? project.name,
+ value: project.id,
+ });
+ }
+ fetched += 1;
+ page = result.nextPage;
+ }
+ return { options, truncated: page !== null };
+}
export const gitlabCommon = {
projectId: (required = true) =>
@@ -10,7 +53,8 @@ export const gitlabCommon = {
displayName: 'Project',
required,
refreshers: [],
- options: async ({ auth }) => {
+ refreshOnSearch: true,
+ options: async ({ auth }, { searchValue }) => {
if (!auth) {
return {
disabled: true,
@@ -18,29 +62,27 @@ export const gitlabCommon = {
options: [],
};
}
- const client = makeClient({
- auth: auth,
- });
- const res = await client.listProjects({
- simple: true,
- membership: true,
- });
- return {
- disabled: false,
- options: res.map((project) => {
- return {
- label: project.name,
- value: project.id,
- };
- }),
- };
+ try {
+ const { options, truncated } = await listProjectOptions({
+ auth,
+ searchValue,
+ });
+ return {
+ disabled: false,
+ options,
+ placeholder: truncated
+ ? 'Showing your most recently active projects. Type to search for others.'
+ : undefined,
+ };
+ } catch (error) {
+ return {
+ disabled: true,
+ placeholder: `Could not load projects: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ options: [],
+ };
+ }
},
}),
};
-
-export function makeClient(propsValue: {
- auth: OAuth2PropertyValue;
-}): GitlabApi {
- const token = getAccessTokenOrThrow(propsValue.auth);
- return new GitlabApi(token);
-}
diff --git a/packages/pieces/community/gitlab/src/lib/common/irreversible.ts b/packages/pieces/community/gitlab/src/lib/common/irreversible.ts
new file mode 100644
index 00000000000..52fe42189b5
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/common/irreversible.ts
@@ -0,0 +1,39 @@
+import { GitlabAuthValue, gitlabRequest, projectPath } from './client';
+
+export async function resetIssueSpentTime<T>({
+ auth,
+ projectId,
+ issueIid,
+}: {
+ auth: GitlabAuthValue;
+ projectId: string | number;
+ issueIid: number;
+}): Promise<T> {
+ return gitlabRequest<T>({
+ auth,
+ method: 'POST',
+ path: `${projectPath(projectId)}/issues/${issueIid}/reset_spent_time`,
+ });
+}
+
+export async function mergeMergeRequest<T>({
+ auth,
+ projectId,
+ mergeRequestIid,
+ body,
+ statusMessages,
+}: {
+ auth: GitlabAuthValue;
+ projectId: string | number;
+ mergeRequestIid: number;
+ body: Record<string, unknown>;
+ statusMessages: Partial<Record<number, string>>;
+}): Promise<T> {
+ return gitlabRequest<T>({
+ auth,
+ method: 'PUT',
+ path: `${projectPath(projectId)}/merge_requests/${mergeRequestIid}/merge`,
+ body,
+ statusMessages,
+ });
+}
diff --git a/packages/pieces/community/gitlab/src/lib/common/models.ts b/packages/pieces/community/gitlab/src/lib/common/models.ts
index 788ff717f9d..c78e6364aec 100644
--- a/packages/pieces/community/gitlab/src/lib/common/models.ts
+++ b/packages/pieces/community/gitlab/src/lib/common/models.ts
@@ -1,57 +1,45 @@
-export interface ListProjectsRequest {
- membership?: boolean;
- simple?: boolean;
-}
-export interface ProjectWebhookRequest {
+export type ProjectWebhookRequest = {
url: string;
- confidential_issues_events?: boolean;
- confidential_note_events?: boolean;
- deployment_events?: boolean;
- enable_ssl_verification?: boolean;
+ token?: string;
issues_events?: boolean;
- job_events?: boolean;
- merge_requests_events?: boolean;
- note_events?: boolean;
- pipeline_events?: boolean;
- push_events_branch_filter?: string;
+ confidential_issues_events?: boolean;
push_events?: boolean;
- releases_events?: boolean;
- tag_push_events?: boolean;
- wiki_page_events?: boolean;
- token?: boolean;
-}
-export interface CreateProjectIssueRequest {
- title: string;
- description?: string;
-}
-export interface ProjectWebhook {
- id: string;
-}
-export interface GitlabProject {
- id: string;
- description?: string;
+ enable_ssl_verification?: boolean;
+};
+
+export type ProjectWebhook = {
+ id: number;
+ url: string;
+};
+
+export type GitlabProjectSummary = {
+ id: number;
name: string;
- name_with_namespace: string;
- path: string;
+ name_with_namespace?: string;
path_with_namespace: string;
- created_at: string;
- default_branch: string;
- tag_list?: string[];
- topics?: string[];
- ssh_url_to_repo: string;
- http_url_to_repo: string;
+};
+
+export type GitlabIssue = {
+ id: number;
+ iid: number;
+ project_id: number;
+ title: string;
web_url: string;
- avatar_url?: string;
- star_count: number;
- last_activity_at: string;
- namespace: {
- id: number;
- name: string;
- path: string;
- kind: string;
- full_path: string;
- parent_id?: string;
- avatar_url?: string;
- web_url: string;
- };
-}
+};
+
+export type GitlabNote = {
+ id: number;
+ body: string;
+};
+
+export type GitlabUserStatus = {
+ emoji: string | null;
+ message: string | null;
+ availability: string | null;
+ clear_status_at: string | null;
+};
+
+export type GitlabDiff = {
+ diff?: string;
+ [key: string]: unknown;
+};
diff --git a/packages/pieces/community/gitlab/src/lib/common/props.ts b/packages/pieces/community/gitlab/src/lib/common/props.ts
new file mode 100644
index 00000000000..12b4765a98b
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/common/props.ts
@@ -0,0 +1,217 @@
+import { Property } from '@activepieces/pieces-framework';
+
+export const gitlabProps = {
+ projectId: (
+ description = 'Numeric project ID or full path, e.g. `my-group/my-project`. Shown on the project overview page.'
+ ) =>
+ Property.ShortText({
+ displayName: 'Project ID or Path',
+ description,
+ required: true,
+ }),
+ issueIid: () =>
+ Property.Number({
+ displayName: 'Issue IID',
+ description:
+ 'The issue number inside the project (the `iid`, shown as #12 in GitLab), not the global issue ID.',
+ required: true,
+ }),
+ mergeRequestIid: () =>
+ Property.Number({
+ displayName: 'Merge Request IID',
+ description:
+ 'The merge request number inside the project (the `iid`, shown as !12 in GitLab), not the global ID.',
+ required: true,
+ }),
+ noteId: () =>
+ Property.Number({
+ displayName: 'Note ID',
+ description: 'Numeric ID of the comment (note).',
+ required: true,
+ }),
+ sha: (displayName = 'Commit SHA') =>
+ Property.ShortText({
+ displayName,
+ description:
+ 'Commit SHA, or a branch or tag name that resolves to a commit.',
+ required: true,
+ }),
+ branch: (displayName = 'Branch', description = 'Branch name.') =>
+ Property.ShortText({ displayName, description, required: true }),
+ page: () =>
+ Property.Number({
+ displayName: 'Page',
+ description:
+ 'Page number to fetch, starting at 1. Use `nextPage` from the previous result to continue.',
+ required: false,
+ }),
+ perPage: () =>
+ Property.Number({
+ displayName: 'Per Page',
+ description: 'Items per page, 1 to 100. Defaults to 20.',
+ required: false,
+ }),
+ sort: () =>
+ Property.StaticDropdown({
+ displayName: 'Sort',
+ required: false,
+ options: {
+ options: [
+ { label: 'Descending', value: 'desc' },
+ { label: 'Ascending', value: 'asc' },
+ ],
+ },
+ }),
+ triState: (displayName: string, description: string) =>
+ Property.StaticDropdown<string>({
+ displayName,
+ description,
+ required: false,
+ options: {
+ options: [
+ { label: 'Yes', value: 'true' },
+ { label: 'No', value: 'false' },
+ ],
+ },
+ }),
+};
+
+export function requirePositiveInt({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): number {
+ const parsed =
+ typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed <= 0) {
+ throw new Error(`${label} must be a positive whole number.`);
+ }
+ return parsed;
+}
+
+export function optionalPositiveInt({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ return requirePositiveInt({ value, label });
+}
+
+export function pagingInput({
+ page,
+ perPage,
+}: {
+ page: unknown;
+ perPage: unknown;
+}): { page?: number; perPage?: number } {
+ const pageNumber = optionalPositiveInt({ value: page, label: 'Page' });
+ const size = optionalPositiveInt({ value: perPage, label: 'Per Page' });
+ if (size !== undefined && size > 100) {
+ throw new Error('Per Page must be between 1 and 100.');
+ }
+ return { page: pageNumber, perPage: size };
+}
+
+export function requireText({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): string {
+ if (typeof value !== 'string' || value.trim().length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ return value.trim();
+}
+
+export function optionalText(value: unknown): string | undefined {
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+export function triStateValue(value: unknown): boolean | undefined {
+ if (value === true || value === 'true') {
+ return true;
+ }
+ if (value === false || value === 'false') {
+ return false;
+ }
+ return undefined;
+}
+
+export function stringList({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): string[] | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ if (!Array.isArray(value)) {
+ throw new Error(`${label} must be a list.`);
+ }
+ const items = value
+ .map((item) => String(item).trim())
+ .filter((item) => item.length > 0);
+ return items.length > 0 ? items : undefined;
+}
+
+export function idList({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): number[] | undefined {
+ const items = stringList({ value, label });
+ return items?.map((item) => requirePositiveInt({ value: item, label }));
+}
+
+export function optionalIsoDate({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): string | undefined {
+ const text = optionalText(value);
+ if (text === undefined) {
+ return undefined;
+ }
+ if (Number.isNaN(Date.parse(text))) {
+ throw new Error(
+ `${label} must be an ISO 8601 date, e.g. 2026-10-11 or 2026-10-11T09:00:00Z.`
+ );
+ }
+ return text;
+}
+
+export function requireDuration({
+ value,
+ label,
+}: {
+ value: unknown;
+ label: string;
+}): string {
+ const text = requireText({ value, label });
+ const compact = text.replace(/\s+/g, '');
+ if (compact.length > 32 || !/^(\d+mo|\d+[wdhms])+$/.test(compact)) {
+ throw new Error(
+ `${label} must be a GitLab duration such as 1h30m, 2d or 1w.`
+ );
+ }
+ return compact;
+}
diff --git a/packages/pieces/community/gitlab/src/lib/common/secret-request.ts b/packages/pieces/community/gitlab/src/lib/common/secret-request.ts
new file mode 100644
index 00000000000..990b1bb8092
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/common/secret-request.ts
@@ -0,0 +1,276 @@
+import type { Dispatcher } from 'undici';
+import { GITLAB_API_BASE } from './constants';
+
+const DEFAULT_TIMEOUT_MS = 60_000;
+
+let verifiedTlsAgent: Promise<Dispatcher> | undefined;
+
+function getVerifiedTlsAgent(): Promise<Dispatcher> {
+ verifiedTlsAgent ??= import('undici').then(
+ ({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } })
+ );
+ return verifiedTlsAgent;
+}
+
+export const gitlabTransport = {
+ getDispatcher: getVerifiedTlsAgent,
+};
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+export class GitlabApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({
+ message,
+ status,
+ responseBody,
+ }: {
+ message: string;
+ status: number;
+ responseBody: unknown;
+ }) {
+ super(message);
+ this.name = 'GitlabApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+export function vendorMessage(responseBody: unknown): string | undefined {
+ if (typeof responseBody === 'string') {
+ const trimmed = responseBody.trim();
+ return trimmed.length > 0 ? trimmed.slice(0, 500) : undefined;
+ }
+ if (!isRecord(responseBody)) {
+ return undefined;
+ }
+ const record = responseBody;
+ const raw =
+ record['message'] ?? record['error_description'] ?? record['error'];
+ if (raw === undefined || raw === null) {
+ return undefined;
+ }
+ if (typeof raw === 'string') {
+ return raw;
+ }
+ return JSON.stringify(raw).slice(0, 500);
+}
+
+const DEFAULT_STATUS_MESSAGES: Record<number, string> = {
+ 400: 'GitLab rejected the request as invalid',
+ 401: 'GitLab rejected the access token. Reconnect the GitLab connection',
+ 403: 'The connected GitLab user does not have permission for this operation (check the role on the project or group)',
+ 404: 'GitLab could not find the resource, or the connected user cannot see it',
+ 408: 'GitLab timed out answering the request. Narrow it (for example set a project or more filters) and retry',
+ 405: 'GitLab does not allow this operation on the resource in its current state',
+ 409: 'GitLab reported a conflict with the current state of the resource',
+ 422: 'GitLab could not process the request',
+ 429: 'GitLab rate limit reached. Retry later',
+};
+
+export function buildGitlabError({
+ status,
+ responseBody,
+ statusMessages,
+}: {
+ status: number;
+ responseBody: unknown;
+ statusMessages?: Partial<Record<number, string>>;
+}): GitlabApiError {
+ const base =
+ statusMessages?.[status] ??
+ DEFAULT_STATUS_MESSAGES[status] ??
+ (status >= 500
+ ? 'GitLab returned a server error. Retry later'
+ : 'GitLab request failed');
+ const detail = vendorMessage(responseBody);
+ const message =
+ detail === undefined
+ ? `${base} (HTTP ${status}).`
+ : `${base} (HTTP ${status}): ${detail}`;
+ return new GitlabApiError({ message, status, responseBody });
+}
+
+type JsonValue = ReturnType<typeof JSON.parse>;
+
+export type GitlabQueryValue =
+ | string
+ | number
+ | boolean
+ | undefined
+ | null
+ | Array<string | number>;
+
+export type GitlabRequest = {
+ token: string;
+ method: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE';
+ path: string;
+ query?: Record<string, GitlabQueryValue>;
+ body?: unknown;
+ statusMessages?: Partial<Record<number, string>>;
+ timeoutMs?: number;
+};
+
+export type GitlabResponse<T> = {
+ status: number;
+ headers: Headers;
+ body: T;
+};
+
+export function buildGitlabUrl({
+ path,
+ query,
+}: {
+ path: string;
+ query?: Record<string, GitlabQueryValue>;
+}): string {
+ if (
+ !path.startsWith('/') ||
+ path.startsWith('//') ||
+ path.includes('/../') ||
+ path.endsWith('/..')
+ ) {
+ throw new Error(
+ `Refusing to send a GitLab request to an unexpected path: ${path}`
+ );
+ }
+ const url = new URL(GITLAB_API_BASE + path);
+ if (query) {
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === null || value === '') {
+ continue;
+ }
+ if (Array.isArray(value)) {
+ if (value.length === 0) {
+ continue;
+ }
+ for (const item of value) {
+ url.searchParams.append(`${key}[]`, String(item));
+ }
+ continue;
+ }
+ url.searchParams.set(key, String(value));
+ }
+ }
+ return url.toString();
+}
+
+async function readBody(response: Response): Promise<JsonValue> {
+ if (response.status === 204 || response.body === null) {
+ return undefined;
+ }
+ const text = await response.text();
+ if (text.length === 0) {
+ return undefined;
+ }
+ const contentType = response.headers.get('content-type') ?? '';
+ if (contentType.includes('json')) {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+ }
+ return text;
+}
+
+async function openGitlabResponse({
+ request,
+ accept,
+}: {
+ request: GitlabRequest;
+ accept: string;
+}): Promise<Response> {
+ const url = buildGitlabUrl({ path: request.path, query: request.query });
+ const headers: Record<string, string> = {
+ Authorization: `Bearer ${request.token}`,
+ Accept: accept,
+ };
+ let payload: string | undefined;
+ if (request.body !== undefined) {
+ headers['Content-Type'] = 'application/json';
+ payload = JSON.stringify(request.body);
+ }
+ const dispatcher = await gitlabTransport.getDispatcher();
+ const init: RequestInit & { dispatcher: Dispatcher } = {
+ method: request.method,
+ headers,
+ body: payload,
+ redirect: 'manual',
+ signal: AbortSignal.timeout(request.timeoutMs ?? DEFAULT_TIMEOUT_MS),
+ dispatcher,
+ };
+ const response = await fetch(url, init);
+ if (response.status >= 300 && response.status < 400) {
+ await response.body?.cancel();
+ throw new GitlabApiError({
+ message: `GitLab answered with an unexpected redirect (HTTP ${response.status}); the request was not followed.`,
+ status: response.status,
+ responseBody: undefined,
+ });
+ }
+ if (!response.ok) {
+ throw buildGitlabError({
+ status: response.status,
+ responseBody: await readBody(response),
+ statusMessages: request.statusMessages,
+ });
+ }
+ return response;
+}
+
+export async function sendGitlabRequest<T>(
+ request: GitlabRequest
+): Promise<GitlabResponse<T>> {
+ const response = await openGitlabResponse({
+ request,
+ accept: 'application/json',
+ });
+ const body = await readBody(response);
+ return {
+ status: response.status,
+ headers: response.headers,
+ body,
+ };
+}
+
+export async function readGitlabRawPrefix({
+ request,
+ maxBytes,
+}: {
+ request: GitlabRequest;
+ maxBytes: number;
+}): Promise<{ bytes: Buffer; complete: boolean }> {
+ const response = await openGitlabResponse({
+ request,
+ accept: 'application/octet-stream',
+ });
+ if (response.body === null) {
+ return { bytes: Buffer.alloc(0), complete: true };
+ }
+ const reader = response.body.getReader();
+ const chunks: Buffer[] = [];
+ let length = 0;
+ let complete = true;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) {
+ break;
+ }
+ const room = maxBytes - length;
+ if (value.byteLength > room) {
+ chunks.push(Buffer.from(value.subarray(0, room)));
+ length += room;
+ complete = false;
+ await reader.cancel();
+ break;
+ }
+ chunks.push(Buffer.from(value));
+ length += value.byteLength;
+ }
+ return { bytes: Buffer.concat(chunks, length), complete };
+}
diff --git a/packages/pieces/community/gitlab/src/lib/output-schemas.ts b/packages/pieces/community/gitlab/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..ea2314aca6d
--- /dev/null
+++ b/packages/pieces/community/gitlab/src/lib/output-schemas.ts
@@ -0,0 +1,633 @@
+import {
+ OutputSchema,
+ OutputSchemaField,
+} from '@activepieces/pieces-framework';
+
+type Fields = OutputSchemaField[];
+
+const pageFields = ({
+ label,
+ itemFields,
+ labelKey,
+}: {
+ label: string;
+ itemFields: Fields;
+ labelKey: string;
+}): Fields => [
+ { key: 'items', label, labelKey, listItems: itemFields },
+ { key: 'count', label: 'Items on This Page', format: 'number' },
+ { key: 'page', label: 'Page', format: 'number' },
+ {
+ key: 'nextPage',
+ label: 'Next Page',
+ format: 'number',
+ description: 'Pass as Page to fetch more. Empty on the last page.',
+ },
+ { key: 'hasMore', label: 'Has More', format: 'boolean' },
+ {
+ key: 'total',
+ label: 'Total',
+ format: 'number',
+ description:
+ 'Total items when GitLab reports it; empty for very large lists.',
+ },
+];
+
+const userRefFields: Fields = [
+ { key: 'id', label: 'User ID', format: 'number' },
+ { key: 'username', label: 'Username' },
+ { key: 'name', label: 'Name' },
+ { key: 'state', label: 'State' },
+ { key: 'avatar_url', label: 'Avatar', format: 'image' },
+ { key: 'web_url', label: 'Profile URL', format: 'url' },
+];
+
+const milestoneRefFields: Fields = [
+ { key: 'id', label: 'Milestone ID', format: 'number' },
+ { key: 'iid', label: 'Milestone IID', format: 'number' },
+ { key: 'title', label: 'Title' },
+ { key: 'state', label: 'State' },
+ { key: 'due_date', label: 'Due Date', format: 'date' },
+ { key: 'web_url', label: 'URL', format: 'url' },
+];
+
+const issueFields: Fields = [
+ { key: 'id', label: 'Issue ID', format: 'number' },
+ { key: 'iid', label: 'Issue IID', format: 'number' },
+ { key: 'project_id', label: 'Project ID', format: 'number' },
+ { key: 'title', label: 'Title' },
+ { key: 'description', label: 'Description' },
+ { key: 'state', label: 'State' },
+ { key: 'labels', label: 'Labels' },
+ { key: 'author', label: 'Author', children: userRefFields },
+ {
+ key: 'assignees',
+ label: 'Assignees',
+ labelKey: 'username',
+ listItems: userRefFields,
+ },
+ { key: 'milestone', label: 'Milestone', children: milestoneRefFields },
+ { key: 'confidential', label: 'Confidential', format: 'boolean' },
+ { key: 'discussion_locked', label: 'Discussion Locked', format: 'boolean' },
+ { key: 'due_date', label: 'Due Date', format: 'date' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'closed_at', label: 'Closed At', format: 'datetime' },
+ { key: 'closed_by', label: 'Closed By', children: userRefFields },
+ { key: 'user_notes_count', label: 'Comment Count', format: 'number' },
+ { key: 'issue_type', label: 'Type' },
+ { key: 'web_url', label: 'URL', format: 'url' },
+ {
+ key: 'time_stats',
+ label: 'Time Tracking',
+ children: [
+ { key: 'time_estimate', label: 'Estimate (seconds)', format: 'number' },
+ {
+ key: 'total_time_spent',
+ label: 'Time Spent (seconds)',
+ format: 'number',
+ },
+ ],
+ },
+ {
+ key: 'references',
+ label: 'References',
+ children: [{ key: 'full', label: 'Full Reference' }],
+ },
+];
+
+export const issueOutputSchema: OutputSchema = { fields: issueFields };
+export const issueListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Issues',
+ itemFields: issueFields,
+ labelKey: 'title',
+ }),
+};
+
+const noteFields: Fields = [
+ { key: 'id', label: 'Note ID', format: 'number' },
+ { key: 'body', label: 'Body' },
+ { key: 'author', label: 'Author', children: userRefFields },
+ { key: 'system', label: 'System Note', format: 'boolean' },
+ { key: 'internal', label: 'Internal', format: 'boolean' },
+ { key: 'noteable_type', label: 'Attached To' },
+ { key: 'noteable_iid', label: 'Attached To IID', format: 'number' },
+ { key: 'resolvable', label: 'Resolvable', format: 'boolean' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+export const noteOutputSchema: OutputSchema = { fields: noteFields };
+export const noteListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Comments',
+ itemFields: noteFields,
+ labelKey: 'id',
+ }),
+};
+export const deletedNoteOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'noteId', label: 'Note ID', format: 'number' },
+ { key: 'issueIid', label: 'Issue IID', format: 'number' },
+ ],
+};
+
+export const timeStatsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'time_estimate', label: 'Estimate (seconds)', format: 'number' },
+ {
+ key: 'total_time_spent',
+ label: 'Time Spent (seconds)',
+ format: 'number',
+ },
+ { key: 'human_time_estimate', label: 'Estimate' },
+ { key: 'human_total_time_spent', label: 'Time Spent' },
+ ],
+};
+
+const mergeRequestFields: Fields = [
+ { key: 'id', label: 'Merge Request ID', format: 'number' },
+ { key: 'iid', label: 'Merge Request IID', format: 'number' },
+ { key: 'project_id', label: 'Project ID', format: 'number' },
+ { key: 'title', label: 'Title' },
+ { key: 'description', label: 'Description' },
+ { key: 'state', label: 'State' },
+ { key: 'draft', label: 'Draft', format: 'boolean' },
+ { key: 'source_branch', label: 'Source Branch' },
+ { key: 'target_branch', label: 'Target Branch' },
+ { key: 'sha', label: 'Head SHA' },
+ { key: 'merge_commit_sha', label: 'Merge Commit SHA' },
+ { key: 'squash_commit_sha', label: 'Squash Commit SHA' },
+ { key: 'detailed_merge_status', label: 'Merge Status' },
+ { key: 'has_conflicts', label: 'Has Conflicts', format: 'boolean' },
+ { key: 'labels', label: 'Labels' },
+ { key: 'author', label: 'Author', children: userRefFields },
+ {
+ key: 'assignees',
+ label: 'Assignees',
+ labelKey: 'username',
+ listItems: userRefFields,
+ },
+ {
+ key: 'reviewers',
+ label: 'Reviewers',
+ labelKey: 'username',
+ listItems: userRefFields,
+ },
+ { key: 'milestone', label: 'Milestone', children: milestoneRefFields },
+ { key: 'merged_by', label: 'Merged By', children: userRefFields },
+ { key: 'merged_at', label: 'Merged At', format: 'datetime' },
+ { key: 'closed_at', label: 'Closed At', format: 'datetime' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ { key: 'squash', label: 'Squash on Merge', format: 'boolean' },
+ {
+ key: 'force_remove_source_branch',
+ label: 'Delete Source Branch on Merge',
+ format: 'boolean',
+ },
+ { key: 'user_notes_count', label: 'Comment Count', format: 'number' },
+ { key: 'web_url', label: 'URL', format: 'url' },
+ {
+ key: 'references',
+ label: 'References',
+ children: [{ key: 'full', label: 'Full Reference' }],
+ },
+];
+
+export const mergeRequestOutputSchema: OutputSchema = {
+ fields: mergeRequestFields,
+};
+export const mergeRequestListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Merge Requests',
+ itemFields: mergeRequestFields,
+ labelKey: 'title',
+ }),
+};
+export const deletedMergeRequestOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'mergeRequestIid', label: 'Merge Request IID', format: 'number' },
+ ],
+};
+
+export const approvalsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'iid', label: 'Merge Request IID', format: 'number' },
+ { key: 'approved', label: 'Approved', format: 'boolean' },
+ {
+ key: 'approvals_required',
+ label: 'Approvals Required',
+ format: 'number',
+ },
+ { key: 'approvals_left', label: 'Approvals Left', format: 'number' },
+ {
+ key: 'user_has_approved',
+ label: 'Connected User Approved',
+ format: 'boolean',
+ },
+ {
+ key: 'user_can_approve',
+ label: 'Connected User Can Approve',
+ format: 'boolean',
+ },
+ {
+ key: 'approved_by',
+ label: 'Approved By',
+ listItems: [{ key: 'user', label: 'User', children: userRefFields }],
+ },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+ ],
+};
+
+export const draftNoteOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Draft Note ID', format: 'number' },
+ { key: 'author_id', label: 'Author ID', format: 'number' },
+ { key: 'merge_request_id', label: 'Merge Request ID', format: 'number' },
+ { key: 'note', label: 'Comment' },
+ { key: 'discussion_id', label: 'Discussion ID' },
+ {
+ key: 'resolve_discussion',
+ label: 'Resolves Discussion',
+ format: 'boolean',
+ },
+ ],
+};
+
+export const discussionListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Discussions',
+ itemFields: [
+ { key: 'id', label: 'Discussion ID' },
+ { key: 'individual_note', label: 'Single Comment', format: 'boolean' },
+ {
+ key: 'notes',
+ label: 'Comments',
+ labelKey: 'id',
+ listItems: [...noteFields],
+ },
+ ],
+ labelKey: 'id',
+ }),
+};
+
+export const diffListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Changed Files',
+ itemFields: [
+ { key: 'old_path', label: 'Old Path' },
+ { key: 'new_path', label: 'New Path' },
+ { key: 'new_file', label: 'New File', format: 'boolean' },
+ { key: 'renamed_file', label: 'Renamed', format: 'boolean' },
+ { key: 'deleted_file', label: 'Deleted', format: 'boolean' },
+ { key: 'generated_file', label: 'Generated', format: 'boolean' },
+ { key: 'diff', label: 'Diff' },
+ { key: 'diffTruncated', label: 'Diff Truncated', format: 'boolean' },
+ ],
+ labelKey: 'new_path',
+ }),
+};
+
+export const diffVersionListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Diff Versions',
+ itemFields: [
+ { key: 'id', label: 'Version ID', format: 'number' },
+ { key: 'head_commit_sha', label: 'Head SHA' },
+ { key: 'base_commit_sha', label: 'Base SHA' },
+ { key: 'start_commit_sha', label: 'Start SHA' },
+ { key: 'state', label: 'State' },
+ { key: 'real_size', label: 'Changed Files' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ ],
+ labelKey: 'id',
+ }),
+};
+
+const commitFields: Fields = [
+ { key: 'id', label: 'SHA' },
+ { key: 'short_id', label: 'Short SHA' },
+ { key: 'title', label: 'Title' },
+ { key: 'message', label: 'Message' },
+ { key: 'author_name', label: 'Author Name' },
+ { key: 'author_email', label: 'Author Email', format: 'email' },
+ { key: 'authored_date', label: 'Authored At', format: 'datetime' },
+ { key: 'committer_name', label: 'Committer Name' },
+ { key: 'committed_date', label: 'Committed At', format: 'datetime' },
+ { key: 'parent_ids', label: 'Parent SHAs' },
+ { key: 'web_url', label: 'URL', format: 'url' },
+];
+
+export const commitOutputSchema: OutputSchema = {
+ fields: [
+ ...commitFields,
+ {
+ key: 'stats',
+ label: 'Stats',
+ children: [
+ { key: 'additions', label: 'Additions', format: 'number' },
+ { key: 'deletions', label: 'Deletions', format: 'number' },
+ { key: 'total', label: 'Total', format: 'number' },
+ ],
+ },
+ {
+ key: 'last_pipeline',
+ label: 'Last Pipeline',
+ children: [
+ { key: 'id', label: 'Pipeline ID', format: 'number' },
+ { key: 'status', label: 'Status' },
+ { key: 'web_url', label: 'URL', format: 'url' },
+ ],
+ },
+ ],
+};
+export const commitListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Commits',
+ itemFields: commitFields,
+ labelKey: 'title',
+ }),
+};
+
+export const commitRefListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Refs',
+ itemFields: [
+ { key: 'type', label: 'Type' },
+ { key: 'name', label: 'Name' },
+ ],
+ labelKey: 'name',
+ }),
+};
+
+export const commitSequenceOutputSchema: OutputSchema = {
+ fields: [{ key: 'count', label: 'Sequence Number', format: 'number' }],
+};
+
+const commitCommentFields: Fields = [
+ { key: 'note', label: 'Comment' },
+ { key: 'path', label: 'File Path' },
+ { key: 'line', label: 'Line', format: 'number' },
+ { key: 'line_type', label: 'Line Type' },
+ { key: 'author', label: 'Author', children: userRefFields },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+export const commitCommentOutputSchema: OutputSchema = {
+ fields: [
+ ...commitCommentFields,
+ { key: 'lineAnchored', label: 'Anchored to Line', format: 'boolean' },
+ ],
+};
+export const commitCommentListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Comments',
+ itemFields: commitCommentFields,
+ labelKey: 'note',
+ }),
+};
+
+export const fileOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'file_name', label: 'File Name' },
+ { key: 'file_path', label: 'File Path' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'content', label: 'Content' },
+ { key: 'isBinary', label: 'Binary', format: 'boolean' },
+ { key: 'truncated', label: 'Truncated', format: 'boolean' },
+ { key: 'ref', label: 'Ref' },
+ { key: 'blob_id', label: 'Blob ID' },
+ { key: 'commit_id', label: 'Commit ID' },
+ { key: 'last_commit_id', label: 'Last Commit ID' },
+ { key: 'content_sha256', label: 'SHA-256' },
+ ],
+};
+
+export const fileCommitOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'file_path', label: 'File Path' },
+ { key: 'branch', label: 'Branch' },
+ ],
+};
+
+export const deletedFileOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'file_path', label: 'File Path' },
+ { key: 'branch', label: 'Branch' },
+ ],
+};
+
+export const treeListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Entries',
+ itemFields: [
+ { key: 'id', label: 'Object ID' },
+ { key: 'name', label: 'Name' },
+ {
+ key: 'type',
+ label: 'Type',
+ description: 'blob (file) or tree (folder).',
+ },
+ { key: 'path', label: 'Path' },
+ { key: 'mode', label: 'Mode' },
+ ],
+ labelKey: 'path',
+ }),
+};
+
+const branchFields: Fields = [
+ { key: 'name', label: 'Name' },
+ { key: 'merged', label: 'Merged', format: 'boolean' },
+ { key: 'protected', label: 'Protected', format: 'boolean' },
+ { key: 'default', label: 'Default Branch', format: 'boolean' },
+ {
+ key: 'developers_can_push',
+ label: 'Developers Can Push',
+ format: 'boolean',
+ },
+ {
+ key: 'developers_can_merge',
+ label: 'Developers Can Merge',
+ format: 'boolean',
+ },
+ { key: 'can_push', label: 'Connected User Can Push', format: 'boolean' },
+ { key: 'web_url', label: 'URL', format: 'url' },
+ { key: 'commit', label: 'Latest Commit', children: commitFields },
+];
+
+export const branchOutputSchema: OutputSchema = { fields: branchFields };
+export const branchListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Branches',
+ itemFields: branchFields,
+ labelKey: 'name',
+ }),
+};
+export const deletedBranchOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'branch', label: 'Branch' },
+ ],
+};
+
+const accessLevelFields: Fields = [
+ { key: 'access_level', label: 'Access Level', format: 'number' },
+ { key: 'access_level_description', label: 'Description' },
+];
+
+export const protectedBranchOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Protection ID', format: 'number' },
+ { key: 'name', label: 'Branch or Pattern' },
+ { key: 'allow_force_push', label: 'Allow Force Push', format: 'boolean' },
+ {
+ key: 'push_access_levels',
+ label: 'Allowed to Push',
+ labelKey: 'access_level_description',
+ listItems: accessLevelFields,
+ },
+ {
+ key: 'merge_access_levels',
+ label: 'Allowed to Merge',
+ labelKey: 'access_level_description',
+ listItems: accessLevelFields,
+ },
+ ],
+};
+
+export const unprotectedBranchOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'unprotected', label: 'Unprotected', format: 'boolean' },
+ {
+ key: 'alreadyUnprotected',
+ label: 'Was Not Protected',
+ format: 'boolean',
+ },
+ { key: 'name', label: 'Branch or Pattern' },
+ ],
+};
+
+export const tagListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Tags',
+ itemFields: [
+ { key: 'name', label: 'Name' },
+ { key: 'message', label: 'Message' },
+ { key: 'target', label: 'Target SHA' },
+ { key: 'protected', label: 'Protected', format: 'boolean' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'commit', label: 'Commit', children: commitFields },
+ {
+ key: 'release',
+ label: 'Release',
+ children: [
+ { key: 'tag_name', label: 'Tag Name' },
+ { key: 'description', label: 'Description' },
+ ],
+ },
+ ],
+ labelKey: 'name',
+ }),
+};
+
+const userFields: Fields = [
+ ...userRefFields,
+ { key: 'public_email', label: 'Public Email', format: 'email' },
+ { key: 'bio', label: 'Bio' },
+ { key: 'location', label: 'Location' },
+ { key: 'job_title', label: 'Job Title' },
+ { key: 'organization', label: 'Organization' },
+ { key: 'bot', label: 'Bot', format: 'boolean' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+];
+
+export const userOutputSchema: OutputSchema = { fields: userFields };
+export const currentUserOutputSchema: OutputSchema = {
+ fields: [
+ ...userFields,
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'commit_email', label: 'Commit Email', format: 'email' },
+ { key: 'last_activity_on', label: 'Last Activity', format: 'date' },
+ {
+ key: 'can_create_project',
+ label: 'Can Create Projects',
+ format: 'boolean',
+ },
+ { key: 'can_create_group', label: 'Can Create Groups', format: 'boolean' },
+ ],
+};
+export const userListOutputSchema: OutputSchema = {
+ fields: pageFields({
+ label: 'Users',
+ itemFields: userRefFields,
+ labelKey: 'username',
+ }),
+};
+
+export const userStatusOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'emoji', label: 'Emoji' },
+ { key: 'message', label: 'Message' },
+ { key: 'availability', label: 'Availability' },
+ { key: 'clear_status_at', label: 'Clears At', format: 'datetime' },
+ ],
+};
+
+export const issueEventOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'object_kind', label: 'Event Kind' },
+ {
+ key: 'event_type',
+ label: 'Event Type',
+ description: 'issue or confidential_issue.',
+ },
+ {
+ key: 'user',
+ label: 'Triggered By',
+ children: [
+ { key: 'id', label: 'User ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'username', label: 'Username' },
+ ],
+ },
+ {
+ key: 'project',
+ label: 'Project',
+ children: [
+ { key: 'id', label: 'Project ID', format: 'number' },
+ { key: 'name', label: 'Name' },
+ { key: 'path_with_namespace', label: 'Full Path' },
+ { key: 'web_url', label: 'URL', format: 'url' },
+ { key: 'default_branch', label: 'Default Branch' },
+ ],
+ },
+ {
+ key: 'object_attributes',
+ label: 'Issue',
+ children: [
+ { key: 'id', label: 'Issue ID', format: 'number' },
+ { key: 'iid', label: 'Issue IID', format: 'number' },
+ { key: 'title', label: 'Title' },
+ { key: 'description', label: 'Description' },
+ { key: 'state', label: 'State' },
+ {
+ key: 'action',
+ label: 'Action',
+ description: 'open, close, reopen or update.',
+ },
+ { key: 'confidential', label: 'Confidential', format: 'boolean' },
+ { key: 'due_date', label: 'Due Date', format: 'date' },
+ { key: 'created_at', label: 'Created At' },
+ { key: 'updated_at', label: 'Updated At' },
+ { key: 'url', label: 'URL', format: 'url' },
+ ],
+ },
+ { key: 'labels', label: 'Labels' },
+ { key: 'changes', label: 'Changes', dynamicKey: true },
+ ],
+};
diff --git a/packages/pieces/community/gitlab/src/lib/trigger/issue-event.ts b/packages/pieces/community/gitlab/src/lib/trigger/issue-event.ts
index 8d05bad9f2c..5e985dde149 100644
--- a/packages/pieces/community/gitlab/src/lib/trigger/issue-event.ts
+++ b/packages/pieces/community/gitlab/src/lib/trigger/issue-event.ts
@@ -1,11 +1,21 @@
+import { randomBytes, timingSafeEqual } from 'crypto';
import {
createTrigger,
TriggerStrategy,
Property,
} from '@activepieces/pieces-framework';
-
-import { gitlabCommon, makeClient } from '../common';
+import { gitlabCommon } from '../common';
import { gitlabAuth } from '../auth';
+import { GitlabAuthValue, gitlabToken, projectPath } from '../common/client';
+import {
+ GitlabApiError,
+ isRecord,
+ sendGitlabRequest,
+} from '../common/secret-request';
+import { ProjectWebhook } from '../common/models';
+import { issueEventOutputSchema } from '../output-schemas';
+
+export const ISSUE_TRIGGER_STORE_KEY = 'gitlab_issue_trigger';
const sampleData = {
object_kind: 'issue',
event_type: 'issue',
@@ -99,9 +109,10 @@ export const issuesEventTrigger = createTrigger({
classification: 'READ',
displayName: 'New Project Issue Event',
description:
- 'Triggers on project issue events when an issue is created or when an existing issue is updated, closed, or reopened.',
+ 'Triggers on project issue events (including confidential issues) when an issue is created or when an existing issue is updated, closed, or reopened.',
aiMetadata: {
- description: 'Fires when an issue event occurs in the configured GitLab project via webhook. The Issue Event prop scopes which actions fire: All, or only Opened, Closed, or Updated. Represents the issue and its change set at the moment of the event.',
+ description:
+ 'Fires when an issue event, including on confidential issues, occurs in the configured GitLab project via webhook. The Issue Event prop scopes which actions fire: All, or only Opened, Closed, Reopened, or Updated. Represents the issue and its change set at the moment of the event.',
},
props: {
projectId: gitlabCommon.projectId(),
@@ -116,6 +127,7 @@ export const issuesEventTrigger = createTrigger({
{ label: 'All', value: 'all' },
{ label: 'Opened', value: 'open' },
{ label: 'Closed', value: 'close' },
+ { label: 'Reopened', value: 'reopen' },
{ label: 'Updated', value: 'update' },
],
},
@@ -123,53 +135,152 @@ export const issuesEventTrigger = createTrigger({
},
type: TriggerStrategy.WEBHOOK,
sampleData: sampleData,
+ outputSchema: issueEventOutputSchema,
async onEnable({ store, auth, propsValue, webhookUrl }) {
- const projectId = propsValue.projectId!;
- const client = makeClient({ auth });
- const res = await client.subscribeProjectWebhook(projectId, {
- url: webhookUrl,
- issues_events: true,
- push_events: false,
- });
- await store.put<WebhookInformation>('gitlab_issue_trigger', {
- webhookId: res.id,
- projectId: projectId as string,
+ const projectId = String(propsValue.projectId);
+ const token = randomBytes(32).toString('hex');
+ const response = await sendGitlabRequest<ProjectWebhook>({
+ token: gitlabToken(auth),
+ method: 'POST',
+ path: `${projectPath(projectId)}/hooks`,
+ body: {
+ url: webhookUrl,
+ token,
+ issues_events: true,
+ confidential_issues_events: true,
+ push_events: false,
+ enable_ssl_verification: true,
+ },
});
+ const webhookId = response.body.id;
+ try {
+ await store.put<WebhookInformation>(ISSUE_TRIGGER_STORE_KEY, {
+ webhookId,
+ projectId,
+ token,
+ });
+ } catch (error) {
+ await deleteProjectHook({ auth, projectId, webhookId });
+ throw error;
+ }
},
async onDisable({ auth, store }) {
- const response = await store.get<WebhookInformation>(
- 'gitlab_issue_trigger'
- );
- if (response !== null && response !== undefined) {
- const client = makeClient({ auth });
- client.unsubscribeProjectWebhook(response.projectId, response.webhookId);
+ const stored = await store.get<WebhookInformation>(ISSUE_TRIGGER_STORE_KEY);
+ if (stored === null || stored === undefined) {
+ return;
}
+ await deleteProjectHook({
+ auth,
+ projectId: String(stored.projectId),
+ webhookId: stored.webhookId,
+ });
+ await store.delete(ISSUE_TRIGGER_STORE_KEY);
},
async run(context) {
- const { actiontype } = context.propsValue;
+ const stored = await context.store.get<WebhookInformation>(
+ ISSUE_TRIGGER_STORE_KEY
+ );
if (
- isVerificationCall(
- context.payload.body as Record<string, unknown>,
- actiontype as string
- )
+ !isAuthenticDelivery({
+ storedToken: stored?.token,
+ headers: context.payload.headers,
+ })
) {
- return [context.payload.body];
+ return [];
}
- return [];
+ const body = context.payload.body;
+ if (
+ !matchesAction({
+ payload: isRecord(body) ? body : undefined,
+ actiontype: String(context.propsValue.actiontype ?? 'all'),
+ })
+ ) {
+ return [];
+ }
+ return [body];
},
});
-function isVerificationCall(payload: Record<string, any>, actiontype: string) {
- if (actiontype == 'all') {
+async function deleteProjectHook({
+ auth,
+ projectId,
+ webhookId,
+}: {
+ auth: GitlabAuthValue;
+ projectId: string;
+ webhookId: number | string;
+}): Promise<void> {
+ try {
+ await sendGitlabRequest({
+ token: gitlabToken(auth),
+ method: 'DELETE',
+ path: `${projectPath(projectId)}/hooks/${encodeURIComponent(
+ String(webhookId)
+ )}`,
+ });
+ } catch (error) {
+ if (error instanceof GitlabApiError && error.status === 404) {
+ return;
+ }
+ throw error;
+ }
+}
+
+function headerValue({
+ headers,
+ name,
+}: {
+ headers: Record<string, string> | undefined;
+ name: string;
+}): string | undefined {
+ if (!headers) {
+ return undefined;
+ }
+ const match = Object.keys(headers).find((key) => key.toLowerCase() === name);
+ return match === undefined ? undefined : headers[match];
+}
+
+export function isAuthenticDelivery({
+ storedToken,
+ headers,
+}: {
+ storedToken: string | undefined;
+ headers: Record<string, string> | undefined;
+}): boolean {
+ if (storedToken === undefined || storedToken === '') {
return true;
}
- return payload['object_attributes']['action'] == actiontype;
+ const received = headerValue({ headers, name: 'x-gitlab-token' });
+ if (typeof received !== 'string') {
+ return false;
+ }
+ const expected = Buffer.from(storedToken, 'utf8');
+ const actual = Buffer.from(received, 'utf8');
+ if (expected.length !== actual.length) {
+ return false;
+ }
+ return timingSafeEqual(expected, actual);
+}
+
+function matchesAction({
+ payload,
+ actiontype,
+}: {
+ payload: Record<string, unknown> | undefined;
+ actiontype: string;
+}): boolean {
+ if (actiontype === 'all') {
+ return true;
+ }
+ const attributes = payload?.['object_attributes'];
+ return isRecord(attributes) && attributes['action'] === actiontype;
}
interface WebhookInformation {
- webhookId: string;
- projectId: string;
+ webhookId: number | string;
+ projectId: number | string;
+ token?: string;
}
diff --git a/packages/pieces/community/gitlab/test/atomics.test.ts b/packages/pieces/community/gitlab/test/atomics.test.ts
new file mode 100644
index 00000000000..b49fabc9bde
--- /dev/null
+++ b/packages/pieces/community/gitlab/test/atomics.test.ts
@@ -0,0 +1,1234 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { gitlab } from '../src';
+import { createIssueAction } from '../src/lib/actions/create-issue-action';
+import { createProjectIssueAction } from '../src/lib/actions/issues/create-project-issue';
+import { getIssueAction } from '../src/lib/actions/issues/get-issue';
+import { listIssuesAction } from '../src/lib/actions/issues/list-issues';
+import { updateIssueAction } from '../src/lib/actions/issues/update-issue';
+import { moveIssueAction } from '../src/lib/actions/issues/move-issue';
+import { createIssueNoteAction } from '../src/lib/actions/issues/create-issue-note';
+import { getIssueNoteAction } from '../src/lib/actions/issues/get-issue-note';
+import { listIssueNotesAction } from '../src/lib/actions/issues/list-issue-notes';
+import { updateIssueNoteAction } from '../src/lib/actions/issues/update-issue-note';
+import { deleteIssueNoteAction } from '../src/lib/actions/issues/delete-issue-note';
+import { addIssueSpentTimeAction } from '../src/lib/actions/issues/add-issue-spent-time';
+import { resetIssueSpentTimeAction } from '../src/lib/actions/issues/reset-issue-spent-time';
+import { getIssueTimeStatsAction } from '../src/lib/actions/issues/get-issue-time-stats';
+import { setIssueTimeEstimateAction } from '../src/lib/actions/issues/set-issue-time-estimate';
+import { resetIssueTimeEstimateAction } from '../src/lib/actions/issues/reset-issue-time-estimate';
+import { createMergeRequestAction } from '../src/lib/actions/merge-requests/create-merge-request';
+import { getMergeRequestAction } from '../src/lib/actions/merge-requests/get-merge-request';
+import { listMergeRequestsAction } from '../src/lib/actions/merge-requests/list-merge-requests';
+import { updateMergeRequestAction } from '../src/lib/actions/merge-requests/update-merge-request';
+import { mergeMergeRequestAction } from '../src/lib/actions/merge-requests/merge-merge-request';
+import { deleteMergeRequestAction } from '../src/lib/actions/merge-requests/delete-merge-request';
+import { approveMergeRequestAction } from '../src/lib/actions/merge-requests/approve-merge-request';
+import { unapproveMergeRequestAction } from '../src/lib/actions/merge-requests/unapprove-merge-request';
+import { getMergeRequestApprovalsAction } from '../src/lib/actions/merge-requests/get-merge-request-approvals';
+import { listMergeRequestNotesAction } from '../src/lib/actions/merge-requests/list-merge-request-notes';
+import { createMergeRequestDraftNoteAction } from '../src/lib/actions/merge-requests/create-merge-request-draft-note';
+import { listMergeRequestDiscussionsAction } from '../src/lib/actions/merge-requests/list-merge-request-discussions';
+import {
+ listMergeRequestDiffsAction,
+ MAX_DIFF_CHARS,
+} from '../src/lib/actions/merge-requests/list-merge-request-diffs';
+import { listMergeRequestDiffVersionsAction } from '../src/lib/actions/merge-requests/list-merge-request-diff-versions';
+import { listMergeRequestCommitsAction } from '../src/lib/actions/merge-requests/list-merge-request-commits';
+import { createCommitAction } from '../src/lib/actions/repository/create-commit';
+import { getCommitAction } from '../src/lib/actions/repository/get-commit';
+import { listCommitsAction } from '../src/lib/actions/repository/list-commits';
+import { getCommitRefsAction } from '../src/lib/actions/repository/get-commit-refs';
+import { getCommitSequenceAction } from '../src/lib/actions/repository/get-commit-sequence';
+import { createCommitCommentAction } from '../src/lib/actions/repository/create-commit-comment';
+import { listCommitCommentsAction } from '../src/lib/actions/repository/list-commit-comments';
+import {
+ getFileAction,
+ MAX_FILE_TEXT_BYTES,
+ decodeFilePrefix,
+} from '../src/lib/actions/repository/get-file';
+import { createFileAction } from '../src/lib/actions/repository/create-file';
+import { updateFileAction } from '../src/lib/actions/repository/update-file';
+import { deleteFileAction } from '../src/lib/actions/repository/delete-file';
+import { listRepositoryTreeAction } from '../src/lib/actions/repository/list-repository-tree';
+import { createBranchAction } from '../src/lib/actions/repository/create-branch';
+import { getBranchAction } from '../src/lib/actions/repository/get-branch';
+import { listBranchesAction } from '../src/lib/actions/repository/list-branches';
+import { deleteBranchAction } from '../src/lib/actions/repository/delete-branch';
+import { protectBranchAction } from '../src/lib/actions/repository/protect-branch';
+import { unprotectBranchAction } from '../src/lib/actions/repository/unprotect-branch';
+import { listTagsAction } from '../src/lib/actions/repository/list-tags';
+import { getCurrentUserAction } from '../src/lib/actions/users/get-current-user';
+import { getUserAction } from '../src/lib/actions/users/get-user';
+import { listUsersAction } from '../src/lib/actions/users/list-users';
+import { getUserStatusAction } from '../src/lib/actions/users/get-user-status';
+import { setUserStatusAction } from '../src/lib/actions/users/set-user-status';
+import { FAKE_DISPATCHER, rawPath, runAction, stubGitlab } from './helpers';
+import { gitlabTransport } from '../src/lib/common/secret-request';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+const P = { projectId: 'grp/proj' };
+const PP = '/projects/grp%2Fproj';
+
+type Case = {
+ name: string;
+ action: Parameters<typeof runAction>[0];
+ props: Record<string, unknown>;
+ method: string;
+ path: string;
+ query?: Record<string, unknown>;
+ body?: Record<string, unknown>;
+ reply?: unknown;
+ result?: unknown;
+};
+
+const cases: Case[] = [
+ {
+ name: 'create_issue (human)',
+ action: createIssueAction,
+ props: { projectId: 12, title: 'Bug', description: 'Body' },
+ method: 'POST',
+ path: '/projects/12/issues',
+ body: { title: 'Bug', description: 'Body' },
+ },
+ {
+ name: 'create_project_issue',
+ action: createProjectIssueAction,
+ props: {
+ ...P,
+ title: 'T',
+ description: 'D',
+ labels: ['a', 'b'],
+ assigneeIds: ['3'],
+ milestoneId: 4,
+ dueDate: '2026-10-20',
+ confidential: 'true',
+ },
+ method: 'POST',
+ path: `${PP}/issues`,
+ body: {
+ title: 'T',
+ description: 'D',
+ labels: 'a,b',
+ assignee_ids: [3],
+ milestone_id: 4,
+ due_date: '2026-10-20',
+ confidential: true,
+ },
+ },
+ {
+ name: 'get_issue',
+ action: getIssueAction,
+ props: { ...P, issueIid: 7 },
+ method: 'GET',
+ path: `${PP}/issues/7`,
+ },
+ {
+ name: 'list_issues',
+ action: listIssuesAction,
+ props: {
+ ...P,
+ state: 'opened',
+ search: 'crash',
+ labels: ['bug'],
+ assigneeId: 2,
+ authorId: 3,
+ milestone: 'v1',
+ updatedAfter: '2026-10-01',
+ orderBy: 'updated_at',
+ sort: 'asc',
+ page: 2,
+ perPage: 50,
+ },
+ method: 'GET',
+ path: `${PP}/issues`,
+ query: {
+ state: 'opened',
+ search: 'crash',
+ labels: 'bug',
+ assignee_id: '2',
+ author_id: '3',
+ milestone: 'v1',
+ updated_after: '2026-10-01',
+ order_by: 'updated_at',
+ sort: 'asc',
+ page: '2',
+ per_page: '50',
+ },
+ },
+ {
+ name: 'update_issue',
+ action: updateIssueAction,
+ props: {
+ ...P,
+ issueIid: 7,
+ title: 'New',
+ stateEvent: 'close',
+ addLabels: ['x'],
+ confidential: 'false',
+ },
+ method: 'PUT',
+ path: `${PP}/issues/7`,
+ body: {
+ title: 'New',
+ state_event: 'close',
+ add_labels: 'x',
+ confidential: false,
+ },
+ },
+ {
+ name: 'move_issue',
+ action: moveIssueAction,
+ props: { ...P, issueIid: 7, toProjectId: 99 },
+ method: 'POST',
+ path: `${PP}/issues/7/move`,
+ body: { to_project_id: 99 },
+ },
+ {
+ name: 'create_issue_note',
+ action: createIssueNoteAction,
+ props: { ...P, issueIid: 7, body: 'Hi' },
+ method: 'POST',
+ path: `${PP}/issues/7/notes`,
+ body: { body: 'Hi' },
+ },
+ {
+ name: 'get_issue_note',
+ action: getIssueNoteAction,
+ props: { ...P, issueIid: 7, noteId: 5 },
+ method: 'GET',
+ path: `${PP}/issues/7/notes/5`,
+ },
+ {
+ name: 'list_issue_notes',
+ action: listIssueNotesAction,
+ props: { ...P, issueIid: 7, orderBy: 'created_at', sort: 'asc' },
+ method: 'GET',
+ path: `${PP}/issues/7/notes`,
+ query: { order_by: 'created_at', sort: 'asc', page: '1', per_page: '20' },
+ },
+ {
+ name: 'update_issue_note',
+ action: updateIssueNoteAction,
+ props: { ...P, issueIid: 7, noteId: 5, body: 'Edit' },
+ method: 'PUT',
+ path: `${PP}/issues/7/notes/5`,
+ body: { body: 'Edit' },
+ },
+ {
+ name: 'delete_issue_note',
+ action: deleteIssueNoteAction,
+ props: { ...P, issueIid: 7, noteId: 5 },
+ method: 'DELETE',
+ path: `${PP}/issues/7/notes/5`,
+ reply: null,
+ result: { deleted: true, noteId: 5, issueIid: 7 },
+ },
+ {
+ name: 'add_issue_spent_time',
+ action: addIssueSpentTimeAction,
+ props: { ...P, issueIid: 7, duration: '1h 30m', summary: 'review' },
+ method: 'POST',
+ path: `${PP}/issues/7/add_spent_time`,
+ body: { duration: '1h30m', summary: 'review' },
+ },
+ {
+ name: 'reset_issue_spent_time',
+ action: resetIssueSpentTimeAction,
+ props: { ...P, issueIid: 7 },
+ method: 'POST',
+ path: `${PP}/issues/7/reset_spent_time`,
+ },
+ {
+ name: 'get_issue_time_stats',
+ action: getIssueTimeStatsAction,
+ props: { ...P, issueIid: 7 },
+ method: 'GET',
+ path: `${PP}/issues/7/time_stats`,
+ },
+ {
+ name: 'set_issue_time_estimate',
+ action: setIssueTimeEstimateAction,
+ props: { ...P, issueIid: 7, duration: '3h' },
+ method: 'POST',
+ path: `${PP}/issues/7/time_estimate`,
+ body: { duration: '3h' },
+ },
+ {
+ name: 'reset_issue_time_estimate',
+ action: resetIssueTimeEstimateAction,
+ props: { ...P, issueIid: 7 },
+ method: 'POST',
+ path: `${PP}/issues/7/reset_time_estimate`,
+ },
+ {
+ name: 'create_merge_request',
+ action: createMergeRequestAction,
+ props: {
+ ...P,
+ sourceBranch: 'feat/x',
+ targetBranch: 'main',
+ title: 'Feat',
+ reviewerIds: [8],
+ squash: 'true',
+ },
+ method: 'POST',
+ path: `${PP}/merge_requests`,
+ body: {
+ source_branch: 'feat/x',
+ target_branch: 'main',
+ title: 'Feat',
+ reviewer_ids: [8],
+ squash: true,
+ },
+ },
+ {
+ name: 'get_merge_request',
+ action: getMergeRequestAction,
+ props: { ...P, mergeRequestIid: 3 },
+ method: 'GET',
+ path: `${PP}/merge_requests/3`,
+ },
+ {
+ name: 'list_merge_requests (project)',
+ action: listMergeRequestsAction,
+ props: { ...P, state: 'opened', targetBranch: 'main' },
+ method: 'GET',
+ path: `${PP}/merge_requests`,
+ query: {
+ state: 'opened',
+ target_branch: 'main',
+ page: '1',
+ per_page: '20',
+ },
+ },
+ {
+ name: 'list_merge_requests (global)',
+ action: listMergeRequestsAction,
+ props: { scope: 'all', search: 'fix' },
+ method: 'GET',
+ path: '/merge_requests',
+ query: { scope: 'all', search: 'fix', page: '1', per_page: '20' },
+ },
+ {
+ name: 'update_merge_request',
+ action: updateMergeRequestAction,
+ props: {
+ ...P,
+ mergeRequestIid: 3,
+ targetBranch: 'dev',
+ clearReviewers: true,
+ squash: 'false',
+ },
+ method: 'PUT',
+ path: `${PP}/merge_requests/3`,
+ body: { target_branch: 'dev', reviewer_ids: [0], squash: false },
+ },
+ {
+ name: 'merge_merge_request',
+ action: mergeMergeRequestAction,
+ props: {
+ ...P,
+ mergeRequestIid: 3,
+ sha: 'abc',
+ squash: 'true',
+ shouldRemoveSourceBranch: 'true',
+ },
+ method: 'PUT',
+ path: `${PP}/merge_requests/3/merge`,
+ body: { sha: 'abc', squash: true, should_remove_source_branch: true },
+ },
+ {
+ name: 'delete_merge_request',
+ action: deleteMergeRequestAction,
+ props: { ...P, mergeRequestIid: 3 },
+ method: 'DELETE',
+ path: `${PP}/merge_requests/3`,
+ reply: null,
+ result: { deleted: true, mergeRequestIid: 3 },
+ },
+ {
+ name: 'approve_merge_request',
+ action: approveMergeRequestAction,
+ props: { ...P, mergeRequestIid: 3, sha: 'abc' },
+ method: 'POST',
+ path: `${PP}/merge_requests/3/approve`,
+ body: { sha: 'abc' },
+ },
+ {
+ name: 'unapprove_merge_request',
+ action: unapproveMergeRequestAction,
+ props: { ...P, mergeRequestIid: 3 },
+ method: 'POST',
+ path: `${PP}/merge_requests/3/unapprove`,
+ },
+ {
+ name: 'get_merge_request_approvals',
+ action: getMergeRequestApprovalsAction,
+ props: { ...P, mergeRequestIid: 3 },
+ method: 'GET',
+ path: `${PP}/merge_requests/3/approvals`,
+ },
+ {
+ name: 'list_merge_request_notes',
+ action: listMergeRequestNotesAction,
+ props: { ...P, mergeRequestIid: 3, sort: 'desc' },
+ method: 'GET',
+ path: `${PP}/merge_requests/3/notes`,
+ query: { sort: 'desc', page: '1', per_page: '20' },
+ },
+ {
+ name: 'create_merge_request_draft_note',
+ action: createMergeRequestDraftNoteAction,
+ props: { ...P, mergeRequestIid: 3, note: 'nit' },
+ method: 'POST',
+ path: `${PP}/merge_requests/3/draft_notes`,
+ body: { note: 'nit' },
+ },
+ {
+ name: 'list_merge_request_discussions',
+ action: listMergeRequestDiscussionsAction,
+ props: { ...P, mergeRequestIid: 3 },
+ method: 'GET',
+ path: `${PP}/merge_requests/3/discussions`,
+ query: { page: '1', per_page: '20' },
+ },
+ {
+ name: 'list_merge_request_diffs',
+ action: listMergeRequestDiffsAction,
+ props: { ...P, mergeRequestIid: 3 },
+ method: 'GET',
+ path: `${PP}/merge_requests/3/diffs`,
+ query: { page: '1', per_page: '20' },
+ },
+ {
+ name: 'list_merge_request_diff_versions',
+ action: listMergeRequestDiffVersionsAction,
+ props: { ...P, mergeRequestIid: 3 },
+ method: 'GET',
+ path: `${PP}/merge_requests/3/versions`,
+ query: { page: '1', per_page: '20' },
+ },
+ {
+ name: 'list_merge_request_commits',
+ action: listMergeRequestCommitsAction,
+ props: { ...P, mergeRequestIid: 3 },
+ method: 'GET',
+ path: `${PP}/merge_requests/3/commits`,
+ query: { page: '1', per_page: '20' },
+ },
+ {
+ name: 'create_commit',
+ action: createCommitAction,
+ props: {
+ ...P,
+ branch: 'main',
+ commitMessage: 'msg',
+ actions: '[{"action":"create","file_path":"a.md","content":"x"}]',
+ startBranch: 'dev',
+ },
+ method: 'POST',
+ path: `${PP}/repository/commits`,
+ body: {
+ branch: 'main',
+ commit_message: 'msg',
+ actions: [{ action: 'create', file_path: 'a.md', content: 'x' }],
+ start_branch: 'dev',
+ },
+ },
+ {
+ name: 'get_commit',
+ action: getCommitAction,
+ props: { ...P, sha: 'release/1.0' },
+ method: 'GET',
+ path: `${PP}/repository/commits/release%2F1.0`,
+ query: { stats: 'true' },
+ },
+ {
+ name: 'list_commits',
+ action: listCommitsAction,
+ props: {
+ ...P,
+ refName: 'main',
+ path: 'src',
+ since: '2026-10-01T00:00:00Z',
+ },
+ method: 'GET',
+ path: `${PP}/repository/commits`,
+ query: {
+ ref_name: 'main',
+ path: 'src',
+ since: '2026-10-01T00:00:00Z',
+ page: '1',
+ per_page: '20',
+ },
+ },
+ {
+ name: 'get_commit_refs',
+ action: getCommitRefsAction,
+ props: { ...P, sha: 'abc', type: 'tag' },
+ method: 'GET',
+ path: `${PP}/repository/commits/abc/refs`,
+ query: { type: 'tag', page: '1', per_page: '20' },
+ },
+ {
+ name: 'get_commit_sequence',
+ action: getCommitSequenceAction,
+ props: { ...P, sha: 'abc', firstParent: 'true' },
+ method: 'GET',
+ path: `${PP}/repository/commits/abc/sequence`,
+ query: { first_parent: 'true' },
+ },
+ {
+ name: 'create_commit_comment',
+ action: createCommitCommentAction,
+ props: {
+ ...P,
+ sha: 'abc',
+ note: 'n',
+ path: 'a.ts',
+ line: 3,
+ lineType: 'new',
+ },
+ method: 'POST',
+ path: `${PP}/repository/commits/abc/comments`,
+ body: { note: 'n', path: 'a.ts', line: 3, line_type: 'new' },
+ },
+ {
+ name: 'list_commit_comments',
+ action: listCommitCommentsAction,
+ props: { ...P, sha: 'abc' },
+ method: 'GET',
+ path: `${PP}/repository/commits/abc/comments`,
+ query: { page: '1', per_page: '20' },
+ },
+ {
+ name: 'create_file',
+ action: createFileAction,
+ props: {
+ ...P,
+ filePath: 'docs/x.md',
+ branch: 'main',
+ content: 'hi',
+ commitMessage: 'add',
+ },
+ method: 'POST',
+ path: `${PP}/repository/files/docs%2Fx.md`,
+ body: {
+ branch: 'main',
+ content: 'hi',
+ commit_message: 'add',
+ encoding: 'text',
+ },
+ },
+ {
+ name: 'update_file',
+ action: updateFileAction,
+ props: {
+ ...P,
+ filePath: 'docs/x.md',
+ branch: 'main',
+ content: 'hi2',
+ commitMessage: 'edit',
+ lastCommitId: 'l1',
+ },
+ method: 'PUT',
+ path: `${PP}/repository/files/docs%2Fx.md`,
+ body: {
+ branch: 'main',
+ content: 'hi2',
+ commit_message: 'edit',
+ encoding: 'text',
+ last_commit_id: 'l1',
+ },
+ },
+ {
+ name: 'delete_file',
+ action: deleteFileAction,
+ props: { ...P, filePath: 'docs/x.md', branch: 'main', commitMessage: 'rm' },
+ method: 'DELETE',
+ path: `${PP}/repository/files/docs%2Fx.md`,
+ body: { branch: 'main', commit_message: 'rm' },
+ reply: null,
+ result: { deleted: true, file_path: 'docs/x.md', branch: 'main' },
+ },
+ {
+ name: 'list_repository_tree',
+ action: listRepositoryTreeAction,
+ props: { ...P, path: 'src', ref: 'main', recursive: 'true' },
+ method: 'GET',
+ path: `${PP}/repository/tree`,
+ query: {
+ path: 'src',
+ ref: 'main',
+ recursive: 'true',
+ page: '1',
+ per_page: '20',
+ },
+ },
+ {
+ name: 'create_branch',
+ action: createBranchAction,
+ props: { ...P, branch: 'feat/y', ref: 'main' },
+ method: 'POST',
+ path: `${PP}/repository/branches`,
+ body: { branch: 'feat/y', ref: 'main' },
+ },
+ {
+ name: 'get_branch',
+ action: getBranchAction,
+ props: { ...P, branch: 'feat/y' },
+ method: 'GET',
+ path: `${PP}/repository/branches/feat%2Fy`,
+ },
+ {
+ name: 'list_branches',
+ action: listBranchesAction,
+ props: { ...P, search: '^feat' },
+ method: 'GET',
+ path: `${PP}/repository/branches`,
+ query: { search: '^feat', page: '1', per_page: '20' },
+ },
+ {
+ name: 'delete_branch',
+ action: deleteBranchAction,
+ props: { ...P, branch: 'feat/y' },
+ method: 'DELETE',
+ path: `${PP}/repository/branches/feat%2Fy`,
+ reply: null,
+ result: { deleted: true, branch: 'feat/y' },
+ },
+ {
+ name: 'protect_branch',
+ action: protectBranchAction,
+ props: {
+ ...P,
+ name: 'release/*',
+ pushAccessLevel: 0,
+ mergeAccessLevel: 40,
+ },
+ method: 'POST',
+ path: `${PP}/protected_branches`,
+ body: { name: 'release/*', push_access_level: 0, merge_access_level: 40 },
+ },
+ {
+ name: 'unprotect_branch',
+ action: unprotectBranchAction,
+ props: { ...P, name: 'release/*' },
+ method: 'DELETE',
+ path: `${PP}/protected_branches/release%2F*`,
+ reply: null,
+ result: { unprotected: true, alreadyUnprotected: false, name: 'release/*' },
+ },
+ {
+ name: 'list_tags',
+ action: listTagsAction,
+ props: { ...P, search: 'v1', orderBy: 'version' },
+ method: 'GET',
+ path: `${PP}/repository/tags`,
+ query: { search: 'v1', order_by: 'version', page: '1', per_page: '20' },
+ },
+ {
+ name: 'get_current_user',
+ action: getCurrentUserAction,
+ props: {},
+ method: 'GET',
+ path: '/user',
+ },
+ {
+ name: 'get_user',
+ action: getUserAction,
+ props: { userId: '15' },
+ method: 'GET',
+ path: '/users/15',
+ },
+ {
+ name: 'list_users',
+ action: listUsersAction,
+ props: { username: '@dev' },
+ method: 'GET',
+ path: '/users',
+ query: { username: 'dev', page: '1', per_page: '20' },
+ },
+ {
+ name: 'get_user_status (self)',
+ action: getUserStatusAction,
+ props: {},
+ method: 'GET',
+ path: '/user/status',
+ },
+ {
+ name: 'get_user_status (other)',
+ action: getUserStatusAction,
+ props: { user: '@dev' },
+ method: 'GET',
+ path: '/users/dev/status',
+ },
+];
+
+describe('exact outgoing request per atomic', () => {
+ it.each(cases)('$name', async (testCase) => {
+ const isList = testCase.query !== undefined && 'per_page' in testCase.query;
+ const reply =
+ testCase.reply === null
+ ? { status: 204 }
+ : { body: testCase.reply ?? (isList ? [] : { id: 1 }) };
+ const seen = stubGitlab([reply]);
+ const result = await runAction({
+ action: testCase.action,
+ propsValue: testCase.props,
+ });
+ expect(seen).toHaveLength(1);
+ expect(seen[0].method).toBe(testCase.method);
+ expect(rawPath(seen[0])).toBe(testCase.path);
+ expect(seen[0].query).toEqual(testCase.query ?? {});
+ expect(seen[0].body).toEqual(testCase.body);
+ if (testCase.result !== undefined) {
+ expect(result).toEqual(testCase.result);
+ }
+ });
+
+ it('covers every action registered on the piece except Custom API Call', () => {
+ const covered = new Set([
+ ...cases.map((c) => c.action.name),
+ 'set_user_status',
+ 'get_file',
+ ]);
+ const registered = Object.keys(gitlab.actions()).filter(
+ (name) => name !== 'custom_api_call'
+ );
+ expect(registered.filter((name) => !covered.has(name))).toEqual([]);
+ expect(registered).toHaveLength(55);
+ });
+});
+
+describe('metadata', () => {
+ const actions = Object.values(gitlab.actions()).filter(
+ (action) => action.name !== 'custom_api_call'
+ );
+
+ it('every action declares audience, classification and aiMetadata', () => {
+ for (const action of actions) {
+ expect(action.audience, action.name).toBeDefined();
+ expect(action.classification, action.name).toBeDefined();
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ expect(typeof action.aiMetadata?.idempotent, action.name).toBe('boolean');
+ }
+ });
+
+ it('only create_issue is human; all new atomics are ai and have an outputSchema', () => {
+ expect(
+ actions.filter((a) => a.audience === 'human').map((a) => a.name)
+ ).toEqual(['create_issue']);
+ for (const action of actions) {
+ expect(action.outputSchema, action.name).toBeDefined();
+ }
+ });
+
+ it('destructive verbs are classified DESTRUCTIVE', () => {
+ const destructive = actions
+ .filter((a) => a.classification === 'DESTRUCTIVE')
+ .map((a) => a.name)
+ .sort();
+ expect(destructive).toEqual(
+ [
+ 'delete_branch',
+ 'delete_file',
+ 'delete_issue_note',
+ 'delete_merge_request',
+ 'merge_merge_request',
+ 'reset_issue_spent_time',
+ 'unprotect_branch',
+ ].sort()
+ );
+ });
+
+ it('aiMetadata names only sibling actions that agents can see', () => {
+ const visible = new Set(
+ actions.filter((a) => a.audience !== 'human').map((a) => a.displayName)
+ );
+ const hidden = actions
+ .filter((a) => a.audience === 'human')
+ .map((a) => a.displayName);
+ for (const action of actions.filter((a) => a.audience !== 'human')) {
+ for (const name of hidden) {
+ expect(
+ action.aiMetadata?.description?.includes(`${name} `) &&
+ !visible.has(name),
+ `${action.name} names ${name}`
+ ).toBeFalsy();
+ }
+ }
+ expect(gitlab.minimumSupportedRelease).toBe('0.88.2');
+ });
+});
+
+describe('rule checks', () => {
+ it('update_issue sends clear values and refuses an empty update', async () => {
+ const seen = stubGitlab([{ body: {} }]);
+ await runAction({
+ action: updateIssueAction,
+ propsValue: {
+ ...P,
+ issueIid: 1,
+ clearDescription: true,
+ clearAssignees: true,
+ clearMilestone: true,
+ clearDueDate: true,
+ },
+ });
+ expect(seen[0].body).toEqual({
+ description: '',
+ assignee_ids: [0],
+ milestone_id: 0,
+ due_date: '',
+ });
+ await expect(
+ runAction({
+ action: updateIssueAction,
+ propsValue: { ...P, issueIid: 1, clearDescription: false },
+ })
+ ).rejects.toThrow('Set at least one field');
+ expect(seen).toHaveLength(1);
+ });
+
+ it('update actions unlock the discussion before a state change', async () => {
+ const seen = stubGitlab([{ body: {} }, { body: {} }, { body: {} }]);
+ await runAction({
+ action: updateIssueAction,
+ propsValue: {
+ ...P,
+ issueIid: 1,
+ stateEvent: 'reopen',
+ discussionLocked: 'false',
+ },
+ });
+ await runAction({
+ action: updateMergeRequestAction,
+ propsValue: { ...P, mergeRequestIid: 2, title: 'only a title' },
+ });
+ expect(seen.map((s) => [s.method, rawPath(s), s.body])).toEqual([
+ ['PUT', `${PP}/issues/1`, { discussion_locked: false }],
+ [
+ 'PUT',
+ `${PP}/issues/1`,
+ { state_event: 'reopen', discussion_locked: false },
+ ],
+ ['PUT', `${PP}/merge_requests/2`, { title: 'only a title' }],
+ ]);
+ });
+
+ it('validates IIDs and paging before any request', async () => {
+ const seen = stubGitlab([]);
+ await expect(
+ runAction({ action: getIssueAction, propsValue: { ...P, issueIid: -1 } })
+ ).rejects.toThrow('positive whole number');
+ await expect(
+ runAction({
+ action: listIssuesAction,
+ propsValue: { ...P, perPage: 500 },
+ })
+ ).rejects.toThrow('between 1 and 100');
+ await expect(
+ runAction({
+ action: addIssueSpentTimeAction,
+ propsValue: { ...P, issueIid: 1, duration: 'soon' },
+ })
+ ).rejects.toThrow('duration');
+ await expect(
+ runAction({ action: listUsersAction, propsValue: {} })
+ ).rejects.toThrow('Set Search or Username');
+ await expect(
+ runAction({
+ action: createCommitCommentAction,
+ propsValue: { ...P, sha: 'a', note: 'n', line: 3 },
+ })
+ ).rejects.toThrow('together');
+ await expect(
+ runAction({
+ action: createCommitAction,
+ propsValue: {
+ ...P,
+ branch: 'm',
+ commitMessage: 'x',
+ actions: [{ action: 'nuke', file_path: 'a' }],
+ },
+ })
+ ).rejects.toThrow('action must be one of');
+ await expect(
+ runAction({
+ action: createCommitAction,
+ propsValue: {
+ ...P,
+ branch: 'm',
+ commitMessage: 'x',
+ actions: [{ action: 'move', file_path: 'a' }],
+ },
+ })
+ ).rejects.toThrow('previous_path');
+ await expect(
+ runAction({
+ action: deleteBranchAction,
+ propsValue: { ...P, branch: ' ' },
+ })
+ ).rejects.toThrow('Branch is required');
+ expect(seen).toHaveLength(0);
+ });
+
+ it('unprotect_branch treats 404 as already unprotected and rethrows other errors', async () => {
+ stubGitlab([
+ { status: 404, body: { message: '404 Not found' } },
+ { status: 403, body: { message: 'Forbidden' } },
+ ]);
+ expect(
+ await runAction({
+ action: unprotectBranchAction,
+ propsValue: { ...P, name: 'main' },
+ })
+ ).toEqual({ unprotected: true, alreadyUnprotected: true, name: 'main' });
+ await expect(
+ runAction({
+ action: unprotectBranchAction,
+ propsValue: { ...P, name: 'main' },
+ })
+ ).rejects.toThrow(/HTTP 403/);
+ });
+
+ it('set_user_status reads the current status and keeps omitted fields', async () => {
+ const seen = stubGitlab([
+ {
+ body: {
+ emoji: 'coffee',
+ message: 'Lunch',
+ availability: 'not_set',
+ clear_status_at: null,
+ },
+ },
+ { body: {} },
+ ]);
+ await runAction({
+ action: setUserStatusAction,
+ propsValue: { availability: 'busy' },
+ });
+ expect(seen[0]).toMatchObject({ method: 'GET', path: '/user/status' });
+ expect(seen[1]).toMatchObject({
+ method: 'PUT',
+ path: '/user/status',
+ body: { emoji: 'coffee', message: 'Lunch', availability: 'busy' },
+ });
+ });
+
+ it('set_user_status clears only what is asked', async () => {
+ const seen = stubGitlab([
+ { body: { emoji: 'coffee', message: 'Lunch', availability: 'busy' } },
+ { body: {} },
+ ]);
+ await runAction({
+ action: setUserStatusAction,
+ propsValue: { clearMessage: true, clearStatusAfter: '3_hours' },
+ });
+ expect(seen[1].body).toEqual({
+ emoji: 'coffee',
+ message: '',
+ availability: 'busy',
+ clear_status_after: '3_hours',
+ });
+ });
+
+ it('set_user_status clear-all returns the re-read status instead of the empty PUT body', async () => {
+ const seen = stubGitlab([
+ { status: 200, body: '' },
+ { body: { emoji: null, message: null, availability: null } },
+ ]);
+ const result = await runAction({
+ action: setUserStatusAction,
+ propsValue: { clearAll: true, message: 'ignored' },
+ });
+ expect(seen.map((s) => s.method)).toEqual(['PUT', 'GET']);
+ expect(seen[0].body).toEqual({
+ emoji: '',
+ message: '',
+ availability: 'not_set',
+ });
+ expect(result).toEqual({ emoji: null, message: null, availability: null });
+ });
+
+ it('create_commit_comment reports whether GitLab anchored the comment to the line', async () => {
+ stubGitlab([
+ { body: { note: 'n', path: null, line: null } },
+ { body: { note: 'n', path: 'a.ts', line: 3 } },
+ ]);
+ const props = {
+ ...P,
+ sha: 'a',
+ note: 'n',
+ path: 'a.ts',
+ line: 3,
+ lineType: 'new',
+ };
+ expect(
+ await runAction({ action: createCommitCommentAction, propsValue: props })
+ ).toMatchObject({ lineAnchored: false });
+ expect(
+ await runAction({ action: createCommitCommentAction, propsValue: props })
+ ).toMatchObject({ lineAnchored: true });
+ });
+
+ it('list_merge_requests explains a gitlab.com timeout on a global Scope All search', async () => {
+ stubGitlab([{ status: 408, body: { error: 'Request timed out' } }]);
+ await expect(
+ runAction({
+ action: listMergeRequestsAction,
+ propsValue: { scope: 'all' },
+ })
+ ).rejects.toThrow(/Set Project/);
+ });
+
+ it('get_file reads metadata with HEAD and content from the raw endpoint', async () => {
+ const seen = stubGitlab((entry) =>
+ entry.method === 'HEAD'
+ ? {
+ headers: {
+ 'x-gitlab-file-name': 'a b.ts',
+ 'x-gitlab-file-path': 'src/a b.ts',
+ 'x-gitlab-size': '5',
+ 'x-gitlab-ref': 'main',
+ 'x-gitlab-blob-id': 'b',
+ 'x-gitlab-commit-id': 'c',
+ 'x-gitlab-last-commit-id': 'l',
+ 'x-gitlab-content-sha256': 's',
+ },
+ }
+ : { body: 'hello' }
+ );
+ const result = await runAction({
+ action: getFileAction,
+ propsValue: { ...P, filePath: 'src/a b.ts', ref: 'main' },
+ });
+ expect(seen.map((s) => [s.method, rawPath(s), s.query])).toEqual([
+ ['HEAD', `${PP}/repository/files/src%2Fa%20b.ts`, { ref: 'main' }],
+ ['GET', `${PP}/repository/files/src%2Fa%20b.ts/raw`, { ref: 'main' }],
+ ]);
+ expect(result).toEqual({
+ file_name: 'a b.ts',
+ file_path: 'src/a b.ts',
+ size: 5,
+ ref: 'main',
+ blob_id: 'b',
+ commit_id: 'c',
+ last_commit_id: 'l',
+ content_sha256: 's',
+ content: 'hello',
+ isBinary: false,
+ truncated: false,
+ });
+ });
+
+ it('get_file reports non-ASCII paths and refs exactly', async () => {
+ stubGitlab((entry) =>
+ entry.method === 'HEAD'
+ ? {
+ headers: {
+ 'x-gitlab-file-name': Buffer.from('日本.txt').toString('latin1'),
+ 'x-gitlab-file-path': Buffer.from('ü/日本.txt').toString('latin1'),
+ 'x-gitlab-ref': Buffer.from('fix/ü').toString('latin1'),
+ },
+ }
+ : { body: 'x' }
+ );
+ const result = await runAction({
+ action: getFileAction,
+ propsValue: { ...P, filePath: 'ü/日本.txt', ref: 'fix/ü' },
+ });
+ expect(result).toMatchObject({
+ file_name: '日本.txt',
+ file_path: 'ü/日本.txt',
+ ref: 'fix/ü',
+ });
+ });
+
+ it('file actions keep leading and trailing spaces in the path', async () => {
+ const seen = stubGitlab((entry) =>
+ entry.method === 'HEAD'
+ ? {}
+ : entry.method === 'DELETE'
+ ? { status: 204 }
+ : { body: 'x' }
+ );
+ const read = await runAction({
+ action: getFileAction,
+ propsValue: { ...P, filePath: ' report.txt', ref: 'main' },
+ });
+ expect(read).toMatchObject({
+ file_name: ' report.txt',
+ file_path: ' report.txt',
+ });
+ const deleted = await runAction({
+ action: deleteFileAction,
+ propsValue: {
+ ...P,
+ filePath: ' report.txt',
+ branch: 'main',
+ commitMessage: 'rm',
+ },
+ });
+ await runAction({
+ action: updateFileAction,
+ propsValue: {
+ ...P,
+ filePath: 'report.txt ',
+ branch: 'main',
+ content: 'x',
+ commitMessage: 'u',
+ },
+ });
+ expect(rawPath(seen[0])).toBe(`${PP}/repository/files/%20report.txt`);
+ expect(rawPath(seen[2])).toBe(`${PP}/repository/files/%20report.txt`);
+ expect(deleted).toMatchObject({ file_path: ' report.txt' });
+ expect(rawPath(seen[3])).toBe(`${PP}/repository/files/report.txt%20`);
+ await expect(
+ runAction({
+ action: createFileAction,
+ propsValue: {
+ ...P,
+ filePath: ' ',
+ branch: 'main',
+ content: 'x',
+ commitMessage: 'c',
+ },
+ })
+ ).rejects.toThrow('File Path is required.');
+ });
+
+ it('get_file flags binary content and cuts large text', async () => {
+ const binary = Buffer.from([0x89, 0x50, 0x00, 0x01]);
+ const big = 'a'.repeat(MAX_FILE_TEXT_BYTES + 10);
+ stubGitlab((entry) =>
+ entry.method === 'HEAD'
+ ? {}
+ : { body: entry.path.includes('img') ? binary.toString('latin1') : big }
+ );
+ expect(decodeFilePrefix({ bytes: binary, complete: true })).toMatchObject({
+ content: null,
+ isBinary: true,
+ });
+ const large: { content: string; truncated: boolean } = await runAction({
+ action: getFileAction,
+ propsValue: { ...P, filePath: 'big.txt', ref: 'main' },
+ });
+ expect(large.truncated).toBe(true);
+ expect(large.content.length).toBe(MAX_FILE_TEXT_BYTES);
+ });
+
+ it('get_file stops reading the raw stream once the preview is full', async () => {
+ let pulled = 0;
+ const chunk = new Uint8Array(64 * 1024).fill(0x61);
+ const stream = new ReadableStream<Uint8Array>({
+ pull(controller) {
+ pulled += chunk.byteLength;
+ controller.enqueue(chunk);
+ },
+ });
+ vi.spyOn(gitlabTransport, 'getDispatcher').mockResolvedValue(
+ FAKE_DISPATCHER
+ );
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (_input: string, init: RequestInit) =>
+ init.method === 'HEAD'
+ ? new Response(null, {
+ status: 200,
+ headers: { 'x-gitlab-size': '50000000' },
+ })
+ : new Response(stream, { status: 200 })
+ )
+ );
+ const result: { truncated: boolean; size: number; content: string } =
+ await runAction({
+ action: getFileAction,
+ propsValue: { ...P, filePath: 'huge.txt', ref: 'main' },
+ });
+ expect(result.truncated).toBe(true);
+ expect(result.size).toBe(50_000_000);
+ expect(result.content.length).toBe(MAX_FILE_TEXT_BYTES);
+ expect(pulled).toBeLessThan(MAX_FILE_TEXT_BYTES + 4 * chunk.byteLength);
+ });
+
+ it('decodeFilePrefix keeps strict UTF-8 and only forgives a split character at the cut', () => {
+ const euro = Buffer.from('\u20ac');
+ const split = Buffer.concat([
+ Buffer.alloc(MAX_FILE_TEXT_BYTES - 1, 0x61),
+ euro,
+ ]);
+ const cut = decodeFilePrefix({ bytes: split, complete: false });
+ expect(cut).toMatchObject({ isBinary: false, truncated: true });
+ expect(cut.content?.length).toBe(MAX_FILE_TEXT_BYTES - 1);
+ const invalid = Buffer.concat([
+ Buffer.alloc(9000, 0x61),
+ Buffer.from([0xff, 0xfe]),
+ Buffer.alloc(MAX_FILE_TEXT_BYTES, 0x61),
+ ]);
+ expect(decodeFilePrefix({ bytes: invalid, complete: false })).toMatchObject(
+ { content: null, isBinary: true }
+ );
+ });
+
+ it('list_merge_request_diffs caps each diff and keeps paging from x-next-page', async () => {
+ stubGitlab([
+ {
+ body: [
+ { new_path: 'a', diff: 'x'.repeat(MAX_DIFF_CHARS + 5) },
+ { new_path: 'b', diff: 'small' },
+ ],
+ headers: { 'x-next-page': '2' },
+ },
+ ]);
+ const result: {
+ items: { diff: string; diffTruncated: boolean }[];
+ nextPage: number;
+ } = await runAction({
+ action: listMergeRequestDiffsAction,
+ propsValue: { ...P, mergeRequestIid: 1 },
+ });
+ expect(result.items[0].diff.length).toBe(MAX_DIFF_CHARS);
+ expect(result.items[0].diffTruncated).toBe(true);
+ expect(result.items[1].diffTruncated).toBe(false);
+ expect(result.nextPage).toBe(2);
+ });
+
+ it('approve, merge and create MR surface the documented failure statuses', async () => {
+ stubGitlab([
+ { status: 401, body: { message: '401 Unauthorized' } },
+ { status: 405, body: { message: '405 Method Not Allowed' } },
+ {
+ status: 409,
+ body: {
+ message: [
+ 'Another open merge request already exists for this source branch',
+ ],
+ },
+ },
+ ]);
+ await expect(
+ runAction({
+ action: approveMergeRequestAction,
+ propsValue: { ...P, mergeRequestIid: 1 },
+ })
+ ).rejects.toThrow(/already approved/);
+ await expect(
+ runAction({
+ action: mergeMergeRequestAction,
+ propsValue: { ...P, mergeRequestIid: 1 },
+ })
+ ).rejects.toThrow(/cannot be merged now/);
+ await expect(
+ runAction({
+ action: createMergeRequestAction,
+ propsValue: { ...P, sourceBranch: 'a', targetBranch: 'b', title: 't' },
+ })
+ ).rejects.toThrow(/already exists/);
+ });
+});
diff --git a/packages/pieces/community/gitlab/test/client.test.ts b/packages/pieces/community/gitlab/test/client.test.ts
new file mode 100644
index 00000000000..f0c7994d2d9
--- /dev/null
+++ b/packages/pieces/community/gitlab/test/client.test.ts
@@ -0,0 +1,209 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ encodeSegment,
+ gitlabListPage,
+ gitlabRequest,
+ projectPath,
+} from '../src/lib/common/client';
+import { GITLAB_API_BASE } from '../src/lib/common/constants';
+import {
+ listProjectOptions,
+ gitlabCommon,
+ PROJECT_DROPDOWN_PAGE_CAP,
+} from '../src/lib/common';
+import {
+ buildGitlabUrl,
+ GitlabApiError,
+ sendGitlabRequest,
+} from '../src/lib/common/secret-request';
+import { auth, FAKE_DISPATCHER, stubGitlab } from './helpers';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('base URL and path encoding', () => {
+ it('keeps the API base in one constant', () => {
+ expect(GITLAB_API_BASE).toBe('https://gitlab.com/api/v4');
+ });
+
+ it('encodes a project path so group/project stays one segment', () => {
+ expect(projectPath('my-group/sub group/proj')).toBe(
+ '/projects/my-group%2Fsub%20group%2Fproj'
+ );
+ expect(projectPath(42)).toBe('/projects/42');
+ });
+
+ it('refuses empty and dot segments', () => {
+ expect(() => encodeSegment({ value: ' ', label: 'Branch' })).toThrow(
+ 'Branch is required.'
+ );
+ expect(() => encodeSegment({ value: '..', label: 'Branch' })).toThrow(
+ 'Branch is not valid.'
+ );
+ });
+
+ it('builds URLs only on the GitLab host and refuses traversal or protocol-relative paths', () => {
+ expect(
+ buildGitlabUrl({
+ path: '/projects/1',
+ query: { a: 'x', b: undefined, c: '', d: [1, 2] },
+ })
+ ).toBe('https://gitlab.com/api/v4/projects/1?a=x&d%5B%5D=1&d%5B%5D=2');
+ expect(() => buildGitlabUrl({ path: '//evil.io/x' })).toThrow();
+ expect(() => buildGitlabUrl({ path: '/projects/../../x' })).toThrow();
+ expect(() => buildGitlabUrl({ path: 'projects' })).toThrow();
+ });
+});
+
+describe('transport', () => {
+ it('sends bearer auth, JSON, no redirect following and the verified TLS dispatcher', async () => {
+ const seen = stubGitlab([{ body: { id: 1 } }]);
+ await gitlabRequest({
+ auth,
+ method: 'POST',
+ path: '/projects/1/issues',
+ body: { title: 'x' },
+ });
+ expect(seen[0].headers.get('authorization')).toBe('Bearer TOKEN-123');
+ expect(seen[0].headers.get('content-type')).toBe('application/json');
+ expect(seen[0].redirect).toBe('manual');
+ expect(seen[0].dispatcher).toBe(FAKE_DISPATCHER);
+ });
+
+ it('maps errors to GitlabApiError with status, responseBody and the vendor message', async () => {
+ stubGitlab([{ status: 404, body: { message: '404 Project Not Found' } }]);
+ const error = await gitlabRequest({
+ auth,
+ method: 'GET',
+ path: '/projects/1',
+ }).catch((e) => e);
+ expect(error).toBeInstanceOf(GitlabApiError);
+ expect(error.status).toBe(404);
+ expect(error.responseBody).toEqual({ message: '404 Project Not Found' });
+ expect(error.message).toContain('404 Project Not Found');
+ expect(error).not.toHaveProperty('body');
+ });
+
+ it('uses an action-specific message for a named status', async () => {
+ stubGitlab([
+ {
+ status: 409,
+ body: { message: ['Another open merge request already exists'] },
+ },
+ ]);
+ await expect(
+ gitlabRequest({
+ auth,
+ method: 'POST',
+ path: '/x',
+ statusMessages: { 409: 'Duplicate MR' },
+ })
+ ).rejects.toThrow(
+ /Duplicate MR \(HTTP 409\): \["Another open merge request already exists"\]/
+ );
+ });
+
+ it('does not follow redirects', async () => {
+ stubGitlab([{ status: 302, headers: { location: 'https://evil.io/' } }]);
+ await expect(
+ sendGitlabRequest({ token: 't', method: 'GET', path: '/user' })
+ ).rejects.toThrow(/redirect/);
+ });
+
+ it('returns undefined for 204', async () => {
+ stubGitlab([{ status: 204 }]);
+ expect(
+ await gitlabRequest({ auth, method: 'DELETE', path: '/x' })
+ ).toBeUndefined();
+ });
+});
+
+describe('list paging', () => {
+ it('reads nextPage from x-next-page only and never follows Link', async () => {
+ const seen = stubGitlab([
+ {
+ body: [{ id: 1 }],
+ headers: {
+ 'x-next-page': '3',
+ 'x-total': '41',
+ link: '<https://evil.io/api/v4/projects?page=3>; rel="next"',
+ },
+ },
+ ]);
+ const page = await gitlabListPage({
+ auth,
+ path: '/projects',
+ page: 2,
+ perPage: 20,
+ });
+ expect(page).toEqual({
+ items: [{ id: 1 }],
+ count: 1,
+ page: 2,
+ nextPage: 3,
+ hasMore: true,
+ total: 41,
+ });
+ expect(seen).toHaveLength(1);
+ expect(seen[0].query).toMatchObject({ page: '2', per_page: '20' });
+ });
+
+ it('treats a missing x-total and an empty x-next-page as the last page', async () => {
+ stubGitlab([{ body: [], headers: { 'x-next-page': '' } }]);
+ const page = await gitlabListPage({ auth, path: '/projects' });
+ expect(page).toMatchObject({
+ page: 1,
+ nextPage: null,
+ hasMore: false,
+ total: null,
+ });
+ });
+});
+
+describe('project dropdown', () => {
+ it('pages with per_page 100 and stops at the page cap', async () => {
+ const seen = stubGitlab((request) => ({
+ body: [
+ {
+ id: Number(request.query['page']),
+ name: 'p',
+ name_with_namespace: `g / p${request.query['page']}`,
+ },
+ ],
+ headers: { 'x-next-page': String(Number(request.query['page']) + 1) },
+ }));
+ const result = await listProjectOptions({ auth });
+ expect(seen).toHaveLength(PROJECT_DROPDOWN_PAGE_CAP);
+ expect(seen[0].query).toMatchObject({
+ per_page: '100',
+ membership: 'true',
+ simple: 'true',
+ });
+ expect(result.truncated).toBe(true);
+ expect(result.options[0]).toEqual({ label: 'g / p1', value: 1 });
+ });
+
+ it('passes the search text to GitLab', async () => {
+ const seen = stubGitlab([{ body: [{ id: 5, name: 'api' }] }]);
+ const prop = gitlabCommon.projectId();
+ const state = await Reflect.apply(prop.options, prop, [
+ { auth },
+ { searchValue: 'api' },
+ ]);
+ expect(seen[0].query['search']).toBe('api');
+ expect(state).toMatchObject({
+ disabled: false,
+ options: [{ label: 'api', value: 5 }],
+ });
+ });
+
+ it('returns a disabled state with the reason when GitLab fails', async () => {
+ stubGitlab([{ status: 401, body: { message: '401 Unauthorized' } }]);
+ const prop = gitlabCommon.projectId();
+ const state = await Reflect.apply(prop.options, prop, [{ auth }, {}]);
+ expect(state.disabled).toBe(true);
+ expect(state.placeholder).toContain('401');
+ });
+});
diff --git a/packages/pieces/community/gitlab/test/helpers.ts b/packages/pieces/community/gitlab/test/helpers.ts
new file mode 100644
index 00000000000..cc27b089e21
--- /dev/null
+++ b/packages/pieces/community/gitlab/test/helpers.ts
@@ -0,0 +1,104 @@
+import { MockAgent } from 'undici';
+import { vi } from 'vitest';
+import { gitlabTransport } from '../src/lib/common/secret-request';
+
+export const FAKE_DISPATCHER = new MockAgent();
+
+export const auth = {
+ access_token: 'TOKEN-123',
+ client_id: 'client',
+ client_secret: 'secret',
+ redirect_url: 'http://localhost/redirect',
+ token_type: 'Bearer',
+ claimed_at: 0,
+ refresh_token: 'refresh',
+ scope: 'api read_user',
+ token_url: 'https://gitlab.com/oauth/token',
+ data: {},
+};
+
+export type Seen = {
+ method: string;
+ url: string;
+ path: string;
+ query: Record<string, string | string[]>;
+ headers: Headers;
+ body: unknown;
+ redirect: RequestRedirect | undefined;
+ dispatcher: unknown;
+};
+
+export type Reply = {
+ status?: number;
+ body?: unknown;
+ headers?: Record<string, string>;
+};
+
+export function stubGitlab(replies: Reply[] | ((seen: Seen) => Reply)): Seen[] {
+ const seen: Seen[] = [];
+ const queue = Array.isArray(replies) ? [...replies] : undefined;
+ vi.spyOn(gitlabTransport, 'getDispatcher').mockResolvedValue(FAKE_DISPATCHER);
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ async (input: string, init: RequestInit & { dispatcher?: unknown }) => {
+ const url = new URL(input);
+ const query: Record<string, string | string[]> = {};
+ for (const key of new Set(url.searchParams.keys())) {
+ const all = url.searchParams.getAll(key);
+ query[key] = key.endsWith('[]') ? all : all[0];
+ }
+ const entry: Seen = {
+ method: init.method ?? 'GET',
+ url: url.toString(),
+ path: url.pathname.replace('/api/v4', ''),
+ query,
+ headers: new Headers(init.headers),
+ body:
+ typeof init.body === 'string' ? JSON.parse(init.body) : undefined,
+ redirect: init.redirect,
+ dispatcher: init.dispatcher,
+ };
+ seen.push(entry);
+ const reply = Array.isArray(replies)
+ ? queue?.shift() ?? { status: 200, body: {} }
+ : replies(entry);
+ const status = reply.status ?? 200;
+ const hasBody = reply.body !== undefined && status !== 204;
+ return new Response(
+ hasBody
+ ? typeof reply.body === 'string'
+ ? reply.body
+ : JSON.stringify(reply.body)
+ : null,
+ {
+ status,
+ headers: {
+ ...(hasBody && typeof reply.body !== 'string'
+ ? { 'content-type': 'application/json' }
+ : {}),
+ ...reply.headers,
+ },
+ }
+ );
+ }
+ )
+ );
+ return seen;
+}
+
+type Runnable = { name: string; run: (ctx: never) => Promise<unknown> };
+
+export async function runAction({
+ action,
+ propsValue,
+}: {
+ action: Runnable;
+ propsValue: Record<string, unknown>;
+}) {
+ return Reflect.apply(action.run, action, [{ auth, propsValue }]);
+}
+
+export function rawPath(seen: Seen): string {
+ return new URL(seen.url).pathname.replace('/api/v4', '');
+}
diff --git a/packages/pieces/community/gitlab/test/issue-event.test.ts b/packages/pieces/community/gitlab/test/issue-event.test.ts
new file mode 100644
index 00000000000..bbf7db70bd7
--- /dev/null
+++ b/packages/pieces/community/gitlab/test/issue-event.test.ts
@@ -0,0 +1,246 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { httpClient } from '@activepieces/pieces-common';
+import {
+ ISSUE_TRIGGER_STORE_KEY,
+ isAuthenticDelivery,
+ issuesEventTrigger,
+} from '../src/lib/trigger/issue-event';
+import { isRecord } from '../src/lib/common/secret-request';
+import { auth, stubGitlab } from './helpers';
+
+type Stored = Record<string, unknown>;
+
+function memoryStore(initial?: Stored) {
+ const data = new Map<string, unknown>(initial ? Object.entries(initial) : []);
+ return {
+ data,
+ put: vi.fn(async (key: string, value: unknown) => {
+ data.set(key, value);
+ return value;
+ }),
+ get: vi.fn(async (key: string) => data.get(key) ?? null),
+ delete: vi.fn(async (key: string) => {
+ data.delete(key);
+ }),
+ };
+}
+
+const trigger = {
+ onEnable: async (ctx: unknown): Promise<void> =>
+ Reflect.apply(issuesEventTrigger.onEnable, issuesEventTrigger, [ctx]),
+ onDisable: async (ctx: unknown): Promise<void> =>
+ Reflect.apply(issuesEventTrigger.onDisable, issuesEventTrigger, [ctx]),
+ run: async (ctx: unknown): Promise<unknown[]> =>
+ Reflect.apply(issuesEventTrigger.run, issuesEventTrigger, [ctx]),
+};
+
+const issuePayload = (action: string) => ({
+ object_kind: 'issue',
+ object_attributes: { action, iid: 1 },
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('onEnable', () => {
+ it('creates the hook with a random secret token and confidential issues via native fetch, then stores the token in the same key', async () => {
+ const httpSpy = vi.spyOn(httpClient, 'sendRequest');
+ const seen = stubGitlab([
+ { status: 201, body: { id: 77, url: 'https://ap/webhook' } },
+ ]);
+ const store = memoryStore();
+ await trigger.onEnable({
+ auth,
+ store,
+ propsValue: { projectId: 'grp/proj', actiontype: 'all' },
+ webhookUrl: 'https://ap/webhook',
+ });
+ expect(httpSpy).not.toHaveBeenCalled();
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].path).toBe('/projects/grp%2Fproj/hooks');
+ const body = seen[0].body;
+ const token = isRecord(body) ? body['token'] : undefined;
+ expect(body).toMatchObject({
+ url: 'https://ap/webhook',
+ issues_events: true,
+ confidential_issues_events: true,
+ push_events: false,
+ });
+ expect(typeof token).toBe('string');
+ expect(String(token).length).toBe(64);
+ expect(store.data.get(ISSUE_TRIGGER_STORE_KEY)).toEqual({
+ webhookId: 77,
+ projectId: 'grp/proj',
+ token,
+ });
+ });
+
+ it('deletes the hook it created when storing fails, then rethrows', async () => {
+ const seen = stubGitlab([
+ { status: 201, body: { id: 77 } },
+ { status: 204 },
+ ]);
+ const store = memoryStore();
+ store.put.mockRejectedValueOnce(new Error('store down'));
+ await expect(
+ trigger.onEnable({
+ auth,
+ store,
+ propsValue: { projectId: 5, actiontype: 'all' },
+ webhookUrl: 'https://ap/w',
+ })
+ ).rejects.toThrow('store down');
+ expect(seen[1]).toMatchObject({
+ method: 'DELETE',
+ path: '/projects/5/hooks/77',
+ });
+ });
+
+ it('does not log the secret when GitLab rejects the hook', async () => {
+ const errorLog = vi
+ .spyOn(console, 'error')
+ .mockImplementation(() => undefined);
+ stubGitlab([{ status: 422, body: { message: 'Invalid url' } }]);
+ const error = await trigger
+ .onEnable({
+ auth,
+ store: memoryStore(),
+ propsValue: { projectId: 5, actiontype: 'all' },
+ webhookUrl: 'x',
+ })
+ .catch((e) => e);
+ expect(error.status).toBe(422);
+ expect(errorLog).not.toHaveBeenCalled();
+ });
+});
+
+describe('onDisable', () => {
+ it('awaits the delete and forgets the hook only after it is gone', async () => {
+ const seen = stubGitlab([{ status: 204 }]);
+ const store = memoryStore({
+ [ISSUE_TRIGGER_STORE_KEY]: { webhookId: 9, projectId: 5, token: 't' },
+ });
+ await trigger.onDisable({ auth, store });
+ expect(seen[0]).toMatchObject({
+ method: 'DELETE',
+ path: '/projects/5/hooks/9',
+ });
+ expect(store.data.has(ISSUE_TRIGGER_STORE_KEY)).toBe(false);
+ });
+
+ it('treats 404 as already deleted', async () => {
+ stubGitlab([{ status: 404, body: { message: '404 Not found' } }]);
+ const store = memoryStore({
+ [ISSUE_TRIGGER_STORE_KEY]: { webhookId: '9', projectId: '5' },
+ });
+ await trigger.onDisable({ auth, store });
+ expect(store.data.has(ISSUE_TRIGGER_STORE_KEY)).toBe(false);
+ });
+
+ it('keeps the stored hook and fails when the delete fails', async () => {
+ stubGitlab([{ status: 500, body: { message: 'boom' } }]);
+ const store = memoryStore({
+ [ISSUE_TRIGGER_STORE_KEY]: { webhookId: 9, projectId: 5, token: 't' },
+ });
+ await expect(trigger.onDisable({ auth, store })).rejects.toThrow(
+ /HTTP 500/
+ );
+ expect(store.data.has(ISSUE_TRIGGER_STORE_KEY)).toBe(true);
+ });
+});
+
+describe('run', () => {
+ const store = (token?: string) =>
+ memoryStore({
+ [ISSUE_TRIGGER_STORE_KEY]: {
+ webhookId: 1,
+ projectId: 1,
+ ...(token ? { token } : {}),
+ },
+ });
+
+ it('emits a delivery with the matching X-Gitlab-Token', async () => {
+ const result = await trigger.run({
+ store: store('secret-1'),
+ payload: {
+ headers: { 'X-Gitlab-Token': 'secret-1' },
+ body: issuePayload('open'),
+ },
+ propsValue: { actiontype: 'all' },
+ });
+ expect(result).toHaveLength(1);
+ });
+
+ it('drops a forged delivery without the header', async () => {
+ const result = await trigger.run({
+ store: store('secret-1'),
+ payload: { headers: {}, body: issuePayload('open') },
+ propsValue: { actiontype: 'all' },
+ });
+ expect(result).toEqual([]);
+ });
+
+ it('drops a forged delivery with a wrong header of the same or different length', async () => {
+ for (const token of ['secret-2', 'x']) {
+ const result = await trigger.run({
+ store: store('secret-1'),
+ payload: {
+ headers: { 'x-gitlab-token': token },
+ body: issuePayload('open'),
+ },
+ propsValue: { actiontype: 'all' },
+ });
+ expect(result).toEqual([]);
+ }
+ });
+
+ it('accepts deliveries for legacy hooks stored without a token', async () => {
+ const result = await trigger.run({
+ store: store(),
+ payload: { headers: {}, body: issuePayload('close') },
+ propsValue: { actiontype: 'close' },
+ });
+ expect(result).toHaveLength(1);
+ });
+
+ it('filters by action, supports reopen, and does not throw on payloads without object_attributes', async () => {
+ const reopen = await trigger.run({
+ store: store(),
+ payload: { headers: {}, body: issuePayload('reopen') },
+ propsValue: { actiontype: 'reopen' },
+ });
+ const other = await trigger.run({
+ store: store(),
+ payload: { headers: {}, body: issuePayload('update') },
+ propsValue: { actiontype: 'reopen' },
+ });
+ const odd = await trigger.run({
+ store: store(),
+ payload: { headers: {}, body: { object_kind: 'push' } },
+ propsValue: { actiontype: 'open' },
+ });
+ expect(reopen).toHaveLength(1);
+ expect(other).toEqual([]);
+ expect(odd).toEqual([]);
+ });
+
+ it('compares tokens in constant time only on equal-length buffers', () => {
+ expect(
+ isAuthenticDelivery({
+ storedToken: 'abc',
+ headers: { 'x-gitlab-token': 'abc' },
+ })
+ ).toBe(true);
+ expect(
+ isAuthenticDelivery({
+ storedToken: 'abc',
+ headers: { 'x-gitlab-token': 'abcd' },
+ })
+ ).toBe(false);
+ expect(
+ isAuthenticDelivery({ storedToken: 'abc', headers: undefined })
+ ).toBe(false);
+ });
+});