AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(0codekit): add PDF, QR code, file storage, code, AI text, crypto and short link actions (#16071)
Odai Ahmad55c02467563c
diff --git a/bun.lock b/bun.lockindex c063a3043e3..0f23a6ffe42 100644--- a/bun.lock+++ b/bun.lock@@ -230,7 +230,7 @@},"packages/pieces/community/0codekit": {"name": "@activepieces/piece-0codekit",- "version": "0.0.1",+ "version": "0.1.0","dependencies": {"@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",diff --git a/packages/pieces/community/0codekit/package.json b/packages/pieces/community/0codekit/package.jsonindex da48716a7b2..97ee896c311 100644--- a/packages/pieces/community/0codekit/package.json+++ b/packages/pieces/community/0codekit/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-0codekit",- "version": "0.0.1",+ "version": "0.1.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {diff --git a/packages/pieces/community/0codekit/src/i18n/translation.json b/packages/pieces/community/0codekit/src/i18n/translation.jsonindex 2cd8b2b6db8..dd8fe477c99 100644--- a/packages/pieces/community/0codekit/src/i18n/translation.json+++ b/packages/pieces/community/0codekit/src/i18n/translation.json@@ -1,5 +1,5 @@{- "Ready-made utilities for automations: dates and calendar weeks, conversions and validation.": "Ready-made utilities for automations: dates and calendar weeks, conversions and validation.",+ "Ready-made utilities for automations: dates and calendar weeks, conversions, validation, PDF and QR tools, file storage, AI text and image analysis, code execution, crypto and short links.": "Ready-made utilities for automations: dates and calendar weeks, conversions, validation, PDF and QR tools, file storage, AI text and image analysis, code execution, crypto and short links.","To get your API key:\n1. Log in to your [0CodeKit](https://0codekit.com) account.\n2. Open the **Account** tab. Your API key is shown there.\n3. Copy the key and paste it here.": "To get your API key:\n1. Log in to your [0CodeKit](https://0codekit.com) account.\n2. Open the **Account** tab. Your API key is shown there.\n3. Copy the key and paste it here.","Current Month": "Current Month","Specific Month and Year": "Specific Month and Year",@@ -34,6 +34,47 @@"Get Random Name": "Get Random Name","Get Random Name with Gender": "Get Random Name with Gender","Get a Number": "Get a Number",+ "Gets PDF page count": "Gets PDF page count",+ "Creates a PDF from HTML": "Creates a PDF from HTML",+ "Creates a PDF file from URL": "Creates a PDF file from URL",+ "Merges multiple PDFs": "Merges multiple PDFs",+ "Splits a PDF": "Splits a PDF",+ "Generate a QRCode": "Generate a QRCode",+ "Decode a QRCode": "Decode a QRCode",+ "Image Exif": "Image Exif",+ "Add a Temporary File and Recieve a URL": "Add a Temporary File and Recieve a URL",+ "Add a Global Variable": "Add a Global Variable",+ "Get a Global Variable": "Get a Global Variable",+ "Delete a Global Variable": "Delete a Global Variable",+ "List Global Variables": "List Global Variables",+ "Add a Perm File": "Add a Perm File",+ "Get a Perm File": "Get a Perm File",+ "Delete a Perm File": "Delete a Perm File",+ "List Perm Files": "List Perm Files",+ "Entity Detection": "Entity Detection",+ "Language Detection": "Language Detection",+ "Mood Detection": "Mood Detection",+ "Picture Object Recognition": "Picture Object Recognition",+ "Picture Text Recognition": "Picture Text Recognition",+ "Translate Text": "Translate Text",+ "Run Javascript Code": "Run Javascript Code",+ "Run Python Code": "Run Python Code",+ "Crypto Decrypt": "Crypto Decrypt",+ "Crypto Encrypt": "Crypto Encrypt",+ "Crypto Hash": "Crypto Hash",+ "Create a Scheduler": "Create a Scheduler",+ "Delete a Scheduler": "Delete a Scheduler",+ "List Schedulers": "List Schedulers",+ "Advanced Switch with URL": "Advanced Switch with URL",+ "Create Custom Shortened Url": "Create Custom Shortened Url",+ "Create Shortened Url": "Create Shortened Url",+ "Delete Shortened Url": "Delete Shortened Url",+ "Get a Shortened Url": "Get a Shortened Url",+ "List Shortened Urls": "List Shortened Urls",+ "Update Shortened Url": "Update Shortened Url",+ "URL Expander": "URL Expander",+ "UTM Build": "UTM Build",+ "UTM Parse": "UTM Parse","Custom API Call": "Custom API Call","Get the days, workdays, Saturdays and Sundays of the current month.": "Get the days, workdays, Saturdays and Sundays of the current month.","Get the days, workdays, Saturdays and Sundays of a chosen month.": "Get the days, workdays, Saturdays and Sundays of a chosen month.",@@ -68,6 +109,47 @@"Generate a random person name for test data.": "Generate a random person name for test data.","Generate a random male or female person name for test data.": "Generate a random male or female person name for test data.","Generate a random number between a minimum and a maximum.": "Generate a random number between a minimum and a maximum.",+ "Count the pages in a PDF file.": "Count the pages in a PDF file.",+ "Render HTML markup into a PDF file.": "Render HTML markup into a PDF file.",+ "Capture a web page as a PDF file.": "Capture a web page as a PDF file.",+ "Combine several PDF files into one, in the order you list them.": "Combine several PDF files into one, in the order you list them.",+ "Break a PDF into several smaller PDF files.": "Break a PDF into several smaller PDF files.",+ "Create a QR code image (PNG) from text or a link.": "Create a QR code image (PNG) from text or a link.",+ "Read the text or link stored in a QR code image.": "Read the text or link stored in a QR code image.",+ "Read the EXIF details of a photo, such as camera, date taken and GPS location.": "Read the EXIF details of a photo, such as camera, date taken and GPS location.",+ "Upload a file and get a public download link that expires after 24 hours.": "Upload a file and get a public download link that expires after 24 hours.",+ "Save a value in 0CodeKit so any of your flows can read it later.": "Save a value in 0CodeKit so any of your flows can read it later.",+ "Read the value of a global variable saved in 0CodeKit.": "Read the value of a global variable saved in 0CodeKit.",+ "Permanently remove a global variable from 0CodeKit.": "Permanently remove a global variable from 0CodeKit.",+ "Get every global variable saved in your 0CodeKit account.": "Get every global variable saved in your 0CodeKit account.",+ "Upload a file to 0CodeKit permanent storage and get a lasting download link.": "Upload a file to 0CodeKit permanent storage and get a lasting download link.",+ "Get a file from 0CodeKit permanent storage so later steps can use it.": "Get a file from 0CodeKit permanent storage so later steps can use it.",+ "Permanently remove a file from 0CodeKit permanent storage.": "Permanently remove a file from 0CodeKit permanent storage.",+ "Get every file in your 0CodeKit permanent storage and how much space is left.": "Get every file in your 0CodeKit permanent storage and how much space is left.",+ "Find people, places, organizations, dates and other named entities in a text.": "Find people, places, organizations, dates and other named entities in a text.",+ "Detect which language a text is written in.": "Detect which language a text is written in.",+ "Analyze whether a text sounds positive, neutral or negative.": "Analyze whether a text sounds positive, neutral or negative.",+ "List the objects and things that appear in an image.": "List the objects and things that appear in an image.",+ "Read the text shown in an image (OCR).": "Read the text shown in an image (OCR).",+ "Translate a text into another language.": "Translate a text into another language.",+ "Run JavaScript in a 0CodeKit sandbox (Bun runtime); what it returns is under Result. Each run costs 50 credits and is limited to 180 seconds.": "Run JavaScript in a 0CodeKit sandbox (Bun runtime); what it returns is under Result. Each run costs 50 credits and is limited to 180 seconds.",+ "Run Python in a 0CodeKit sandbox; the value of `result` is under Result. Each run costs 50 credits (the free plan includes 250 credits a month) and is limited to 180 seconds.": "Run Python in a 0CodeKit sandbox; the value of `result` is under Result. Each run costs 50 credits (the free plan includes 250 credits a month) and is limited to 180 seconds.",+ "Decrypt text that was encrypted with a secret key using AES, DES, Triple DES, Rabbit or RC4.": "Decrypt text that was encrypted with a secret key using AES, DES, Triple DES, Rabbit or RC4.",+ "Encrypt text with a secret key using AES, DES, Triple DES, Rabbit or RC4.": "Encrypt text with a secret key using AES, DES, Triple DES, Rabbit or RC4.",+ "Create a hash (MD5, SHA, RIPEMD) or an HMAC signature of a text.": "Create a hash (MD5, SHA, RIPEMD) or an HMAC signature of a text.",+ "Have 0CodeKit call a webhook with your data once, at set times, on a cron schedule, or every n hours, days, weeks or months.": "Have 0CodeKit call a webhook with your data once, at set times, on a cron schedule, or every n hours, days, weeks or months.",+ "Stop a 0CodeKit scheduler so it no longer calls its webhook.": "Stop a 0CodeKit scheduler so it no longer calls its webhook.",+ "Get every active scheduler in your 0CodeKit account.": "Get every active scheduler in your 0CodeKit account.",+ "Look up values by key in a JSON file hosted at a URL.": "Look up values by key in a JSON file hosted at a URL.",+ "Create a short lyl.ai link with your own ending that redirects to a URL.": "Create a short lyl.ai link with your own ending that redirects to a URL.",+ "Create a short lyl.ai link that redirects to a URL.": "Create a short lyl.ai link that redirects to a URL.",+ "Permanently remove a short link so it stops redirecting.": "Permanently remove a short link so it stops redirecting.",+ "Find out where one of your short links redirects to.": "Find out where one of your short links redirects to.",+ "Get every short link created with your 0CodeKit account.": "Get every short link created with your 0CodeKit account.",+ "Change where one of your short links redirects to.": "Change where one of your short links redirects to.",+ "Find the full URL behind a short link from any URL shortener.": "Find the full URL behind a short link from any URL shortener.",+ "Add UTM tracking parameters to a URL.": "Add UTM tracking parameters to a URL.",+ "Read the UTM tracking parameters from a URL.": "Read the UTM tracking parameters from a URL.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Output Date Format": "Output Date Format","Return Unix Timestamps": "Return Unix Timestamps",@@ -120,6 +202,69 @@"Maximum": "Maximum","Number Type": "Number Type","Decimal Places": "Decimal Places",+ "PDF": "PDF",+ "HTML": "HTML",+ "File Name": "File Name",+ "Page Size": "Page Size",+ "Landscape": "Landscape",+ "Print Background": "Print Background",+ "Margin": "Margin",+ "Scale": "Scale",+ "Page Ranges": "Page Ranges",+ "Show Header and Footer": "Show Header and Footer",+ "Web Page URL": "Web Page URL",+ "PDFs": "PDFs",+ "Split By": "Split By",+ "Pages per File": "Pages per File",+ "Content": "Content",+ "Width (px)": "Width (px)",+ "Height (px)": "Height (px)",+ "Margin (px)": "Margin (px)",+ "Error Correction Level": "Error Correction Level",+ "Dot Style": "Dot Style",+ "Dot Color": "Dot Color",+ "Corner Square Style": "Corner Square Style",+ "Corner Square Color": "Corner Square Color",+ "Corner Dot Style": "Corner Dot Style",+ "Corner Dot Color": "Corner Dot Color",+ "Logo URL": "Logo URL",+ "Hide Dots Behind Logo": "Hide Dots Behind Logo",+ "Logo Margin (px)": "Logo Margin (px)",+ "Image File": "Image File",+ "Image URL": "Image URL",+ "File": "File",+ "Variable Name": "Variable Name",+ "Variable Value": "Variable Value",+ "File URL": "File URL",+ "Link Only": "Link Only",+ "Target Language": "Target Language",+ "Markdown": "Markdown",+ "Code": "Code",+ "Inputs": "Inputs",+ "System Packages": "System Packages",+ "Libraries": "Libraries",+ "Algorithm": "Algorithm",+ "Encrypted Text": "Encrypted Text",+ "Secret Key": "Secret Key",+ "Webhook URL": "Webhook URL",+ "Data": "Data",+ "Schedule Type": "Schedule Type",+ "Schedule": "Schedule",+ "End Date": "End Date",+ "Scheduler": "Scheduler",+ "JSON URL": "JSON URL",+ "Keys": "Keys",+ "Destination URL": "Destination URL",+ "Custom Ending": "Custom Ending",+ "Shortened URL": "Shortened URL",+ "New Destination URL": "New Destination URL",+ "Short URL": "Short URL",+ "URL": "URL",+ "Source (utm_source)": "Source (utm_source)",+ "Medium (utm_medium)": "Medium (utm_medium)",+ "Campaign (utm_campaign)": "Campaign (utm_campaign)",+ "Content (utm_content)": "Content (utm_content)",+ "Term (utm_term)": "Term (utm_term)","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters",@@ -187,6 +332,101 @@"The largest number that can be returned.": "The largest number that can be returned.","Whether to return a whole number or a decimal number.": "Whether to return a whole number or a decimal number.","Digits after the decimal point. Only used for decimal numbers.": "Digits after the decimal point. Only used for decimal numbers.",+ "The PDF file to count, from an earlier step or a public URL.": "The PDF file to count, from an earlier step or a public URL.",+ "The HTML to render. Use inline styles and absolute image URLs.": "The HTML to render. Use inline styles and absolute image URLs.",+ "Name of the PDF file to create. Defaults to `document.pdf`.": "Name of the PDF file to create. Defaults to `document.pdf`.",+ "The paper size of the PDF pages.": "The paper size of the PDF pages.",+ "Lay the pages out horizontally instead of vertically.": "Lay the pages out horizontally instead of vertically.",+ "Include background colors and images from the page.": "Include background colors and images from the page.",+ "Space around the content on every side, with a unit such as `1cm`, `10mm`, `0.5in` or `20px`. Leave empty for no margin.": "Space around the content on every side, with a unit such as `1cm`, `10mm`, `0.5in` or `20px`. Leave empty for no margin.",+ "Zoom level of the rendered page, between 0.1 and 2. Leave empty for 1 (actual size).": "Zoom level of the rendered page, between 0.1 and 2. Leave empty for 1 (actual size).",+ "Only keep these pages, for example `1-3,5`. Leave empty to keep all pages.": "Only keep these pages, for example `1-3,5`. Leave empty to keep all pages.",+ "Print the default browser header and footer (date, title, page numbers) on every page.": "Print the default browser header and footer (date, title, page numbers) on every page.",+ "The full address of a public web page, including `https://`.": "The full address of a public web page, including `https://`.",+ "Name of the PDF file to create. Defaults to `webpage.pdf`.": "Name of the PDF file to create. Defaults to `webpage.pdf`.",+ "The PDFs to combine, in the order they should appear.": "The PDFs to combine, in the order they should appear.",+ "Name of the merged PDF file. Defaults to `merged.pdf`.": "Name of the merged PDF file. Defaults to `merged.pdf`.",+ "The PDF file to split, from an earlier step or a public URL.": "The PDF file to split, from an earlier step or a public URL.",+ "How to divide the PDF.": "How to divide the PDF.",+ "Used with **Every N pages**. For example `1` gives one file per page.": "Used with **Every N pages**. For example `1` gives one file per page.",+ "One entry per output file (Page ranges mode). `^1` is the last page.": "One entry per output file (Page ranges mode). `^1` is the last page.",+ "Name prefix for the new files. Parts are named `<prefix>-1.pdf`, `<prefix>-2.pdf`, and so on. Defaults to `part`.": "Name prefix for the new files. Parts are named `<prefix>-1.pdf`, `<prefix>-2.pdf`, and so on. Defaults to `part`.",+ "The text or link to encode in the QR code.": "The text or link to encode in the QR code.",+ "The name of the generated image file. \".png\" is added when missing.": "The name of the generated image file. \".png\" is added when missing.",+ "The width of the image in pixels. Default is 500.": "The width of the image in pixels. Default is 500.",+ "The height of the image in pixels. Default is 500.": "The height of the image in pixels. Default is 500.",+ "Empty space around the QR code, in pixels. Default is 15.": "Empty space around the QR code, in pixels. Default is 15.",+ "How much of the code can be covered and still read. Default is Q.": "How much of the code can be covered and still read. Default is Q.",+ "The shape of the dots that make up the code. Default is square.": "The shape of the dots that make up the code. Default is square.",+ "The color of the dots as a hex code. Default is black.": "The color of the dots as a hex code. Default is black.",+ "The shape of the three large corner squares. Default is square.": "The shape of the three large corner squares. Default is square.",+ "The color of the corner squares as a hex code. Default is black.": "The color of the corner squares as a hex code. Default is black.",+ "The shape of the dot inside each corner square. Default is square.": "The shape of the dot inside each corner square. Default is square.",+ "The color of the corner dots as a hex code. Default is black.": "The color of the corner dots as a hex code. Default is black.",+ "A public image link shown in the middle; use a high error correction.": "A public image link shown in the middle; use a high error correction.",+ "Remove dots behind the logo (default on); needs a Logo URL.": "Remove dots behind the logo (default on); needs a Logo URL.",+ "Space around the logo in pixels (default 0); needs a Logo URL.": "Space around the logo in pixels (default 0); needs a Logo URL.",+ "The QR code image (JPG, PNG, BMP, TIFF or GIF). Use this or Image URL.": "The QR code image (JPG, PNG, BMP, TIFF or GIF). Use this or Image URL.",+ "A public link to the QR code image. Used only when no Image File is provided.": "A public link to the QR code image. Used only when no Image File is provided.",+ "The image to inspect, usually a JPG photo. Use this or Image URL.": "The image to inspect, usually a JPG photo. Use this or Image URL.",+ "A public link to the image. Used only when no Image File is provided.": "A public link to the image. Used only when no Image File is provided.",+ "The file to upload.": "The file to upload.",+ "The uploaded file name, with extension. Empty keeps the original.": "The uploaded file name, with extension. Empty keeps the original.",+ "The name to store the value under. Empty: 0CodeKit picks one.": "The name to store the value under. Empty: 0CodeKit picks one.",+ "The value to store. It is saved as text.": "The value to store. It is saved as text.",+ "The global variable to read.": "The global variable to read.",+ "The global variable to delete.": "The global variable to delete.",+ "The file to upload. Leave empty if you use File URL instead.": "The file to upload. Leave empty if you use File URL instead.",+ "A public link to the file to upload. Used only when File is empty.": "A public link to the file to upload. Used only when File is empty.",+ "The download name, with extension. Empty keeps the original name.": "The download name, with extension. Empty keeps the original name.",+ "The perm file to get.": "The perm file to get.",+ "Turn on to return only the download link without downloading the file.": "Turn on to return only the download link without downloading the file.",+ "The perm file to delete.": "The perm file to delete.",+ "The text to scan for entities.": "The text to scan for entities.",+ "The text whose language you want to detect.": "The text whose language you want to detect.",+ "The text to analyze, such as a review, email or message.": "The text to analyze, such as a review, email or message.",+ "A public link to the image to analyze (JPG, PNG, GIF or WEBP).": "A public link to the image to analyze (JPG, PNG, GIF or WEBP).",+ "A public link to the image to read text from (JPG, PNG, BMP, TIFF or GIF).": "A public link to the image to read text from (JPG, PNG, BMP, TIFF or GIF).",+ "The text to translate. Any source language is detected automatically.": "The text to translate. Any source language is detected automatically.",+ "The language to translate the text into.": "The language to translate the text into.",+ "Send data back with a top-level `return` or by setting the global `result` variable. Later steps find it under **Result**. `console.log` output is discarded. Load npm packages with `require`; they are installed for you.": "Send data back with a top-level `return` or by setting the global `result` variable. Later steps find it under **Result**. `console.log` output is discarded. Load npm packages with `require`; they are installed for you.",+ "The JavaScript to run. Return the value you want to use later.": "The JavaScript to run. Return the value you want to use later.",+ "Data to pass into your code. It is available in the code as the `inputs` variable. Map values from earlier steps here instead of pasting them into the code.": "Data to pass into your code. It is available in the code as the `inputs` variable. Map values from earlier steps here instead of pasting them into the code.",+ "Alpine Linux (apk) packages your code needs, such as `ffmpeg`. Leave empty if you only use language libraries.": "Alpine Linux (apk) packages your code needs, such as `ffmpeg`. Leave empty if you only use language libraries.",+ "Send data back by assigning it to the global `result` variable. Later steps find it under **Result**. `print` output is discarded. Each run costs **50 credits** and is limited to 180 seconds.": "Send data back by assigning it to the global `result` variable. Later steps find it under **Result**. `print` output is discarded. Each run costs **50 credits** and is limited to 180 seconds.",+ "The Python to run. Assign the value you want back to `result`.": "The Python to run. Assign the value you want back to `result`.",+ "Every PyPI package your code imports; auto-detection is unreliable.": "Every PyPI package your code imports; auto-detection is unreliable.",+ "The cipher to use. Decrypt with the same algorithm and secret key that encrypted the text.": "The cipher to use. Decrypt with the same algorithm and secret key that encrypted the text.",+ "The encrypted text to decrypt, such as the Crypto Encrypt output.": "The encrypted text to decrypt, such as the Crypto Encrypt output.",+ "The key (passphrase) that was used to encrypt the text.": "The key (passphrase) that was used to encrypt the text.",+ "The plain text to encrypt.": "The plain text to encrypt.",+ "The key (passphrase) used to encrypt. Keep it safe: you need the same key to decrypt.": "The key (passphrase) used to encrypt. Keep it safe: you need the same key to decrypt.",+ "The hash algorithm. HMAC algorithms also need a secret key.": "The hash algorithm. HMAC algorithms also need a secret key.",+ "The text to hash.": "The text to hash.",+ "The key used to sign the text. Required for HMAC algorithms, ignored otherwise.": "The key used to sign the text. Required for HMAC algorithms, ignored otherwise.",+ "The URL 0CodeKit calls on every run, such as a Catch Webhook URL.": "The URL 0CodeKit calls on every run, such as a Catch Webhook URL.",+ "The JSON data sent to the webhook on every run.": "The JSON data sent to the webhook on every run.",+ "How often the webhook is called. It sets the Schedule format.": "How often the webhook is called. It sets the Schedule format.",+ "**Schedule format** for each Schedule Type:\n- **Once**: an ISO 8601 date or Unix timestamp, for example `2026-12-31T09:00:00Z`.\n- **At several specific dates**: ISO 8601 dates or Unix timestamps separated by commas.\n- **Cron expression**: a cron string, for example `0 9 * * 1` for every Monday at 09:00.\n- **Every n hours, days, weeks or months**: `period;n`, for example `days;2`.": "**Schedule format** for each Schedule Type:\n- **Once**: an ISO 8601 date or Unix timestamp, for example `2026-12-31T09:00:00Z`.\n- **At several specific dates**: ISO 8601 dates or Unix timestamps separated by commas.\n- **Cron expression**: a cron string, for example `0 9 * * 1` for every Monday at 09:00.\n- **Every n hours, days, weeks or months**: `period;n`, for example `days;2`.",+ "When to run, in the format shown above for the Schedule Type.": "When to run, in the format shown above for the Schedule Type.",+ "The last date the scheduler runs. Leave empty to keep it running.": "The last date the scheduler runs. Leave empty to keep it running.",+ "The scheduler to delete.": "The scheduler to delete.",+ "A public link to a JSON file of key-value pairs.": "A public link to a JSON file of key-value pairs.",+ "The keys to look up in the JSON file.": "The keys to look up in the JSON file.",+ "The full URL the short link should redirect to, including `https://`.": "The full URL the short link should redirect to, including `https://`.",+ "The text after `lyl.ai/`. It must not already be taken.": "The text after `lyl.ai/`. It must not already be taken.",+ "The short link to delete.": "The short link to delete.",+ "The short link to look up.": "The short link to look up.",+ "The short link to change.": "The short link to change.",+ "The full URL the short link redirects to from now on.": "The full URL the short link redirects to from now on.",+ "The shortened URL to expand, for example `https://bit.ly/abc123`.": "The shortened URL to expand, for example `https://bit.ly/abc123`.",+ "The page the link should open.": "The page the link should open.",+ "Where the traffic comes from, for example `newsletter` or `google`.": "Where the traffic comes from, for example `newsletter` or `google`.",+ "The marketing channel, for example `email` or `cpc`.": "The marketing channel, for example `email` or `cpc`.",+ "The campaign name, for example `spring_sale`.": "The campaign name, for example `spring_sale`.",+ "Tells apart links in the same campaign, for example `header_button`.": "Tells apart links in the same campaign, for example `header_button`.",+ "The paid search keyword, if any.": "The paid search keyword, if any.",+ "The link with UTM parameters to read.": "The link with UTM parameters to read.","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.",@@ -666,6 +906,94 @@"Male": "Male","Whole number": "Whole number","Decimal number": "Decimal number",+ "A0": "A0",+ "A1": "A1",+ "A2": "A2",+ "A3": "A3",+ "A4": "A4",+ "A5": "A5",+ "A6": "A6",+ "Letter": "Letter",+ "Legal": "Legal",+ "Tabloid": "Tabloid",+ "Ledger": "Ledger",+ "Every N pages": "Every N pages",+ "Page ranges": "Page ranges",+ "Low (7%)": "Low (7%)",+ "Medium (15%)": "Medium (15%)",+ "Quartile (25%)": "Quartile (25%)",+ "High (30%)": "High (30%)",+ "Square": "Square",+ "Dots": "Dots",+ "Rounded": "Rounded",+ "Extra Rounded": "Extra Rounded",+ "Classy": "Classy",+ "Classy Rounded": "Classy Rounded",+ "Dot": "Dot",+ "Arabic (ar)": "Arabic (ar)",+ "Bulgarian (bg)": "Bulgarian (bg)",+ "Chinese (zh)": "Chinese (zh)",+ "Croatian (hr)": "Croatian (hr)",+ "Czech (cs)": "Czech (cs)",+ "Danish (da)": "Danish (da)",+ "Dutch (nl)": "Dutch (nl)",+ "English (en)": "English (en)",+ "Estonian (et)": "Estonian (et)",+ "Finnish (fi)": "Finnish (fi)",+ "French (fr)": "French (fr)",+ "German (de)": "German (de)",+ "Greek (el)": "Greek (el)",+ "Hebrew (he)": "Hebrew (he)",+ "Hindi (hi)": "Hindi (hi)",+ "Hungarian (hu)": "Hungarian (hu)",+ "Indonesian (id)": "Indonesian (id)",+ "Italian (it)": "Italian (it)",+ "Japanese (ja)": "Japanese (ja)",+ "Korean (ko)": "Korean (ko)",+ "Latvian (lv)": "Latvian (lv)",+ "Lithuanian (lt)": "Lithuanian (lt)",+ "Norwegian (no)": "Norwegian (no)",+ "Persian (fa)": "Persian (fa)",+ "Polish (pl)": "Polish (pl)",+ "Portuguese (pt)": "Portuguese (pt)",+ "Romanian (ro)": "Romanian (ro)",+ "Russian (ru)": "Russian (ru)",+ "Serbian (sr)": "Serbian (sr)",+ "Slovak (sk)": "Slovak (sk)",+ "Slovenian (sl)": "Slovenian (sl)",+ "Spanish (es)": "Spanish (es)",+ "Swedish (sv)": "Swedish (sv)",+ "Thai (th)": "Thai (th)",+ "Turkish (tr)": "Turkish (tr)",+ "Ukrainian (uk)": "Ukrainian (uk)",+ "Urdu (ur)": "Urdu (ur)",+ "Vietnamese (vi)": "Vietnamese (vi)",+ "AES": "AES",+ "DES": "DES",+ "TripleDES": "TripleDES",+ "Rabbit": "Rabbit",+ "RC4": "RC4",+ "RC4Drop": "RC4Drop",+ "MD5": "MD5",+ "SHA-1": "SHA-1",+ "SHA-224": "SHA-224",+ "SHA-256": "SHA-256",+ "SHA-3": "SHA-3",+ "SHA-384": "SHA-384",+ "SHA-512": "SHA-512",+ "RIPEMD-160": "RIPEMD-160",+ "HMAC MD5": "HMAC MD5",+ "HMAC SHA-1": "HMAC SHA-1",+ "HMAC SHA-224": "HMAC SHA-224",+ "HMAC SHA-256": "HMAC SHA-256",+ "HMAC SHA-3": "HMAC SHA-3",+ "HMAC SHA-384": "HMAC SHA-384",+ "HMAC SHA-512": "HMAC SHA-512",+ "HMAC RIPEMD-160": "HMAC RIPEMD-160",+ "Once": "Once",+ "At several specific dates": "At several specific dates",+ "Cron expression": "Cron expression",+ "Every n hours, days, weeks or months": "Every n hours, days, weeks or months","GET": "GET","POST": "POST","PATCH": "PATCH",diff --git a/packages/pieces/community/0codekit/src/index.ts b/packages/pieces/community/0codekit/src/index.tsindex dc59ad53e85..96690fccc00 100644--- a/packages/pieces/community/0codekit/src/index.ts+++ b/packages/pieces/community/0codekit/src/index.ts@@ -1,5 +1,11 @@import { createCustomApiCallAction } from '@activepieces/pieces-common';import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { entityDetectionAction } from './lib/actions/ai/entity-detection';+import { languageDetectionAction } from './lib/actions/ai/language-detection';+import { moodDetectionAction } from './lib/actions/ai/mood-detection';+import { pictureObjectRecognitionAction } from './lib/actions/ai/picture-object-recognition';+import { pictureTextRecognitionAction } from './lib/actions/ai/picture-text-recognition';+import { translateTextAction } from './lib/actions/ai/translate-text';import { lookupVatRatesAction } from './lib/actions/business/lookup-vat-rates';import { validateBicAction } from './lib/actions/business/validate-bic';import { validateEmailAction } from './lib/actions/business/validate-email';@@ -9,11 +15,16 @@ import { validateVatWithCountryCodeAction } from './lib/actions/business/validatimport { verifyDomainAction } from './lib/actions/business/verify-domain';import { calculateBmiAction } from './lib/actions/calculate/calculate-bmi';import { calculateGeoDistanceAction } from './lib/actions/calculate/calculate-geo-distance';+import { runJavascriptCodeAction } from './lib/actions/code/run-javascript-code';+import { runPythonCodeAction } from './lib/actions/code/run-python-code';import { convertCsvToJsonAction } from './lib/actions/convert/convert-csv-to-json';import { convertCurrencyAction } from './lib/actions/convert/convert-currency';import { convertIpToGeoAction } from './lib/actions/convert/convert-ip-to-geo';import { convertIsoToNationAction } from './lib/actions/convert/convert-iso-to-nation';import { convertNationToIsoAction } from './lib/actions/convert/convert-nation-to-iso';+import { cryptoDecryptAction } from './lib/actions/crypto/crypto-decrypt';+import { cryptoEncryptAction } from './lib/actions/crypto/crypto-encrypt';+import { cryptoHashAction } from './lib/actions/crypto/crypto-hash';import { convertTimezoneWithDateAction } from './lib/actions/date-and-time/convert-timezone-with-date';import { convertTimezoneWithUnixTimestampAction } from './lib/actions/date-and-time/convert-timezone-with-unix-timestamp';import { currentMonthAction } from './lib/actions/date-and-time/current-month';@@ -30,16 +41,46 @@ import { getANumberAction } from './lib/actions/generate/get-a-number';import { getRandomCityAction } from './lib/actions/generate/get-random-city';import { getRandomNameAction } from './lib/actions/generate/get-random-name';import { getRandomNameWithGenderAction } from './lib/actions/generate/get-random-name-with-gender';+import { decodeQrCodeAction } from './lib/actions/image/decode-qr-code';+import { generateQrCodeAction } from './lib/actions/image/generate-qr-code';+import { imageExifAction } from './lib/actions/image/image-exif';+import { createPdfFromHtmlAction } from './lib/actions/pdf/create-pdf-from-html';+import { createPdfFromUrlAction } from './lib/actions/pdf/create-pdf-from-url';+import { getPdfPageCountAction } from './lib/actions/pdf/get-pdf-page-count';+import { mergePdfsAction } from './lib/actions/pdf/merge-pdfs';+import { splitPdfAction } from './lib/actions/pdf/split-pdf';+import { createASchedulerAction } from './lib/actions/scheduler/create-a-scheduler';+import { deleteASchedulerAction } from './lib/actions/scheduler/delete-a-scheduler';+import { listSchedulersAction } from './lib/actions/scheduler/list-schedulers';+import { addAGlobalVariableAction } from './lib/actions/storage/add-a-global-variable';+import { addAPermFileAction } from './lib/actions/storage/add-a-perm-file';+import { deleteAGlobalVariableAction } from './lib/actions/storage/delete-a-global-variable';+import { deleteAPermFileAction } from './lib/actions/storage/delete-a-perm-file';+import { getAGlobalVariableAction } from './lib/actions/storage/get-a-global-variable';+import { getAPermFileAction } from './lib/actions/storage/get-a-perm-file';+import { listGlobalVariablesAction } from './lib/actions/storage/list-global-variables';+import { listPermFilesAction } from './lib/actions/storage/list-perm-files';+import { addTemporaryFileAction } from './lib/actions/temp-file/add-temporary-file';import { detectGenderAction } from './lib/actions/text/detect-gender';import { splitNameAction } from './lib/actions/text/split-name';import { textContainsAction } from './lib/actions/text/text-contains';+import { advancedSwitchWithUrlAction } from './lib/actions/url/advanced-switch-with-url';+import { createCustomShortenedUrlAction } from './lib/actions/url/create-custom-shortened-url';+import { createShortenedUrlAction } from './lib/actions/url/create-shortened-url';+import { deleteShortenedUrlAction } from './lib/actions/url/delete-shortened-url';+import { getAShortenedUrlAction } from './lib/actions/url/get-a-shortened-url';+import { listShortenedUrlsAction } from './lib/actions/url/list-shortened-urls';+import { updateShortenedUrlAction } from './lib/actions/url/update-shortened-url';+import { urlExpanderAction } from './lib/actions/url/url-expander';+import { utmBuildAction } from './lib/actions/url/utm-build';+import { utmParseAction } from './lib/actions/url/utm-parse';import { zeroCodeKitAuth } from './lib/auth';import { ZEROCODEKIT_BASE_URL, zeroCodeKitApi } from './lib/common/client';export const zeroCodeKit = createPiece({displayName: '0CodeKit',description:- 'Ready-made utilities for automations: dates and calendar weeks, conversions and validation.',+ 'Ready-made utilities for automations: dates and calendar weeks, conversions, validation, PDF and QR tools, file storage, AI text and image analysis, code execution, crypto and short links.',minimumSupportedRelease: '0.82.0',logoUrl: 'https://cdn.activepieces.com/pieces/0codekit.png',categories: [PieceCategory.DEVELOPER_TOOLS, PieceCategory.PRODUCTIVITY],@@ -79,6 +120,47 @@ export const zeroCodeKit = createPiece({getRandomNameAction,getRandomNameWithGenderAction,getANumberAction,+ getPdfPageCountAction,+ createPdfFromHtmlAction,+ createPdfFromUrlAction,+ mergePdfsAction,+ splitPdfAction,+ generateQrCodeAction,+ decodeQrCodeAction,+ imageExifAction,+ addTemporaryFileAction,+ addAGlobalVariableAction,+ getAGlobalVariableAction,+ deleteAGlobalVariableAction,+ listGlobalVariablesAction,+ addAPermFileAction,+ getAPermFileAction,+ deleteAPermFileAction,+ listPermFilesAction,+ entityDetectionAction,+ languageDetectionAction,+ moodDetectionAction,+ pictureObjectRecognitionAction,+ pictureTextRecognitionAction,+ translateTextAction,+ runJavascriptCodeAction,+ runPythonCodeAction,+ cryptoDecryptAction,+ cryptoEncryptAction,+ cryptoHashAction,+ createASchedulerAction,+ deleteASchedulerAction,+ listSchedulersAction,+ advancedSwitchWithUrlAction,+ createCustomShortenedUrlAction,+ createShortenedUrlAction,+ deleteShortenedUrlAction,+ getAShortenedUrlAction,+ listShortenedUrlsAction,+ updateShortenedUrlAction,+ urlExpanderAction,+ utmBuildAction,+ utmParseAction,createCustomApiCallAction({baseUrl: () => ZEROCODEKIT_BASE_URL,auth: zeroCodeKitAuth,diff --git a/packages/pieces/community/0codekit/src/lib/actions/ai/entity-detection.ts b/packages/pieces/community/0codekit/src/lib/actions/ai/entity-detection.tsnew file mode 100644index 00000000000..25af64a5e35--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/ai/entity-detection.ts@@ -0,0 +1,52 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitAi } from '../../common/ai';+import { zeroCodeKitApi } from '../../common/client';+import { businessAiOutputSchemas } from '../../common/output-schemas/business-ai';++export const entityDetectionAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'entity_detection',+ classification: 'READ',+ displayName: 'Entity Detection',+ description: 'Find people, places, organizations, dates and other named entities in a text.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Run named-entity recognition on a text and return every entity found (for example a person, location, organization, date, quantity, email or URL) with its category, optional sub-category, character offset, length and a confidence score between 0 and 1. Nothing is stored; safe to retry.',+ idempotent: true,+ },+ props: {+ text: zeroCodeKitAi.textProp({ description: 'The text to scan for entities.' }),+ },+ outputSchema: businessAiOutputSchemas.entityDetection,+ async run({ auth, propsValue }) {+ const text = zeroCodeKitAi.requireText({ value: propsValue.text, label: 'Text' });+ const leadingWhitespace = (propsValue.text ?? '').length - (propsValue.text ?? '').trimStart().length;+ const response = await zeroCodeKitApi.post<EntityDetectionResponse>({+ apiKey: auth.secret_text,+ path: '/ai/entitydetection',+ body: { text },+ });+ const entities = (response.detections ?? []).map((detection) => ({+ text: detection.text ?? null,+ category: detection.category ?? null,+ sub_category: detection.subCategory ?? null,+ offset: typeof detection.offset === 'number' ? detection.offset + leadingWhitespace : null,+ length: detection.length ?? null,+ confidence_score: detection.confidenceScore ?? null,+ }));+ return { entity_count: entities.length, entities };+ },+});++type EntityDetectionResponse = {+ detections?: {+ text?: string;+ category?: string;+ subCategory?: string;+ offset?: number;+ length?: number;+ confidenceScore?: number;+ }[];+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/ai/language-detection.ts b/packages/pieces/community/0codekit/src/lib/actions/ai/language-detection.tsnew file mode 100644index 00000000000..3bbabe462ae--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/ai/language-detection.ts@@ -0,0 +1,41 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitAi } from '../../common/ai';+import { zeroCodeKitApi } from '../../common/client';+import { businessAiOutputSchemas } from '../../common/output-schemas/business-ai';++export const languageDetectionAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'language_detection',+ classification: 'READ',+ displayName: 'Language Detection',+ description: 'Detect which language a text is written in.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Detect the main language of a text and return its English name, its two-letter ISO 639-1 code (for example `en`, `de`) and a confidence score between 0 and 1. Nothing is stored; safe to retry.',+ idempotent: true,+ },+ props: {+ text: zeroCodeKitAi.textProp({ description: 'The text whose language you want to detect.' }),+ },+ outputSchema: businessAiOutputSchemas.languageDetection,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<LanguageDetectionResponse>({+ apiKey: auth.secret_text,+ path: '/ai/languagedetection',+ body: { text: zeroCodeKitAi.requireText({ value: propsValue.text, label: 'Text' }) },+ });+ return {+ language_name: response.name ?? null,+ language_code: response.iso6391Name ?? null,+ confidence_score: response.confidenceScore ?? null,+ };+ },+});++type LanguageDetectionResponse = {+ name?: string;+ iso6391Name?: string;+ confidenceScore?: number;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/ai/mood-detection.ts b/packages/pieces/community/0codekit/src/lib/actions/ai/mood-detection.tsnew file mode 100644index 00000000000..af66a95d530--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/ai/mood-detection.ts@@ -0,0 +1,53 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitAi } from '../../common/ai';+import { zeroCodeKitApi } from '../../common/client';+import { businessAiOutputSchemas } from '../../common/output-schemas/business-ai';++export const moodDetectionAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'mood_detection',+ classification: 'READ',+ displayName: 'Mood Detection',+ description: 'Analyze whether a text sounds positive, neutral or negative.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Run sentiment analysis on a text. Returns the overall mood (typically `positive`, `neutral`, `negative` or `mixed`), a score between 0 and 1 for each of positive, neutral and negative, and the mood of every sentence. Nothing is stored; safe to retry.',+ idempotent: true,+ },+ props: {+ text: zeroCodeKitAi.textProp({ description: 'The text to analyze, such as a review, email or message.' }),+ },+ outputSchema: businessAiOutputSchemas.moodDetection,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<MoodDetectionResponse>({+ apiKey: auth.secret_text,+ path: '/ai/mooddetection',+ body: { text: zeroCodeKitAi.requireText({ value: propsValue.text, label: 'Text' }) },+ });+ return {+ mood: response.moodOverall ?? null,+ positive_score: response.moodScore?.positive ?? null,+ neutral_score: response.moodScore?.neutral ?? null,+ negative_score: response.moodScore?.negative ?? null,+ sentences: (response.moodPerSentence ?? []).map((sentence) => ({+ text: sentence.text ?? null,+ mood: sentence.mood ?? null,+ })),+ };+ },+});++type MoodDetectionResponse = {+ moodOverall?: string;+ moodScore?: {+ positive?: number;+ neutral?: number;+ negative?: number;+ };+ moodPerSentence?: {+ mood?: string;+ text?: string;+ }[];+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/ai/picture-object-recognition.ts b/packages/pieces/community/0codekit/src/lib/actions/ai/picture-object-recognition.tsnew file mode 100644index 00000000000..20043bc3671--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/ai/picture-object-recognition.ts@@ -0,0 +1,38 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitAi } from '../../common/ai';+import { zeroCodeKitApi } from '../../common/client';+import { businessAiOutputSchemas } from '../../common/output-schemas/business-ai';++export const pictureObjectRecognitionAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'picture_object_recognition',+ classification: 'READ',+ displayName: 'Picture Object Recognition',+ description: 'List the objects and things that appear in an image.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Look at an image reachable by a public URL and return a list of short labels describing the objects, scenes and concepts it shows (for example `dog`, `beach`, `sunset`). The image must be a publicly accessible link; files from earlier steps are not accepted by this endpoint. Nothing is stored; safe to retry, though labels can vary slightly between calls.',+ idempotent: true,+ },+ props: {+ imageUrl: zeroCodeKitAi.imageUrlProp({+ description: 'A public link to the image to analyze (JPG, PNG, GIF or WEBP).',+ }),+ },+ outputSchema: businessAiOutputSchemas.pictureObjectRecognition,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<PictureObjectRecognitionResponse>({+ apiKey: auth.secret_text,+ path: '/ai/pictureobjectrecognition',+ body: { imageUrl: zeroCodeKitAi.requireText({ value: propsValue.imageUrl, label: 'Image URL' }) },+ });+ const labels = zeroCodeKitAi.stringList(response.recognizedLabels);+ return { label_count: labels.length, labels };+ },+});++type PictureObjectRecognitionResponse = {+ recognizedLabels?: unknown;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/ai/picture-text-recognition.ts b/packages/pieces/community/0codekit/src/lib/actions/ai/picture-text-recognition.tsnew file mode 100644index 00000000000..b4f2f06f0a4--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/ai/picture-text-recognition.ts@@ -0,0 +1,38 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitAi } from '../../common/ai';+import { zeroCodeKitApi } from '../../common/client';+import { businessAiOutputSchemas } from '../../common/output-schemas/business-ai';++export const pictureTextRecognitionAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'picture_text_recognition',+ classification: 'READ',+ displayName: 'Picture Text Recognition',+ description: 'Read the text shown in an image (OCR).',+ audience: 'both',+ aiMetadata: {+ description:+ 'Run optical character recognition on an image reachable by a public URL and return every line of text found, both as a list and joined into one text with line breaks. The image must be a publicly accessible link; files from earlier steps are not accepted by this endpoint. Nothing is stored; safe to retry.',+ idempotent: true,+ },+ props: {+ imageUrl: zeroCodeKitAi.imageUrlProp({+ description: 'A public link to the image to read text from (JPG, PNG, BMP, TIFF or GIF).',+ }),+ },+ outputSchema: businessAiOutputSchemas.pictureTextRecognition,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<PictureTextRecognitionResponse>({+ apiKey: auth.secret_text,+ path: '/ai/picturetextrecognition',+ body: { imageUrl: zeroCodeKitAi.requireText({ value: propsValue.imageUrl, label: 'Image URL' }) },+ });+ const lines = zeroCodeKitAi.stringList(response.recognizedTexts);+ return { text: lines.join('\n'), line_count: lines.length, lines };+ },+});++type PictureTextRecognitionResponse = {+ recognizedTexts?: unknown;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/ai/translate-text.ts b/packages/pieces/community/0codekit/src/lib/actions/ai/translate-text.tsnew file mode 100644index 00000000000..6e479e36a09--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/ai/translate-text.ts@@ -0,0 +1,42 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitAi } from '../../common/ai';+import { zeroCodeKitApi } from '../../common/client';+import { businessAiOutputSchemas } from '../../common/output-schemas/business-ai';++export const translateTextAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'translate_text',+ classification: 'READ',+ displayName: 'Translate Text',+ description: 'Translate a text into another language.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Translate a text into the chosen target language, given as a two-letter ISO 639-1 code (for example `es` for Spanish, `de` for German). The source language is detected automatically. Returns only the translated text. Nothing is stored; safe to retry, though wording can vary slightly between calls.',+ idempotent: true,+ },+ props: {+ text: zeroCodeKitAi.textProp({ description: 'The text to translate. Any source language is detected automatically.' }),+ resultLang: zeroCodeKitAi.targetLanguageProp(),+ },+ outputSchema: businessAiOutputSchemas.translateText,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<TranslateResponse>({+ apiKey: auth.secret_text,+ path: '/ai/translate',+ body: {+ text: zeroCodeKitAi.requireText({ value: propsValue.text, label: 'Text' }),+ resultLang: zeroCodeKitAi.requireText({ value: propsValue.resultLang, label: 'Target Language' }),+ },+ });+ return {+ translation: response.translation ?? null,+ target_language: propsValue.resultLang,+ };+ },+});++type TranslateResponse = {+ translation?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/code/run-javascript-code.ts b/packages/pieces/community/0codekit/src/lib/actions/code/run-javascript-code.tsnew file mode 100644index 00000000000..a0c01a78206--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/code/run-javascript-code.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitCode } from '../../common/code';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const runJavascriptCodeAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'run_javascript_code',+ classification: 'WRITE',+ displayName: 'Run Javascript Code',+ description:+ 'Run JavaScript in a 0CodeKit sandbox (Bun runtime); what it returns is under Result. Each run costs 50 credits and is limited to 180 seconds.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Execute JavaScript on the 0CodeKit Bun sandbox. Returns `{ result }`, where `result` is the value produced by a top-level `return` or the global `result` variable (null when nothing is returned). npm packages load through `require` and install automatically. Use for computations or libraries you cannot do directly; each call costs 50 credits, runs for at most 180 seconds, and repeats any side effects the code has.',+ idempotent: false,+ },+ props: {+ instructions: Property.MarkDown({+ value: 'Send data back with a top-level `return` or by setting the global `result` variable. Later steps find it under **Result**. `console.log` output is discarded. Load npm packages with `require`; they are installed for you.',+ }),+ code: Property.LongText({+ displayName: 'Code',+ description: 'The JavaScript to run. Return the value you want to use later.',+ required: true,+ placeholder: 'return { total: inputs.a + 1 };',+ }),+ inputs: zeroCodeKitCode.inputsProp({ variable: 'inputs' }),+ dependencies: zeroCodeKitCode.dependenciesProp(),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.codeResult,+ async run({ auth, propsValue }) {+ const dependencies = zeroCodeKitCode.stringList(propsValue.dependencies);+ const body = await zeroCodeKitCode.execute({+ apiKey: auth.secret_text,+ path: '/code/javascript',+ body: {+ code: zeroCodeKitCode.withJavascriptInputs({ code: propsValue.code, inputs: propsValue.inputs }),+ ...(dependencies.length > 0 ? { dependencies } : {}),+ },+ });+ return zeroCodeKitCode.javascriptResult(body);+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/code/run-python-code.ts b/packages/pieces/community/0codekit/src/lib/actions/code/run-python-code.tsnew file mode 100644index 00000000000..6862a9e1c75--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/code/run-python-code.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitCode } from '../../common/code';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const runPythonCodeAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'run_python_code',+ classification: 'WRITE',+ displayName: 'Run Python Code',+ description:+ 'Run Python in a 0CodeKit sandbox; the value of `result` is under Result. Each run costs 50 credits (the free plan includes 250 credits a month) and is limited to 180 seconds.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Execute Python (CPython) on the 0CodeKit sandbox. Returns `{ result }`, where `result` is the value assigned to the global `result` variable (null when nothing is assigned). List PyPI packages in Libraries so they are installed before the run. Use for computations or libraries you cannot do directly; each call costs 50 credits, runs for at most 180 seconds, and repeats any side effects the code has.',+ idempotent: false,+ },+ props: {+ instructions: Property.MarkDown({+ value: 'Send data back by assigning it to the global `result` variable. Later steps find it under **Result**. `print` output is discarded. Each run costs **50 credits** and is limited to 180 seconds.',+ }),+ code: Property.LongText({+ displayName: 'Code',+ description: 'The Python to run. Assign the value you want back to `result`.',+ required: true,+ placeholder: 'result = {"total": inputs["a"] + 1}',+ }),+ inputs: zeroCodeKitCode.inputsProp({ variable: 'inputs' }),+ requirements: Property.Array({+ displayName: 'Libraries',+ description: 'Every PyPI package your code imports; auto-detection is unreliable.',+ required: false,+ placeholder: 'pandas==2.2.2',+ }),+ dependencies: zeroCodeKitCode.dependenciesProp(),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.codeResult,+ async run({ auth, propsValue }) {+ const requirements = zeroCodeKitCode.stringList(propsValue.requirements);+ const dependencies = zeroCodeKitCode.stringList(propsValue.dependencies);+ const body = await zeroCodeKitCode.execute({+ apiKey: auth.secret_text,+ path: '/code/python',+ body: {+ code: zeroCodeKitCode.withPythonInputs({ code: propsValue.code, inputs: propsValue.inputs }),+ ...(requirements.length > 0 ? { requirements } : {}),+ ...(dependencies.length > 0 ? { dependencies } : {}),+ },+ });+ return zeroCodeKitCode.pythonResult(body);+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/crypto/crypto-decrypt.ts b/packages/pieces/community/0codekit/src/lib/actions/crypto/crypto-decrypt.tsnew file mode 100644index 00000000000..d9cdeedfb9f--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/crypto/crypto-decrypt.ts@@ -0,0 +1,50 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitCrypto } from '../../common/crypto';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const cryptoDecryptAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'crypto_decrypt',+ classification: 'READ',+ displayName: 'Crypto Decrypt',+ description: 'Decrypt text that was encrypted with a secret key using AES, DES, Triple DES, Rabbit or RC4.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Decrypt ciphertext produced by Crypto Encrypt (or any CryptoJS-compatible passphrase cipher) back to plain text. The algorithm and secret key must match the ones used to encrypt; a wrong key yields empty or garbled text. Pure transform with no side effects, safe to retry.',+ idempotent: true,+ },+ props: {+ cryptoType: zeroCodeKitCrypto.cipher(),+ ciphertext: Property.LongText({+ displayName: 'Encrypted Text',+ description: 'The encrypted text to decrypt, such as the Crypto Encrypt output.',+ required: true,+ }),+ secretKey: zeroCodeKitCrypto.secretKey({+ description: 'The key (passphrase) that was used to encrypt the text.',+ required: true,+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.cryptoDecrypt,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<DecryptResponse>({+ apiKey: auth.secret_text,+ path: '/crypto/decrypt',+ body: {+ cryptoType: propsValue.cryptoType,+ ciphertext: propsValue.ciphertext,+ secretKey: propsValue.secretKey,+ },+ });+ return {+ decrypted_text: response.decryptedText,+ };+ },+});++type DecryptResponse = {+ decryptedText: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/crypto/crypto-encrypt.ts b/packages/pieces/community/0codekit/src/lib/actions/crypto/crypto-encrypt.tsnew file mode 100644index 00000000000..7fb0ca4df1e--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/crypto/crypto-encrypt.ts@@ -0,0 +1,50 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitCrypto } from '../../common/crypto';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const cryptoEncryptAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'crypto_encrypt',+ classification: 'READ',+ displayName: 'Crypto Encrypt',+ description: 'Encrypt text with a secret key using AES, DES, Triple DES, Rabbit or RC4.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Encrypt plaintext with a symmetric cipher (AES by default) and a secret key, returning the ciphertext as text. Pair with Crypto Decrypt using the same algorithm and key; for one-way fingerprints use Crypto Hash instead. Pure transform with no side effects, safe to retry.',+ idempotent: true,+ },+ props: {+ cryptoType: zeroCodeKitCrypto.cipher(),+ message: Property.LongText({+ displayName: 'Text',+ description: 'The plain text to encrypt.',+ required: true,+ }),+ secretKey: zeroCodeKitCrypto.secretKey({+ description: 'The key (passphrase) used to encrypt. Keep it safe: you need the same key to decrypt.',+ required: true,+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.cryptoEncrypt,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<EncryptResponse>({+ apiKey: auth.secret_text,+ path: '/crypto/encrypt',+ body: {+ cryptoType: propsValue.cryptoType,+ message: propsValue.message,+ secretKey: propsValue.secretKey,+ },+ });+ return {+ encrypted_text: response.encryptedText,+ };+ },+});++type EncryptResponse = {+ encryptedText: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/crypto/crypto-hash.ts b/packages/pieces/community/0codekit/src/lib/actions/crypto/crypto-hash.tsnew file mode 100644index 00000000000..2a74a66bb42--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/crypto/crypto-hash.ts@@ -0,0 +1,64 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { HASH_TYPES, zeroCodeKitCrypto } from '../../common/crypto';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const cryptoHashAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'crypto_hash',+ classification: 'READ',+ displayName: 'Crypto Hash',+ description: 'Create a hash (MD5, SHA, RIPEMD) or an HMAC signature of a text.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Compute a one-way hash (MD5, SHA-1/2/3, RIPEMD-160) of a text, or an HMAC signature when an HMAC algorithm and secret key are given, for example to verify webhook signatures. Use Crypto Encrypt instead when the text must be recoverable. Pure transform, safe to retry.',+ idempotent: true,+ },+ props: {+ hashType: Property.StaticDropdown({+ displayName: 'Algorithm',+ description: 'The hash algorithm. HMAC algorithms also need a secret key.',+ required: true,+ defaultValue: 'SHA256',+ options: {+ options: HASH_TYPES,+ },+ }),+ message: Property.LongText({+ displayName: 'Text',+ description: 'The text to hash.',+ required: true,+ }),+ secretKey: zeroCodeKitCrypto.secretKey({+ description: 'The key used to sign the text. Required for HMAC algorithms, ignored otherwise.',+ required: false,+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.cryptoHash,+ async run({ auth, propsValue }) {+ const hmac = zeroCodeKitCrypto.isHmac(propsValue.hashType);+ const secretKey = propsValue.secretKey ?? '';+ if (hmac && secretKey === '') {+ throw new Error(`${propsValue.hashType} needs a Secret Key. Enter one, or pick a non-HMAC algorithm.`);+ }+ const response = await zeroCodeKitApi.post<HashResponse>({+ apiKey: auth.secret_text,+ path: '/crypto/hash',+ body: {+ hashType: propsValue.hashType,+ message: propsValue.message,+ secretKey: hmac ? secretKey : undefined,+ },+ });+ return {+ hashed_text: response.hashedText,+ algorithm: propsValue.hashType,+ };+ },+});++type HashResponse = {+ hashedText: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/image/decode-qr-code.ts b/packages/pieces/community/0codekit/src/lib/actions/image/decode-qr-code.tsnew file mode 100644index 00000000000..b8870982915--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/image/decode-qr-code.ts@@ -0,0 +1,40 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitImage } from '../../common/image';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const decodeQrCodeAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'decode_qr_code',+ classification: 'READ',+ displayName: 'Decode a QRCode',+ description: 'Read the text or link stored in a QR code image.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Decode a QR code image and return the text it contains (often a URL). Provide the image either as a file from an earlier step or as a public image URL; if both are given the file is used. Supported formats: JPG, PNG, BMP, TIFF, GIF. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ file: zeroCodeKitImage.imageFileProp({+ description: 'The QR code image (JPG, PNG, BMP, TIFF or GIF). Use this or Image URL.',+ }),+ url: zeroCodeKitImage.imageUrlProp({+ description: 'A public link to the QR code image. Used only when no Image File is provided.',+ }),+ },+ outputSchema: filesStorageOutputSchemas.decodedQrCode,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<DecodeQrCodeResponse>({+ apiKey: auth.secret_text,+ path: '/generate/qrcode/decode',+ body: zeroCodeKitImage.imageSource({ file: propsValue.file, url: propsValue.url }),+ });+ return { data: response.data ?? null };+ },+});++type DecodeQrCodeResponse = {+ data?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/image/generate-qr-code.ts b/packages/pieces/community/0codekit/src/lib/actions/image/generate-qr-code.tsnew file mode 100644index 00000000000..fd446d530f2--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/image/generate-qr-code.ts@@ -0,0 +1,184 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitFiles } from '../../common/files';+import { zeroCodeKitImage } from '../../common/image';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const generateQrCodeAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'generate_qr_code',+ classification: 'READ',+ displayName: 'Generate a QRCode',+ description: 'Create a QR code image (PNG) from text or a link.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Generate a styled QR code PNG image that encodes the given text or URL. Optional settings control size, margin, colors, dot and corner styles, error correction and a logo placed in the middle. Returns a file reference to the PNG that later steps can attach or upload. Creates nothing in any external account and is safe to retry.',+ idempotent: true,+ },+ props: {+ data: Property.LongText({+ displayName: 'Content',+ description: 'The text or link to encode in the QR code.',+ required: true,+ }),+ fileName: Property.ShortText({+ displayName: 'File Name',+ description: 'The name of the generated image file. ".png" is added when missing.',+ required: false,+ defaultValue: 'qr-code.png',+ }),+ width: Property.Number({+ displayName: 'Width (px)',+ description: 'The width of the image in pixels. Default is 500.',+ required: false,+ }),+ height: Property.Number({+ displayName: 'Height (px)',+ description: 'The height of the image in pixels. Default is 500.',+ required: false,+ }),+ margin: Property.Number({+ displayName: 'Margin (px)',+ description: 'Empty space around the QR code, in pixels. Default is 15.',+ required: false,+ }),+ errorCorrectionLevel: Property.StaticDropdown({+ displayName: 'Error Correction Level',+ description: 'How much of the code can be covered and still read. Default is Q.',+ required: false,+ options: {+ options: [+ { label: 'Low (7%)', value: 'L' },+ { label: 'Medium (15%)', value: 'M' },+ { label: 'Quartile (25%)', value: 'Q' },+ { label: 'High (30%)', value: 'H' },+ ],+ },+ }),+ dotsType: Property.StaticDropdown({+ displayName: 'Dot Style',+ description: 'The shape of the dots that make up the code. Default is square.',+ required: false,+ options: {+ options: [+ { label: 'Square', value: 'square' },+ { label: 'Dots', value: 'dots' },+ { label: 'Rounded', value: 'rounded' },+ { label: 'Extra Rounded', value: 'extra-rounded' },+ { label: 'Classy', value: 'classy' },+ { label: 'Classy Rounded', value: 'classy-rounded' },+ ],+ },+ }),+ dotsColor: Property.ShortText({+ displayName: 'Dot Color',+ description: 'The color of the dots as a hex code. Default is black.',+ required: false,+ placeholder: '#000000',+ }),+ cornersSquareType: Property.StaticDropdown({+ displayName: 'Corner Square Style',+ description: 'The shape of the three large corner squares. Default is square.',+ required: false,+ options: {+ options: [+ { label: 'Square', value: 'square' },+ { label: 'Extra Rounded', value: 'extra-rounded' },+ { label: 'Dot', value: 'dot' },+ ],+ },+ }),+ cornersSquareColor: Property.ShortText({+ displayName: 'Corner Square Color',+ description: 'The color of the corner squares as a hex code. Default is black.',+ required: false,+ placeholder: '#000000',+ }),+ cornersDotType: Property.StaticDropdown({+ displayName: 'Corner Dot Style',+ description: 'The shape of the dot inside each corner square. Default is square.',+ required: false,+ options: {+ options: [+ { label: 'Square', value: 'square' },+ { label: 'Dot', value: 'dot' },+ ],+ },+ }),+ cornersDotColor: Property.ShortText({+ displayName: 'Corner Dot Color',+ description: 'The color of the corner dots as a hex code. Default is black.',+ required: false,+ placeholder: '#000000',+ }),+ image: Property.ShortText({+ displayName: 'Logo URL',+ description: 'A public image link shown in the middle; use a high error correction.',+ required: false,+ placeholder: 'https://example.com/logo.png',+ }),+ hideBackgroundDots: Property.Checkbox({+ displayName: 'Hide Dots Behind Logo',+ description: 'Remove dots behind the logo (default on); needs a Logo URL.',+ required: false,+ defaultValue: true,+ }),+ imageMargin: Property.Number({+ displayName: 'Logo Margin (px)',+ description: 'Space around the logo in pixels (default 0); needs a Logo URL.',+ required: false,+ }),+ },+ outputSchema: filesStorageOutputSchemas.generatedQrCode,+ async run({ auth, propsValue, files }) {+ const hasImage = (propsValue.image ?? '').trim() !== '';+ const binary = await zeroCodeKitFiles.postForBinary({+ apiKey: auth.secret_text,+ path: '/generate/qrcode/encode',+ body: compact({+ data: propsValue.data,+ width: propsValue.width,+ height: propsValue.height,+ margin: propsValue.margin,+ image: hasImage ? (propsValue.image ?? '').trim() : undefined,+ qrOptions: compact({ errorCorrectionLevel: propsValue.errorCorrectionLevel }),+ dotsOptions: compact({ type: propsValue.dotsType, color: hexColor(propsValue.dotsColor) }),+ cornersSquareOptions: compact({+ type: propsValue.cornersSquareType,+ color: hexColor(propsValue.cornersSquareColor),+ }),+ cornersDotOptions: compact({+ type: propsValue.cornersDotType,+ color: hexColor(propsValue.cornersDotColor),+ }),+ imageOptions: hasImage+ ? compact({+ hideBackgroundDots: propsValue.hideBackgroundDots,+ margin: propsValue.imageMargin,+ })+ : undefined,+ }),+ });+ const image = await zeroCodeKitImage.resolveImage(binary);+ const saved = await zeroCodeKitFiles.save({+ files,+ fileName: zeroCodeKitFiles.withExtension({ name: (propsValue.fileName ?? '').trim() || 'qr-code', extension: 'png' }),+ data: image.data,+ });+ return { ...saved, image_url: image.imageUrl };+ },+});++function hexColor(value: string | undefined): string | undefined {+ const trimmed = (value ?? '').trim();+ if (trimmed === '') {+ return undefined;+ }+ return trimmed.startsWith('#') ? trimmed : `#${trimmed}`;+}++function compact(body: Record<string, unknown>): Record<string, unknown> | undefined {+ const entries = Object.entries(body).filter(([, value]) => value !== undefined && value !== null && value !== '');+ return entries.length === 0 ? undefined : Object.fromEntries(entries);+}diff --git a/packages/pieces/community/0codekit/src/lib/actions/image/image-exif.ts b/packages/pieces/community/0codekit/src/lib/actions/image/image-exif.tsnew file mode 100644index 00000000000..f9c4032a1a5--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/image/image-exif.ts@@ -0,0 +1,40 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitImage } from '../../common/image';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const imageExifAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'image_exif',+ classification: 'READ',+ displayName: 'Image Exif',+ description: 'Read the EXIF details of a photo, such as camera, date taken and GPS location.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Extract the EXIF metadata embedded in an image (camera make and model, capture date, exposure, GPS coordinates, and so on). Provide the image as a file from an earlier step or as a public image URL; if both are given the file is used. Returns the EXIF tags as an object, empty when the image has none. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ file: zeroCodeKitImage.imageFileProp({+ description: 'The image to inspect, usually a JPG photo. Use this or Image URL.',+ }),+ url: zeroCodeKitImage.imageUrlProp({+ description: 'A public link to the image. Used only when no Image File is provided.',+ }),+ },+ outputSchema: filesStorageOutputSchemas.imageExif,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<ImageExifResponse>({+ apiKey: auth.secret_text,+ path: '/image/exif',+ body: zeroCodeKitImage.imageSource({ file: propsValue.file, url: propsValue.url }),+ });+ return { exif_data: response.exifData ?? {} };+ },+});++type ImageExifResponse = {+ exifData?: unknown;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/pdf/create-pdf-from-html.ts b/packages/pieces/community/0codekit/src/lib/actions/pdf/create-pdf-from-html.tsnew file mode 100644index 00000000000..da59c7c0214--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/pdf/create-pdf-from-html.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitFiles } from '../../common/files';+import { zeroCodeKitPdf } from '../../common/pdf';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const createPdfFromHtmlAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'create_pdf_from_html',+ classification: 'WRITE',+ displayName: 'Creates a PDF from HTML',+ description: 'Render HTML markup into a PDF file.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Render an HTML document (inline CSS and absolute image URLs supported) into a PDF and return it as a file. Pass the HTML source itself, not a web address; use "Creates a PDF file from URL" for live pages. Creates a new file on every call.',+ idempotent: false,+ },+ props: {+ html: Property.LongText({+ displayName: 'HTML',+ description: 'The HTML to render. Use inline styles and absolute image URLs.',+ required: true,+ placeholder: '<h1>Invoice</h1><p style="color: gray">Thank you!</p>',+ }),+ fileName: zeroCodeKitPdf.fileName({ description: 'Name of the PDF file to create. Defaults to `document.pdf`.' }),+ ...zeroCodeKitPdf.renderProps(),+ },+ outputSchema: filesStorageOutputSchemas.createdPdf,+ async run({ auth, propsValue, files }) {+ const html = zeroCodeKitPdf.clean(propsValue.html);+ if (html === undefined) {+ throw new Error('HTML is required.');+ }+ const data = await zeroCodeKitFiles.postForBinary({+ apiKey: auth.secret_text,+ path: '/pdf/html',+ body: {+ html,+ getAsUrl: false,+ options: zeroCodeKitPdf.renderOptions(propsValue),+ },+ });+ return zeroCodeKitFiles.save({+ files,+ fileName: zeroCodeKitFiles.withExtension({+ name: zeroCodeKitPdf.baseName({ name: propsValue.fileName, fallback: 'document' }),+ extension: 'pdf',+ }),+ data,+ });+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/pdf/create-pdf-from-url.ts b/packages/pieces/community/0codekit/src/lib/actions/pdf/create-pdf-from-url.tsnew file mode 100644index 00000000000..5b0dfb1b587--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/pdf/create-pdf-from-url.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitFiles } from '../../common/files';+import { zeroCodeKitPdf } from '../../common/pdf';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const createPdfFromUrlAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'create_pdf_from_url',+ classification: 'WRITE',+ displayName: 'Creates a PDF file from URL',+ description: 'Capture a web page as a PDF file.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Open a public web page in a browser and print it to a PDF file. Pass the full page address including https://. Pages behind a login cannot be captured. Creates a new file on every call.',+ idempotent: false,+ },+ props: {+ url: Property.ShortText({+ displayName: 'Web Page URL',+ description: 'The full address of a public web page, including `https://`.',+ required: true,+ placeholder: 'https://example.com',+ }),+ fileName: zeroCodeKitPdf.fileName({ description: 'Name of the PDF file to create. Defaults to `webpage.pdf`.' }),+ ...zeroCodeKitPdf.renderProps(),+ },+ outputSchema: filesStorageOutputSchemas.createdPdf,+ async run({ auth, propsValue, files }) {+ const url = zeroCodeKitPdf.clean(propsValue.url);+ if (url === undefined || !/^https?:\/\//i.test(url)) {+ throw new Error('Web Page URL must be a full address starting with http:// or https://.');+ }+ const data = await zeroCodeKitFiles.postForBinary({+ apiKey: auth.secret_text,+ path: '/pdf/html',+ body: {+ url,+ getAsUrl: false,+ options: zeroCodeKitPdf.renderOptions(propsValue),+ },+ });+ return zeroCodeKitFiles.save({+ files,+ fileName: zeroCodeKitFiles.withExtension({+ name: zeroCodeKitPdf.baseName({ name: propsValue.fileName, fallback: 'webpage' }),+ extension: 'pdf',+ }),+ data,+ });+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/pdf/get-pdf-page-count.ts b/packages/pieces/community/0codekit/src/lib/actions/pdf/get-pdf-page-count.tsnew file mode 100644index 00000000000..16ef7d09ef7--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/pdf/get-pdf-page-count.ts@@ -0,0 +1,41 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitFiles } from '../../common/files';+import { zeroCodeKitPdf } from '../../common/pdf';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const getPdfPageCountAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'get_pdf_page_count',+ classification: 'READ',+ displayName: 'Gets PDF page count',+ description: 'Count the pages in a PDF file.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Return the number of pages in a PDF. Pass the PDF as a file from an earlier step or as a public URL to the file. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ pdf: zeroCodeKitPdf.pdfFile({+ displayName: 'PDF',+ description: 'The PDF file to count, from an earlier step or a public URL.',+ }),+ },+ outputSchema: filesStorageOutputSchemas.pdfPageCount,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<PageCountResponse>({+ apiKey: auth.secret_text,+ path: '/pdf/count',+ body: {+ buffer: zeroCodeKitFiles.toBase64(propsValue.pdf),+ },+ });+ return { page_count: response.pageCount ?? null };+ },+});++type PageCountResponse = {+ pageCount?: number;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/pdf/merge-pdfs.ts b/packages/pieces/community/0codekit/src/lib/actions/pdf/merge-pdfs.tsnew file mode 100644index 00000000000..017afe567db--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/pdf/merge-pdfs.ts@@ -0,0 +1,85 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitFiles } from '../../common/files';+import { zeroCodeKitPdf } from '../../common/pdf';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const mergePdfsAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'merge_pdfs',+ classification: 'WRITE',+ displayName: 'Merges multiple PDFs',+ description: 'Combine several PDF files into one, in the order you list them.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Combine two or more PDFs into a single PDF file, in list order. Each entry takes a PDF file or public URL and optional page ranges such as "1-3,5" (^1 means the last page). Creates a new file on every call.',+ idempotent: false,+ },+ props: {+ pdfs: Property.Array({+ displayName: 'PDFs',+ description: 'The PDFs to combine, in the order they should appear.',+ required: true,+ properties: {+ file: Property.File({+ displayName: 'PDF',+ description: 'A PDF file from an earlier step or a public URL.',+ required: true,+ }),+ pages: Property.ShortText({+ displayName: 'Pages',+ description: 'Pages to include, for example `1-3,5`. `^1` is the last page. Leave empty to include all pages.',+ required: false,+ }),+ },+ }),+ fileName: zeroCodeKitPdf.fileName({ description: 'Name of the merged PDF file. Defaults to `merged.pdf`.' }),+ },+ outputSchema: filesStorageOutputSchemas.mergedPdf,+ async run({ auth, propsValue, files }) {+ const entries = (propsValue.pdfs ?? []).map((item, index) => toMergeEntry({ item, index }));+ if (entries.length < 2) {+ throw new Error('Add at least two PDFs to merge.');+ }+ const data = await zeroCodeKitFiles.postForBinary({+ apiKey: auth.secret_text,+ path: '/pdf/merge',+ body: {+ files: entries,+ getAsUrl: false,+ },+ });+ return {+ ...(await zeroCodeKitFiles.save({+ files,+ fileName: zeroCodeKitFiles.withExtension({+ name: zeroCodeKitPdf.baseName({ name: propsValue.fileName, fallback: 'merged' }),+ extension: 'pdf',+ }),+ data,+ })),+ merged_count: entries.length,+ };+ },+});++function toMergeEntry({ item, index }: { item: unknown; index: number }): MergeEntry {+ const file = isRecord(item) ? item['file'] : undefined;+ if (!zeroCodeKitPdf.isApFile(file)) {+ throw new Error(`PDF #${index + 1} is missing a file.`);+ }+ const pages = isRecord(item) && typeof item['pages'] === 'string' ? zeroCodeKitPdf.clean(item['pages']) : undefined;+ return pages === undefined+ ? { buffer: zeroCodeKitFiles.toBase64(file) }+ : { buffer: zeroCodeKitFiles.toBase64(file), pages };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++type MergeEntry = {+ buffer: string;+ pages?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/pdf/split-pdf.ts b/packages/pieces/community/0codekit/src/lib/actions/pdf/split-pdf.tsnew file mode 100644index 00000000000..5138201297f--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/pdf/split-pdf.ts@@ -0,0 +1,112 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi, ZEROCODEKIT_TIMEOUT_MS } from '../../common/client';+import { zeroCodeKitFiles } from '../../common/files';+import { zeroCodeKitPdf } from '../../common/pdf';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const splitPdfAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'split_pdf',+ classification: 'WRITE',+ displayName: 'Splits a PDF',+ description: 'Break a PDF into several smaller PDF files.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Split one PDF into several PDF files, either every N pages or by explicit page ranges (one range per output file, such as "1-3" or "4,6"; ^1 means the last page). Returns a list of files, one per part. Creates new files on every call.',+ idempotent: false,+ },+ props: {+ pdf: zeroCodeKitPdf.pdfFile({+ displayName: 'PDF',+ description: 'The PDF file to split, from an earlier step or a public URL.',+ }),+ mode: Property.StaticDropdown({+ displayName: 'Split By',+ description: 'How to divide the PDF.',+ required: true,+ defaultValue: 'interval',+ options: {+ options: [+ { label: 'Every N pages', value: 'interval' },+ { label: 'Page ranges', value: 'pages' },+ ],+ },+ }),+ interval: Property.Number({+ displayName: 'Pages per File',+ description: 'Used with **Every N pages**. For example `1` gives one file per page.',+ required: false,+ defaultValue: 1,+ }),+ pageRanges: Property.Array({+ displayName: 'Page Ranges',+ description: 'One entry per output file (Page ranges mode). `^1` is the last page.',+ required: false,+ placeholder: '1-3',+ }),+ fileName: zeroCodeKitPdf.fileName({+ description: 'Name prefix for the new files. Parts are named `<prefix>-1.pdf`, `<prefix>-2.pdf`, and so on. Defaults to `part`.',+ }),+ },+ outputSchema: filesStorageOutputSchemas.splitPdf,+ async run({ auth, propsValue, files }) {+ const deadline = Date.now() + SPLIT_BUDGET_MS;+ const response = await zeroCodeKitApi.post<SplitResponse>({+ apiKey: auth.secret_text,+ path: '/pdf/split',+ body: {+ buffer: zeroCodeKitFiles.toBase64(propsValue.pdf),+ ...splitRule({ mode: propsValue.mode, interval: propsValue.interval, pageRanges: propsValue.pageRanges }),+ },+ });+ const urls = response.pdfUrls ?? [];+ const prefix = zeroCodeKitPdf.baseName({ name: propsValue.fileName, fallback: 'part' });+ const saved = [];+ for (const url of urls) {+ zeroCodeKitFiles.assertZeroCodeKitUrl(url);+ }+ for (const [index, url] of urls.entries()) {+ const remaining = deadline - Date.now();+ if (remaining <= 0) {+ throw new Error(+ `Downloading the ${urls.length} split parts took too long; ${saved.length} were saved. Split into fewer, larger parts.`,+ );+ }+ const data = await zeroCodeKitPdf.download({ url, timeoutMs: Math.min(remaining, ZEROCODEKIT_TIMEOUT_MS.file) });+ saved.push(await zeroCodeKitFiles.save({ files, fileName: `${prefix}-${index + 1}.pdf`, data }));+ }+ return saved;+ },+});++function splitRule({+ mode,+ interval,+ pageRanges,+}: {+ mode: string;+ interval: number | undefined;+ pageRanges: unknown[] | undefined;+}): Record<string, unknown> {+ if (mode === 'pages') {+ const pages = (pageRanges ?? [])+ .map((range) => (typeof range === 'string' || typeof range === 'number' ? String(range).trim() : ''))+ .filter((range) => range !== '');+ if (pages.length === 0) {+ throw new Error('Add at least one page range, for example 1-3.');+ }+ return { pages };+ }+ if (interval === undefined || interval === null || !Number.isInteger(interval) || interval < 1) {+ throw new Error('Pages per File must be a whole number of 1 or more.');+ }+ return { interval };+}++const SPLIT_BUDGET_MS = 480_000;++type SplitResponse = {+ pdfUrls?: string[];+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/scheduler/create-a-scheduler.ts b/packages/pieces/community/0codekit/src/lib/actions/scheduler/create-a-scheduler.tsnew file mode 100644index 00000000000..37f2cc08ba9--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/scheduler/create-a-scheduler.ts@@ -0,0 +1,93 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { CRON, MULTIPLE_TIMES, ONE_TIME, RECURRING, zeroCodeKitScheduler } from '../../common/scheduler';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const createASchedulerAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'create_a_scheduler',+ classification: 'WRITE',+ displayName: 'Create a Scheduler',+ description: 'Have 0CodeKit call a webhook with your data once, at set times, on a cron schedule, or every n hours, days, weeks or months.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Create a 0CodeKit scheduler task that POSTs the given JSON data to a webhook URL on a schedule: once, at a list of dates, by cron expression, or every n periods. Returns the task_id needed to delete it later. Each call creates a new task, so retries create duplicates.',+ idempotent: false,+ },+ props: {+ sendToWebhook: Property.ShortText({+ displayName: 'Webhook URL',+ description: 'The URL 0CodeKit calls on every run, such as a Catch Webhook URL.',+ required: true,+ placeholder: 'https://example.com/webhook',+ }),+ data: Property.Json({+ displayName: 'Data',+ description: 'The JSON data sent to the webhook on every run.',+ required: false,+ defaultValue: {},+ }),+ intervalType: Property.StaticDropdown({+ displayName: 'Schedule Type',+ description: 'How often the webhook is called. It sets the Schedule format.',+ required: true,+ defaultValue: ONE_TIME,+ options: {+ options: [+ { label: 'Once', value: ONE_TIME },+ { label: 'At several specific dates', value: MULTIPLE_TIMES },+ { label: 'Cron expression', value: CRON },+ { label: 'Every n hours, days, weeks or months', value: RECURRING },+ ],+ },+ }),+ scheduleFormats: Property.MarkDown({+ value: `**Schedule format** for each Schedule Type:+- **Once**: an ISO 8601 date or Unix timestamp, for example \`2026-12-31T09:00:00Z\`.+- **At several specific dates**: ISO 8601 dates or Unix timestamps separated by commas.+- **Cron expression**: a cron string, for example \`0 9 * * 1\` for every Monday at 09:00.+- **Every n hours, days, weeks or months**: \`period;n\`, for example \`days;2\`.`,+ }),+ schedule: Property.ShortText({+ displayName: 'Schedule',+ description: 'When to run, in the format shown above for the Schedule Type.',+ required: true,+ placeholder: '2026-12-31T09:00:00Z',+ }),+ endDate: Property.DateTime({+ displayName: 'End Date',+ description: 'The last date the scheduler runs. Leave empty to keep it running.',+ required: false,+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.createScheduler,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<CreateTaskResponse>({+ apiKey: auth.secret_text,+ path: '/operator/scheduler/add',+ body: {+ sendToWebhook: propsValue.sendToWebhook.trim(),+ data: zeroCodeKitScheduler.stringifyData(propsValue.data),+ intervalType: Number(propsValue.intervalType),+ intervalOptions: zeroCodeKitScheduler.parseSchedule({+ intervalType: propsValue.intervalType,+ schedule: propsValue.schedule,+ }),+ endDate: propsValue.endDate,+ },+ });+ return {+ task_id: response.taskId,+ next_execution: response.nextExecution,+ end_date: response.endDate ?? null,+ };+ },+});++type CreateTaskResponse = {+ taskId: string;+ nextExecution: string;+ endDate?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/scheduler/delete-a-scheduler.ts b/packages/pieces/community/0codekit/src/lib/actions/scheduler/delete-a-scheduler.tsnew file mode 100644index 00000000000..cab0a4b94f5--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/scheduler/delete-a-scheduler.ts@@ -0,0 +1,43 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitScheduler } from '../../common/scheduler';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const deleteASchedulerAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'delete_a_scheduler',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete a Scheduler',+ description: 'Stop a 0CodeKit scheduler so it no longer calls its webhook.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Delete a scheduler task, identified by its task_id from Create a Scheduler or List Schedulers, so its webhook is no longer called. Cannot be undone. Fails if the task no longer exists.',+ idempotent: false,+ },+ props: {+ taskId: zeroCodeKitScheduler.taskId({+ description: 'The scheduler to delete.',+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.deleteScheduler,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<DeleteTaskResponse>({+ apiKey: auth.secret_text,+ path: '/operator/scheduler/del',+ body: {+ taskId: propsValue.taskId,+ },+ });+ return {+ deleted: true,+ task_id: propsValue.taskId,+ message: response.message ?? null,+ };+ },+});++type DeleteTaskResponse = {+ message?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/scheduler/list-schedulers.ts b/packages/pieces/community/0codekit/src/lib/actions/scheduler/list-schedulers.tsnew file mode 100644index 00000000000..7596240f569--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/scheduler/list-schedulers.ts@@ -0,0 +1,27 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitScheduler } from '../../common/scheduler';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const listSchedulersAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'list_schedulers',+ classification: 'SEARCH',+ displayName: 'List Schedulers',+ description: 'Get every active scheduler in your 0CodeKit account.',+ audience: 'both',+ aiMetadata: {+ description:+ 'List all active scheduler tasks in the connected 0CodeKit account, each with its task_id, webhook URL, next run time and data, plus the total count. Takes no input. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {},+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.listSchedulers,+ async run({ auth }) {+ const tasks = await zeroCodeKitScheduler.listTasks(auth.secret_text);+ return {+ count: tasks.length,+ schedulers: tasks.map(zeroCodeKitScheduler.toTask),+ };+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/storage/add-a-global-variable.ts b/packages/pieces/community/0codekit/src/lib/actions/storage/add-a-global-variable.tsnew file mode 100644index 00000000000..75c9b501ada--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/storage/add-a-global-variable.ts@@ -0,0 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { GlobalVariable, zeroCodeKitStorage } from '../../common/storage';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const addAGlobalVariableAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'add_a_global_variable',+ classification: 'WRITE',+ displayName: 'Add a Global Variable',+ description: 'Save a value in 0CodeKit so any of your flows can read it later.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Create a global variable stored in the connected 0CodeKit account and return its name and value. If no name is given, 0CodeKit generates one; use the returned variable_name to read or delete it later. Values are stored as text. Creates a new record on each call, so do not retry blindly.',+ idempotent: false,+ },+ props: {+ variableName: Property.ShortText({+ displayName: 'Variable Name',+ description: 'The name to store the value under. Empty: 0CodeKit picks one.',+ required: false,+ }),+ variableValue: Property.LongText({+ displayName: 'Variable Value',+ description: 'The value to store. It is saved as text.',+ required: true,+ }),+ },+ outputSchema: filesStorageOutputSchemas.globalVariable,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<GlobalVariable>({+ apiKey: auth.secret_text,+ path: '/storage/globalvariables/add',+ body: {+ variableName: propsValue.variableName?.trim(),+ variableValue: propsValue.variableValue,+ },+ });+ return zeroCodeKitStorage.toVariable(response);+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/storage/add-a-perm-file.ts b/packages/pieces/community/0codekit/src/lib/actions/storage/add-a-perm-file.tsnew file mode 100644index 00000000000..c8de9ddc373--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/storage/add-a-perm-file.ts@@ -0,0 +1,63 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitFiles } from '../../common/files';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const addAPermFileAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'add_a_perm_file',+ classification: 'WRITE',+ displayName: 'Add a Perm File',+ description: 'Upload a file to 0CodeKit permanent storage and get a lasting download link.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Upload a file to permanent storage in the connected 0CodeKit account, either from a file or from a public URL, and return its file_id and a permanent download url. Provide exactly one of File or File URL. Each call stores a new copy and uses storage quota, so do not retry blindly.',+ idempotent: false,+ },+ props: {+ file: Property.File({+ displayName: 'File',+ description: 'The file to upload. Leave empty if you use File URL instead.',+ required: false,+ }),+ fileUrl: Property.ShortText({+ displayName: 'File URL',+ description: 'A public link to the file to upload. Used only when File is empty.',+ required: false,+ }),+ uploadName: Property.ShortText({+ displayName: 'File Name',+ description: 'The download name, with extension. Empty keeps the original name.',+ required: false,+ placeholder: 'invoice.pdf',+ }),+ },+ outputSchema: filesStorageOutputSchemas.addedPermFile,+ async run({ auth, propsValue }) {+ const { file } = propsValue;+ const fileUrl = (propsValue.fileUrl ?? '').trim();+ if (!file && fileUrl === '') {+ throw new Error('Provide either a File or a File URL.');+ }+ const uploadName = (propsValue.uploadName ?? '').trim() || file?.filename;+ const response = await zeroCodeKitApi.post<AddPermFileResponse>({+ apiKey: auth.secret_text,+ path: '/storage/perm/add',+ body: file+ ? { fileBuffer: zeroCodeKitFiles.toBase64(file), uploadName }+ : { fileUrl, uploadName },+ });+ return {+ file_id: response.fileId,+ url: response.url,+ file_name: uploadName ?? null,+ };+ },+});++type AddPermFileResponse = {+ fileId: string;+ url: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/storage/delete-a-global-variable.ts b/packages/pieces/community/0codekit/src/lib/actions/storage/delete-a-global-variable.tsnew file mode 100644index 00000000000..a858cf64949--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/storage/delete-a-global-variable.ts@@ -0,0 +1,43 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitStorage } from '../../common/storage';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const deleteAGlobalVariableAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'delete_a_global_variable',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete a Global Variable',+ description: 'Permanently remove a global variable from 0CodeKit.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Permanently delete a global variable, identified by its name, from the connected 0CodeKit account. The value cannot be recovered. Only variables created with this account can be deleted. Fails if the variable no longer exists.',+ idempotent: false,+ },+ props: {+ variableName: zeroCodeKitStorage.variableName({+ description: 'The global variable to delete.',+ }),+ },+ outputSchema: filesStorageOutputSchemas.deletedGlobalVariable,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<DeleteVariableResponse>({+ apiKey: auth.secret_text,+ path: '/storage/globalvariables/del',+ body: {+ variableId: propsValue.variableName,+ },+ });+ return {+ deleted: true,+ variable_name: propsValue.variableName,+ message: response.message ?? null,+ };+ },+});++type DeleteVariableResponse = {+ message?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/storage/delete-a-perm-file.ts b/packages/pieces/community/0codekit/src/lib/actions/storage/delete-a-perm-file.tsnew file mode 100644index 00000000000..152601455b3--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/storage/delete-a-perm-file.ts@@ -0,0 +1,43 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitStorage } from '../../common/storage';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const deleteAPermFileAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'delete_a_perm_file',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete a Perm File',+ description: 'Permanently remove a file from 0CodeKit permanent storage.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Permanently delete a file, identified by its file_id, from permanent storage in the connected 0CodeKit account. Its download link stops working and the file cannot be recovered. Fails if the file no longer exists.',+ idempotent: false,+ },+ props: {+ fileId: zeroCodeKitStorage.permFileId({+ description: 'The perm file to delete.',+ }),+ },+ outputSchema: filesStorageOutputSchemas.deletedPermFile,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<DeletePermFileResponse>({+ apiKey: auth.secret_text,+ path: '/storage/perm/del',+ body: {+ fileId: propsValue.fileId,+ },+ });+ return {+ deleted: true,+ file_id: propsValue.fileId,+ message: response.message ?? null,+ };+ },+});++type DeletePermFileResponse = {+ message?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/storage/get-a-global-variable.ts b/packages/pieces/community/0codekit/src/lib/actions/storage/get-a-global-variable.tsnew file mode 100644index 00000000000..cacccb69ed9--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/storage/get-a-global-variable.ts@@ -0,0 +1,35 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { GlobalVariable, zeroCodeKitStorage } from '../../common/storage';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const getAGlobalVariableAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'get_a_global_variable',+ classification: 'READ',+ displayName: 'Get a Global Variable',+ description: 'Read the value of a global variable saved in 0CodeKit.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Return the name and current text value of one global variable, identified by its name, from the connected 0CodeKit account. Only variables created with this account are visible. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ variableName: zeroCodeKitStorage.variableName({+ description: 'The global variable to read.',+ }),+ },+ outputSchema: filesStorageOutputSchemas.globalVariable,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<GlobalVariable>({+ apiKey: auth.secret_text,+ path: '/storage/globalvariables/get',+ body: {+ variableName: propsValue.variableName,+ },+ });+ return zeroCodeKitStorage.toVariable(response);+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/storage/get-a-perm-file.ts b/packages/pieces/community/0codekit/src/lib/actions/storage/get-a-perm-file.tsnew file mode 100644index 00000000000..4e153149628--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/storage/get-a-perm-file.ts@@ -0,0 +1,57 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitFiles } from '../../common/files';+import { zeroCodeKitStorage } from '../../common/storage';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const getAPermFileAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'get_a_perm_file',+ classification: 'READ',+ displayName: 'Get a Perm File',+ description: 'Get a file from 0CodeKit permanent storage so later steps can use it.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Fetch a file, identified by its file_id, from permanent storage in the connected 0CodeKit account. Returns its download url and, unless Link Only is on, also downloads the file and returns a file reference usable by later steps. Read-only and safe to retry. The vendor marks this endpoint as deprecated in favour of the url returned when the file was added.',+ idempotent: true,+ },+ props: {+ fileId: zeroCodeKitStorage.permFileId({+ description: 'The perm file to get.',+ }),+ linkOnly: Property.Checkbox({+ displayName: 'Link Only',+ description: 'Turn on to return only the download link without downloading the file.',+ required: false,+ defaultValue: false,+ }),+ },+ outputSchema: filesStorageOutputSchemas.permFile,+ async run({ auth, propsValue, files }) {+ const response = await zeroCodeKitApi.post<GetPermFileResponse>({+ apiKey: auth.secret_text,+ path: '/storage/perm/get',+ body: {+ fileId: propsValue.fileId,+ getAsUrl: true,+ },+ });+ const url = response.url;+ if (typeof url !== 'string' || url === '') {+ throw new Error('0CodeKit did not return a download link for this file.');+ }+ if (propsValue.linkOnly) {+ return { file_id: propsValue.fileId, url };+ }+ const data = await zeroCodeKitStorage.download(url);+ const fileName = zeroCodeKitStorage.fileNameFromUrl({ url, fallback: propsValue.fileId });+ const saved = await zeroCodeKitFiles.save({ files, fileName, data });+ return { file_id: propsValue.fileId, url, ...saved };+ },+});++type GetPermFileResponse = {+ url?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/storage/list-global-variables.ts b/packages/pieces/community/0codekit/src/lib/actions/storage/list-global-variables.tsnew file mode 100644index 00000000000..6004f06ee77--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/storage/list-global-variables.ts@@ -0,0 +1,27 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitStorage } from '../../common/storage';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const listGlobalVariablesAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'list_global_variables',+ classification: 'SEARCH',+ displayName: 'List Global Variables',+ description: 'Get every global variable saved in your 0CodeKit account.',+ audience: 'both',+ aiMetadata: {+ description:+ 'List all global variables in the connected 0CodeKit account, each with its name and text value, plus the total count. Takes no input. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {},+ outputSchema: filesStorageOutputSchemas.globalVariableList,+ async run({ auth }) {+ const variables = await zeroCodeKitStorage.listVariables(auth.secret_text);+ return {+ count: variables.length,+ variables: variables.map(zeroCodeKitStorage.toVariable),+ };+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/storage/list-perm-files.ts b/packages/pieces/community/0codekit/src/lib/actions/storage/list-perm-files.tsnew file mode 100644index 00000000000..4b82114880b--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/storage/list-perm-files.ts@@ -0,0 +1,29 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitStorage } from '../../common/storage';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const listPermFilesAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'list_perm_files',+ classification: 'SEARCH',+ displayName: 'List Perm Files',+ description: 'Get every file in your 0CodeKit permanent storage and how much space is left.',+ audience: 'both',+ aiMetadata: {+ description:+ 'List all files in permanent storage for the connected 0CodeKit account, each with file_id, file_name, download url and size in KiB, plus the remaining storage in KiB and the total count. Takes no input. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {},+ outputSchema: filesStorageOutputSchemas.permFileList,+ async run({ auth }) {+ const response = await zeroCodeKitStorage.listPermFiles(auth.secret_text);+ const permFiles = response.files ?? [];+ return {+ count: permFiles.length,+ available_storage_kib: response.availableStorage ?? null,+ files: permFiles.map(zeroCodeKitStorage.toPermFile),+ };+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/temp-file/add-temporary-file.ts b/packages/pieces/community/0codekit/src/lib/actions/temp-file/add-temporary-file.tsnew file mode 100644index 00000000000..bc29889a824--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/temp-file/add-temporary-file.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitFiles } from '../../common/files';+import { filesStorageOutputSchemas } from '../../common/output-schemas/files-storage';++export const addTemporaryFileAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'add_temporary_file',+ classification: 'WRITE',+ displayName: 'Add a Temporary File and Recieve a URL',+ description: 'Upload a file and get a public download link that expires after 24 hours.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Upload a file to 0CodeKit temporary storage and return a public download URL. Anyone with the URL can download the file, and it is deleted automatically after 24 hours. Each call uploads a new copy and returns a new URL, so it is not idempotent.',+ idempotent: false,+ },+ props: {+ file: Property.File({+ displayName: 'File',+ description: 'The file to upload.',+ required: true,+ }),+ fileName: Property.ShortText({+ displayName: 'File Name',+ description: 'The uploaded file name, with extension. Empty keeps the original.',+ required: false,+ placeholder: 'report.pdf',+ }),+ },+ outputSchema: filesStorageOutputSchemas.temporaryFile,+ async run({ auth, propsValue }) {+ const fileName = (propsValue.fileName ?? '').trim() || propsValue.file.filename;+ const response = await zeroCodeKitApi.post<TemporaryFileResponse>({+ apiKey: auth.secret_text,+ path: '/storage/temp',+ body: {+ buffer: zeroCodeKitFiles.toBase64(propsValue.file),+ fileName,+ },+ });+ return {+ url: response.url ?? null,+ file_name: response.fileName ?? fileName ?? null,+ };+ },+});++type TemporaryFileResponse = {+ url?: string;+ fileName?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/url/advanced-switch-with-url.ts b/packages/pieces/community/0codekit/src/lib/actions/url/advanced-switch-with-url.tsnew file mode 100644index 00000000000..ff6e6e3cb64--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/url/advanced-switch-with-url.ts@@ -0,0 +1,60 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitUrl } from '../../common/url';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const advancedSwitchWithUrlAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'advanced_switch_with_url',+ classification: 'READ',+ displayName: 'Advanced Switch with URL',+ description: 'Look up values by key in a JSON file hosted at a URL.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Load a JSON object of key-value pairs from a public URL and return the values stored under the given keys, like a lookup table or switch statement. Values are returned in the same order as the keys. Does not change anything; safe to retry, though results change if the hosted file changes.',+ idempotent: true,+ },+ props: {+ jsonUrl: Property.ShortText({+ displayName: 'JSON URL',+ description: 'A public link to a JSON file of key-value pairs.',+ required: true,+ placeholder: 'https://example.com/lookup.json',+ }),+ keys: Property.Array({+ displayName: 'Keys',+ description: 'The keys to look up in the JSON file.',+ required: true,+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.advancedSwitch,+ async run({ auth, propsValue }) {+ const keys = zeroCodeKitUrl.normalizeTextList(propsValue.keys);+ if (keys.length === 0) {+ throw new Error('Add at least one key to look up.');+ }+ const response = await zeroCodeKitApi.post<AdvancedSwitchResponse>({+ apiKey: auth.secret_text,+ path: '/operator/advancedswitch',+ body: {+ external: true,+ json: propsValue.jsonUrl.trim(),+ key: keys,+ },+ });+ const found = response.found;+ const values: unknown[] = Array.isArray(found) ? found : found === undefined || found === null ? [] : [found];+ return {+ found: values.length > 0,+ count: values.length,+ first_value: values[0] ?? null,+ values,+ };+ },+});++type AdvancedSwitchResponse = {+ found?: unknown;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/url/create-custom-shortened-url.ts b/packages/pieces/community/0codekit/src/lib/actions/url/create-custom-shortened-url.tsnew file mode 100644index 00000000000..fa6f08ab957--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/url/create-custom-shortened-url.ts@@ -0,0 +1,44 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitUrl } from '../../common/url';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const createCustomShortenedUrlAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'create_custom_shortened_url',+ classification: 'WRITE',+ displayName: 'Create Custom Shortened Url',+ description: 'Create a short lyl.ai link with your own ending that redirects to a URL.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Create a new shortened URL on lyl.ai with a chosen identifier (the part after lyl.ai/) that redirects to the given destination URL. The identifier must be globally unique across all 0CodeKit users, so the call fails if it is already taken. Returns the identifier, the full short URL and the destination. Not safe to retry blindly.',+ idempotent: false,+ },+ props: {+ destination: Property.ShortText({+ displayName: 'Destination URL',+ description: 'The full URL the short link should redirect to, including `https://`.',+ required: true,+ placeholder: 'https://example.com/page',+ }),+ custom: Property.ShortText({+ displayName: 'Custom Ending',+ description: 'The text after `lyl.ai/`. It must not already be taken.',+ required: true,+ placeholder: 'summer-sale',+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.shortenedUrl,+ async run({ auth, propsValue }) {+ const custom = propsValue.custom.trim();+ if (custom.length === 0) {+ throw new Error('Enter a custom ending for the short link.');+ }+ return zeroCodeKitUrl.createShortenedUrl({+ apiKey: auth.secret_text,+ destination: propsValue.destination,+ custom,+ });+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/url/create-shortened-url.ts b/packages/pieces/community/0codekit/src/lib/actions/url/create-shortened-url.tsnew file mode 100644index 00000000000..28798774c5d--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/url/create-shortened-url.ts@@ -0,0 +1,33 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitUrl } from '../../common/url';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const createShortenedUrlAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'create_shortened_url',+ classification: 'WRITE',+ displayName: 'Create Shortened Url',+ description: 'Create a short lyl.ai link that redirects to a URL.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Create a new shortened URL on lyl.ai that redirects to the given destination URL, with a random 8-letter identifier. Returns the identifier, the full short URL and the destination. Use the identifier to get, update or delete the link later. Creates a new link on each call, so do not retry blindly.',+ idempotent: false,+ },+ props: {+ destination: Property.ShortText({+ displayName: 'Destination URL',+ description: 'The full URL the short link should redirect to, including `https://`.',+ required: true,+ placeholder: 'https://example.com/page',+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.shortenedUrl,+ async run({ auth, propsValue }) {+ return zeroCodeKitUrl.createShortenedUrl({+ apiKey: auth.secret_text,+ destination: propsValue.destination,+ });+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/url/delete-shortened-url.ts b/packages/pieces/community/0codekit/src/lib/actions/url/delete-shortened-url.tsnew file mode 100644index 00000000000..a820beb68c5--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/url/delete-shortened-url.ts@@ -0,0 +1,44 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitUrl } from '../../common/url';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const deleteShortenedUrlAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'delete_shortened_url',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Shortened Url',+ description: 'Permanently remove a short link so it stops redirecting.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Permanently delete a shortened URL, identified by its identifier, from the connected 0CodeKit account. The short link stops redirecting and cannot be recovered. Only links created with this account can be deleted. Fails if the link no longer exists.',+ idempotent: false,+ },+ props: {+ identifier: zeroCodeKitUrl.shortenedUrlIdentifier({+ description: 'The short link to delete.',+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.deleteShortenedUrl,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<DeleteShortenedUrlResponse>({+ apiKey: auth.secret_text,+ path: '/generate/shortenedurl/del',+ body: {+ identifier: propsValue.identifier,+ },+ });+ return {+ deleted: true,+ identifier: propsValue.identifier,+ short_url: zeroCodeKitUrl.shortUrlOf(propsValue.identifier),+ message: response.message ?? null,+ };+ },+});++type DeleteShortenedUrlResponse = {+ message?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/url/get-a-shortened-url.ts b/packages/pieces/community/0codekit/src/lib/actions/url/get-a-shortened-url.tsnew file mode 100644index 00000000000..0679a5af09e--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/url/get-a-shortened-url.ts@@ -0,0 +1,43 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitUrl } from '../../common/url';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const getAShortenedUrlAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'get_a_shortened_url',+ classification: 'READ',+ displayName: 'Get a Shortened Url',+ description: 'Find out where one of your short links redirects to.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Return the destination URL of one shortened URL, identified by its identifier, from the connected 0CodeKit account, together with the full short URL. Only links created with this account are visible. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ identifier: zeroCodeKitUrl.shortenedUrlIdentifier({+ description: 'The short link to look up.',+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.shortenedUrl,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<GetShortenedUrlResponse>({+ apiKey: auth.secret_text,+ path: '/generate/shortenedurl/get',+ body: {+ identifier: propsValue.identifier,+ },+ });+ return {+ identifier: propsValue.identifier,+ short_url: zeroCodeKitUrl.shortUrlOf(propsValue.identifier),+ destination: response.destination ?? null,+ };+ },+});++type GetShortenedUrlResponse = {+ destination?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/url/list-shortened-urls.ts b/packages/pieces/community/0codekit/src/lib/actions/url/list-shortened-urls.tsnew file mode 100644index 00000000000..5dc46096818--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/url/list-shortened-urls.ts@@ -0,0 +1,27 @@+import { createAction } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitUrl } from '../../common/url';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const listShortenedUrlsAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'list_shortened_urls',+ classification: 'SEARCH',+ displayName: 'List Shortened Urls',+ description: 'Get every short link created with your 0CodeKit account.',+ audience: 'both',+ aiMetadata: {+ description:+ 'List all shortened URLs in the connected 0CodeKit account, each with its identifier, full short URL, destination URL and creation date, plus the total count. Takes no input. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {},+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.listShortenedUrls,+ async run({ auth }) {+ const urls = await zeroCodeKitUrl.listShortenedUrls(auth.secret_text);+ return {+ count: urls.length,+ shortened_urls: urls.map(zeroCodeKitUrl.toShortenedUrl),+ };+ },+});diff --git a/packages/pieces/community/0codekit/src/lib/actions/url/update-shortened-url.ts b/packages/pieces/community/0codekit/src/lib/actions/url/update-shortened-url.tsnew file mode 100644index 00000000000..8934c6b2326--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/url/update-shortened-url.ts@@ -0,0 +1,52 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitUrl } from '../../common/url';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const updateShortenedUrlAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'update_shortened_url',+ classification: 'WRITE',+ displayName: 'Update Shortened Url',+ description: 'Change where one of your short links redirects to.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Point an existing shortened URL, identified by its identifier, at a new destination URL. The short link itself does not change. Only links created with this account can be updated. Setting the same destination again has the same result, so it is safe to retry.',+ idempotent: true,+ },+ props: {+ identifier: zeroCodeKitUrl.shortenedUrlIdentifier({+ description: 'The short link to change.',+ }),+ destination: Property.ShortText({+ displayName: 'New Destination URL',+ description: 'The full URL the short link redirects to from now on.',+ required: true,+ placeholder: 'https://example.com/new-page',+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.shortenedUrl,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<UpdateShortenedUrlResponse>({+ apiKey: auth.secret_text,+ path: '/generate/shortenedurl/put',+ body: {+ identifier: propsValue.identifier,+ destination: propsValue.destination.trim(),+ },+ });+ const identifier = response.identifier ?? propsValue.identifier;+ return {+ identifier,+ short_url: zeroCodeKitUrl.shortUrlOf(identifier),+ destination: response.newDestination ?? propsValue.destination.trim(),+ };+ },+});++type UpdateShortenedUrlResponse = {+ newDestination?: string;+ identifier?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/url/url-expander.ts b/packages/pieces/community/0codekit/src/lib/actions/url/url-expander.tsnew file mode 100644index 00000000000..0c18c8af3f1--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/url/url-expander.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const urlExpanderAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'url_expander',+ classification: 'READ',+ displayName: 'URL Expander',+ description: 'Find the full URL behind a short link from any URL shortener.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Follow a shortened URL from any URL shortener (bit.ly, lyl.ai, t.co and similar) and return the full URL it redirects to. Does not change anything. Safe to retry, though the result can change if the short link is re-pointed.',+ idempotent: true,+ },+ props: {+ url: Property.ShortText({+ displayName: 'Short URL',+ description: 'The shortened URL to expand, for example `https://bit.ly/abc123`.',+ required: true,+ placeholder: 'https://bit.ly/abc123',+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.urlExpander,+ async run({ auth, propsValue }) {+ const url = propsValue.url.trim();+ const response = await zeroCodeKitApi.post<UrlExpanderResponse>({+ apiKey: auth.secret_text,+ path: '/operator/urlexpander',+ body: {+ url,+ },+ });+ return {+ short_url: url,+ expanded_url: response.unshortenedUrl ?? null,+ };+ },+});++type UrlExpanderResponse = {+ unshortenedUrl?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/url/utm-build.ts b/packages/pieces/community/0codekit/src/lib/actions/url/utm-build.tsnew file mode 100644index 00000000000..99685a0ea99--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/url/utm-build.ts@@ -0,0 +1,80 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const utmBuildAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'utm_build',+ classification: 'READ',+ displayName: 'UTM Build',+ description: 'Add UTM tracking parameters to a URL.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Build a campaign tracking link by adding UTM parameters (utm_source, utm_medium, utm_campaign, utm_content, utm_term) to a base URL, and return the resulting URL. Empty parameters are left out. Pure transformation with no side effects; safe to retry.',+ idempotent: true,+ },+ props: {+ url: Property.ShortText({+ displayName: 'URL',+ description: 'The page the link should open.',+ required: true,+ placeholder: 'https://example.com/pricing',+ }),+ utmSource: Property.ShortText({+ displayName: 'Source (utm_source)',+ description: 'Where the traffic comes from, for example `newsletter` or `google`.',+ required: true,+ }),+ utmMedium: Property.ShortText({+ displayName: 'Medium (utm_medium)',+ description: 'The marketing channel, for example `email` or `cpc`.',+ required: false,+ }),+ utmCampaign: Property.ShortText({+ displayName: 'Campaign (utm_campaign)',+ description: 'The campaign name, for example `spring_sale`.',+ required: false,+ }),+ utmContent: Property.ShortText({+ displayName: 'Content (utm_content)',+ description: 'Tells apart links in the same campaign, for example `header_button`.',+ required: false,+ }),+ utmTerm: Property.ShortText({+ displayName: 'Term (utm_term)',+ description: 'The paid search keyword, if any.',+ required: false,+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.utmBuild,+ async run({ auth, propsValue }) {+ const utm = Object.fromEntries(+ Object.entries({+ utm_source: propsValue.utmSource,+ utm_medium: propsValue.utmMedium,+ utm_campaign: propsValue.utmCampaign,+ utm_content: propsValue.utmContent,+ utm_term: propsValue.utmTerm,+ })+ .map(([key, value]) => [key, value?.trim()])+ .filter(([, value]) => value !== undefined && value !== ''),+ );+ const response = await zeroCodeKitApi.post<UtmBuildResponse>({+ apiKey: auth.secret_text,+ path: '/operator/utm/build',+ body: {+ url: propsValue.url.trim(),+ utm,+ },+ });+ return {+ url: response.url ?? null,+ };+ },+});++type UtmBuildResponse = {+ url?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/actions/url/utm-parse.ts b/packages/pieces/community/0codekit/src/lib/actions/url/utm-parse.tsnew file mode 100644index 00000000000..c04156797f3--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/actions/url/utm-parse.ts@@ -0,0 +1,51 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../../auth';+import { zeroCodeKitApi } from '../../common/client';+import { zeroCodeKitCodeUrlOutputSchemas } from '../../common/output-schemas/code-url';++export const utmParseAction = createAction({+ auth: zeroCodeKitAuth,+ name: 'utm_parse',+ classification: 'READ',+ displayName: 'UTM Parse',+ description: 'Read the UTM tracking parameters from a URL.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Extract the UTM parameters (utm_source, utm_medium, utm_campaign, utm_content, utm_term) from a URL. Parameters missing from the URL come back as null. Pure transformation with no side effects; safe to retry.',+ idempotent: true,+ },+ props: {+ url: Property.ShortText({+ displayName: 'URL',+ description: 'The link with UTM parameters to read.',+ required: true,+ placeholder: 'https://example.com/?utm_source=newsletter&utm_medium=email',+ }),+ },+ outputSchema: zeroCodeKitCodeUrlOutputSchemas.utmParse,+ async run({ auth, propsValue }) {+ const response = await zeroCodeKitApi.post<UtmParseResponse>({+ apiKey: auth.secret_text,+ path: '/operator/utm/parse',+ body: {+ url: propsValue.url.trim(),+ },+ });+ return {+ utm_source: response.utm_source ?? null,+ utm_medium: response.utm_medium ?? null,+ utm_campaign: response.utm_campaign ?? null,+ utm_content: response.utm_content ?? null,+ utm_term: response.utm_term ?? null,+ };+ },+});++type UtmParseResponse = {+ utm_source?: string;+ utm_medium?: string;+ utm_campaign?: string;+ utm_content?: string;+ utm_term?: string;+};diff --git a/packages/pieces/community/0codekit/src/lib/common/ai.ts b/packages/pieces/community/0codekit/src/lib/common/ai.tsnew file mode 100644index 00000000000..31d14052a7e--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/ai.ts@@ -0,0 +1,93 @@+import { Property } from '@activepieces/pieces-framework';++export const zeroCodeKitAi = {+ textProp,+ imageUrlProp,+ targetLanguageProp,+ requireText,+ stringList,+};++function textProp({ description }: { description: string }) {+ return Property.LongText({+ displayName: 'Text',+ description,+ required: true,+ });+}++function imageUrlProp({ description }: { description: string }) {+ return Property.ShortText({+ displayName: 'Image URL',+ description,+ required: true,+ placeholder: 'https://example.com/image.jpg',+ });+}++function targetLanguageProp() {+ return Property.StaticDropdown({+ displayName: 'Target Language',+ description: 'The language to translate the text into.',+ required: true,+ options: {+ options: TARGET_LANGUAGES.map((language) => ({+ label: `${language.name} (${language.code})`,+ value: language.code,+ })),+ },+ });+}++function requireText({ value, label }: { value: string | undefined; label: string }): string {+ const trimmed = (value ?? '').trim();+ if (trimmed === '') {+ throw new Error(`${label} cannot be empty.`);+ }+ return trimmed;+}++function stringList(value: unknown): string[] {+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];+}++const TARGET_LANGUAGES = [+ { code: 'ar', name: 'Arabic' },+ { code: 'bg', name: 'Bulgarian' },+ { code: 'zh', name: 'Chinese' },+ { code: 'hr', name: 'Croatian' },+ { code: 'cs', name: 'Czech' },+ { code: 'da', name: 'Danish' },+ { code: 'nl', name: 'Dutch' },+ { code: 'en', name: 'English' },+ { code: 'et', name: 'Estonian' },+ { code: 'fi', name: 'Finnish' },+ { code: 'fr', name: 'French' },+ { code: 'de', name: 'German' },+ { code: 'el', name: 'Greek' },+ { code: 'he', name: 'Hebrew' },+ { code: 'hi', name: 'Hindi' },+ { code: 'hu', name: 'Hungarian' },+ { code: 'id', name: 'Indonesian' },+ { code: 'it', name: 'Italian' },+ { code: 'ja', name: 'Japanese' },+ { code: 'ko', name: 'Korean' },+ { code: 'lv', name: 'Latvian' },+ { code: 'lt', name: 'Lithuanian' },+ { code: 'no', name: 'Norwegian' },+ { code: 'fa', name: 'Persian' },+ { code: 'pl', name: 'Polish' },+ { code: 'pt', name: 'Portuguese' },+ { code: 'ro', name: 'Romanian' },+ { code: 'ru', name: 'Russian' },+ { code: 'sr', name: 'Serbian' },+ { code: 'sk', name: 'Slovak' },+ { code: 'sl', name: 'Slovenian' },+ { code: 'es', name: 'Spanish' },+ { code: 'sv', name: 'Swedish' },+ { code: 'th', name: 'Thai' },+ { code: 'tr', name: 'Turkish' },+ { code: 'uk', name: 'Ukrainian' },+ { code: 'ur', name: 'Urdu' },+ { code: 'vi', name: 'Vietnamese' },+];diff --git a/packages/pieces/community/0codekit/src/lib/common/code.ts b/packages/pieces/community/0codekit/src/lib/common/code.tsnew file mode 100644index 00000000000..466b4734c53--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/code.ts@@ -0,0 +1,206 @@+import { httpClient, HttpError, HttpMethod } from '@activepieces/pieces-common';+import { Property } from '@activepieces/pieces-framework';+import { zeroCodeKitApi, ZEROCODEKIT_BASE_URL } from './client';++export const zeroCodeKitCode = {+ execute,+ describeRunError,+ stringList,+ withJavascriptInputs,+ withPythonInputs,+ javascriptResult,+ pythonResult,+ inputsProp,+ dependenciesProp,+};++export const CODE_TIMEOUT_MS = 190_000;++async function execute({ apiKey, path, body }: ExecuteParams): Promise<unknown> {+ try {+ const response = await httpClient.sendRequest<unknown>({+ method: HttpMethod.POST,+ url: `${ZEROCODEKIT_BASE_URL}${path}`,+ headers: { auth: apiKey },+ body,+ timeout: CODE_TIMEOUT_MS,+ });+ return response.body;+ } catch (error) {+ throw new Error(describeRunError(error));+ }+}++function describeRunError(error: unknown): string {+ if (isAbort(error)) {+ return `0CodeKit did not answer within ${CODE_TIMEOUT_MS / 1000} seconds. Code runs are limited to 180 seconds, including installing dependencies. Make the code faster or split the work into smaller runs.`;+ }+ const message = zeroCodeKitApi.describe({ error, fallback: 'Running the code on 0CodeKit failed.' });+ if (error instanceof HttpError && TIMEOUT_STATUSES.includes(error.response.status)) {+ return `${message}. Code runs are limited to 180 seconds and 512 MB of memory, including installing dependencies.`;+ }+ return message;+}++function isAbort(error: unknown): boolean {+ return error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError');+}++function stringList(value: unknown): string[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value+ .filter((item): item is string | number => typeof item === 'string' || typeof item === 'number')+ .map((item) => String(item).trim())+ .filter((item) => item !== '');+}++function inputsValue(inputs: unknown): unknown {+ return inputs === undefined || inputs === null || inputs === '' ? {} : inputs;+}++function isBlankInputs(inputs: unknown): boolean {+ const value = inputsValue(inputs);+ return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.keys(value).length === 0;+}++function withJavascriptInputs({ code, inputs }: InjectParams): string {+ if (isBlankInputs(inputs)) {+ return code;+ }+ const assignment = `const inputs = ${JSON.stringify(inputsValue(inputs))};`;+ return insertLine({ code, line: assignment, at: lineAfterJavascriptPrologue });+}++function withPythonInputs({ code, inputs }: InjectParams): string {+ const assignment = `inputs = __import__("json").loads(${JSON.stringify(JSON.stringify(inputsValue(inputs)))})`;+ return insertLine({ code, line: assignment, at: lineAfterFutureImports });+}++function insertLine({ code, line, at }: { code: string; line: string; at: (lines: string[]) => number }): string {+ const lines = code.split('\n');+ const index = at(lines);+ return [...lines.slice(0, index), line, ...lines.slice(index)].join('\n');+}++function lineAfterJavascriptPrologue(lines: string[]): number {+ let end = 0;+ for (const [index, line] of lines.entries()) {+ const trimmed = line.trim();+ if ((index === 0 && trimmed.startsWith('#!')) || JAVASCRIPT_DIRECTIVE.test(trimmed)) {+ end = index + 1;+ } else if (trimmed !== '' && !trimmed.startsWith('//')) {+ break;+ }+ }+ return end;+}++function lineAfterFutureImports(lines: string[]): number {+ const state: FutureScan = { end: 0, docstringAllowed: true, openDocstring: undefined, inGroup: false, inContinuation: false };+ for (const [index, line] of lines.entries()) {+ if (!scanPythonHeaderLine({ state, line, index })) {+ break;+ }+ }+ return state.end;+}++function scanPythonHeaderLine({ state, line, index }: { state: FutureScan; line: string; index: number }): boolean {+ const trimmed = line.trim();+ if (state.openDocstring !== undefined) {+ if (line.includes(state.openDocstring)) {+ state.openDocstring = undefined;+ state.end = index + 1;+ }+ return true;+ }+ if (state.inGroup || state.inContinuation || PYTHON_FUTURE_IMPORT.test(line)) {+ state.inGroup = (state.inGroup || (PYTHON_FUTURE_IMPORT.test(line) && line.includes('('))) && !line.includes(')');+ state.inContinuation = line.trimEnd().endsWith('\\');+ state.end = index + 1;+ state.docstringAllowed = false;+ return true;+ }+ if (trimmed === '' || trimmed.startsWith('#')) {+ return true;+ }+ const quote = PYTHON_DOCSTRING_START.exec(trimmed)?.[1];+ if (quote === undefined || !state.docstringAllowed) {+ return false;+ }+ state.docstringAllowed = false;+ const afterOpening = trimmed.slice(trimmed.indexOf(quote) + quote.length);+ state.openDocstring = quote.length === 3 && !afterOpening.includes(quote) ? quote : undefined;+ if (state.openDocstring === undefined) {+ state.end = index + 1;+ }+ return true;+}++function javascriptResult(body: unknown): CodeResult {+ return toResult(body);+}++function pythonResult(body: unknown): CodeResult {+ if (isRecord(body) && 'result' in body) {+ return toResult(body['result']);+ }+ return toResult(body);+}++function toResult(value: unknown): CodeResult {+ return { result: value === undefined || value === '' ? null : value };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function inputsProp({ variable }: { variable: string }) {+ return Property.Json({+ displayName: 'Inputs',+ description: `Data to pass into your code. It is available in the code as the \`${variable}\` variable. Map values from earlier steps here instead of pasting them into the code.`,+ required: false,+ });+}++function dependenciesProp() {+ return Property.Array({+ displayName: 'System Packages',+ description: 'Alpine Linux (apk) packages your code needs, such as `ffmpeg`. Leave empty if you only use language libraries.',+ required: false,+ });+}++const TIMEOUT_STATUSES = [408, 504];++const PYTHON_FUTURE_IMPORT = /^from\s+__future__\s+import\b/;++const PYTHON_DOCSTRING_START = /^[rRuU]?("""|'''|"|')/;++const JAVASCRIPT_DIRECTIVE = /^(['"])use strict\1;?$/;++type ExecuteParams = {+ apiKey: string;+ path: string;+ body: Record<string, unknown>;+};++type CodeResult = {+ result: unknown;+};++type FutureScan = {+ end: number;+ docstringAllowed: boolean;+ openDocstring: string | undefined;+ inGroup: boolean;+ inContinuation: boolean;+};++type InjectParams = {+ code: string;+ inputs: unknown;+};diff --git a/packages/pieces/community/0codekit/src/lib/common/crypto.ts b/packages/pieces/community/0codekit/src/lib/common/crypto.tsnew file mode 100644index 00000000000..87611a5befd--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/crypto.ts@@ -0,0 +1,52 @@+import { Property } from '@activepieces/pieces-framework';++export const zeroCodeKitCrypto = {+ cipher,+ secretKey,+ isHmac,+};++export const CIPHERS = ['AES', 'DES', 'TripleDES', 'Rabbit', 'RC4', 'RC4Drop'];++export const HASH_TYPES = [+ { label: 'MD5', value: 'MD5' },+ { label: 'SHA-1', value: 'SHA1' },+ { label: 'SHA-224', value: 'SHA224' },+ { label: 'SHA-256', value: 'SHA256' },+ { label: 'SHA-3', value: 'SHA3' },+ { label: 'SHA-384', value: 'SHA384' },+ { label: 'SHA-512', value: 'SHA512' },+ { label: 'RIPEMD-160', value: 'RIPEMD160' },+ { label: 'HMAC MD5', value: 'HmacMD5' },+ { label: 'HMAC SHA-1', value: 'HmacSHA1' },+ { label: 'HMAC SHA-224', value: 'HmacSHA224' },+ { label: 'HMAC SHA-256', value: 'HmacSHA256' },+ { label: 'HMAC SHA-3', value: 'HmacSHA3' },+ { label: 'HMAC SHA-384', value: 'HmacSHA384' },+ { label: 'HMAC SHA-512', value: 'HmacSHA512' },+ { label: 'HMAC RIPEMD-160', value: 'HmacRIPEMD160' },+];++function cipher() {+ return Property.StaticDropdown({+ displayName: 'Algorithm',+ description: 'The cipher to use. Decrypt with the same algorithm and secret key that encrypted the text.',+ required: true,+ defaultValue: 'AES',+ options: {+ options: CIPHERS.map((value) => ({ label: value, value })),+ },+ });+}++function secretKey({ description, required }: { description: string; required: boolean }) {+ return Property.ShortText({+ displayName: 'Secret Key',+ description,+ required,+ });+}++function isHmac(hashType: string): boolean {+ return hashType.startsWith('Hmac');+}diff --git a/packages/pieces/community/0codekit/src/lib/common/files.ts b/packages/pieces/community/0codekit/src/lib/common/files.tsnew file mode 100644index 00000000000..2396fb54be8--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/files.ts@@ -0,0 +1,151 @@+import { httpClient, HttpError, HttpMethod } from '@activepieces/pieces-common';+import { ApFile, FilesService } from '@activepieces/pieces-framework';+import { zeroCodeKitApi, ZEROCODEKIT_BASE_URL, ZEROCODEKIT_TIMEOUT_MS, ZeroCodeKitRequest } from './client';++export const zeroCodeKitFiles = {+ postForBinary,+ download,+ assertZeroCodeKitUrl,+ save,+ saveBase64,+ toBase64,+ withExtension,+};++async function postForBinary({ apiKey, path, body, timeoutMs }: ZeroCodeKitRequest): Promise<Buffer> {+ try {+ const response = await httpClient.sendRequest<ArrayBuffer>({+ method: HttpMethod.POST,+ url: `${ZEROCODEKIT_BASE_URL}${path}`,+ headers: { auth: apiKey },+ body: body ?? {},+ responseType: 'arraybuffer',+ timeout: timeoutMs ?? zeroCodeKitApi.timeoutFor(path),+ });+ return Buffer.from(response.body);+ } catch (error) {+ throw new Error(describeBinaryError(error));+ }+}++async function download({ url, failure, timeoutMs }: DownloadParams): Promise<Buffer> {+ const safeUrl = assertZeroCodeKitUrl(url);+ const response = await sendDownload({ url: safeUrl, failure, timeoutMs });+ if (response.status >= 300 && response.status < 400) {+ throw new Error(`${failure} 0CodeKit answered with a redirect (${response.status}), which is not followed.`);+ }+ return Buffer.from(response.body);+}++async function sendDownload({ url, failure, timeoutMs }: DownloadParams) {+ try {+ return await httpClient.sendRequest<ArrayBuffer>({+ method: HttpMethod.GET,+ url,+ responseType: 'arraybuffer',+ followRedirects: false,+ timeout: timeoutMs ?? ZEROCODEKIT_TIMEOUT_MS.file,+ });+ } catch (error) {+ throw new Error(zeroCodeKitApi.describe({ error, fallback: failure }));+ }+}++function assertZeroCodeKitUrl(url: string): string {+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ throw new Error('0CodeKit returned a download link that is not a valid URL.');+ }+ const host = parsed.hostname.toLowerCase();+ const trusted = ZEROCODEKIT_DOWNLOAD_DOMAINS.some((domain) => host === domain || host.endsWith(`.${domain}`));+ if (parsed.protocol !== 'https:' || !trusted || parsed.port !== '' || parsed.username !== '' || parsed.password !== '') {+ throw new Error(+ `Refusing to download from ${parsed.protocol}//${host}: only https links on 0CodeKit domains (${ZEROCODEKIT_DOWNLOAD_DOMAINS.join(', ')}) are downloaded.`,+ );+ }+ return parsed.toString();+}++function describeBinaryError(error: unknown): string {+ const fallback = 'The request to 0CodeKit failed.';+ if (!(error instanceof HttpError)) {+ return zeroCodeKitApi.describe({ error, fallback });+ }+ const parsed = parseBinaryBody(error.response.body);+ if (parsed === undefined) {+ return zeroCodeKitApi.describe({ error, fallback });+ }+ return zeroCodeKitApi.describe({+ error: new HttpError({}, { status: error.response.status, responseBody: parsed }),+ fallback,+ });+}++function parseBinaryBody(body: unknown): unknown {+ const text = Buffer.isBuffer(body)+ ? body.toString('utf8')+ : body instanceof ArrayBuffer+ ? Buffer.from(body).toString('utf8')+ : typeof body === 'string'+ ? body+ : undefined;+ if (text === undefined) {+ return undefined;+ }+ try {+ return JSON.parse(text);+ } catch {+ return { errorMessage: text.slice(0, 300) };+ }+}++async function save({+ files,+ fileName,+ data,+}: {+ files: FilesService;+ fileName: string;+ data: Buffer;+}): Promise<SavedFile> {+ const file = await files.write({ fileName, data });+ return { file, file_name: fileName, size_bytes: data.length };+}++async function saveBase64({+ files,+ fileName,+ base64,+}: {+ files: FilesService;+ fileName: string;+ base64: string;+}): Promise<SavedFile> {+ const cleaned = base64.replace(/^data:[^;]+;base64,/, '');+ return save({ files, fileName, data: Buffer.from(cleaned, 'base64') });+}++function toBase64(file: ApFile): string {+ return file.base64;+}++function withExtension({ name, extension }: { name: string | undefined; extension: string }): string {+ const base = (name ?? '').trim() || 'file';+ return base.toLowerCase().endsWith(`.${extension}`) ? base : `${base}.${extension}`;+}++const ZEROCODEKIT_DOWNLOAD_DOMAINS = ['0codekit.com', '1saas.co'];++type DownloadParams = {+ url: string;+ failure: string;+ timeoutMs?: number;+};++export type SavedFile = {+ file: string;+ file_name: string;+ size_bytes: number;+};diff --git a/packages/pieces/community/0codekit/src/lib/common/image.ts b/packages/pieces/community/0codekit/src/lib/common/image.tsnew file mode 100644index 00000000000..980ca7ce359--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/image.ts@@ -0,0 +1,76 @@+import { ApFile, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitFiles } from './files';++export const zeroCodeKitImage = {+ imageFileProp,+ imageUrlProp,+ imageSource,+ resolveImage,+};++function imageFileProp({ description }: { description: string }) {+ return Property.File({+ displayName: 'Image File',+ description,+ required: false,+ });+}++function imageUrlProp({ description }: { description: string }) {+ return Property.ShortText({+ displayName: 'Image URL',+ description,+ required: false,+ });+}++function imageSource({ file, url }: { file: ApFile | undefined | null; url: string | undefined | null }): ImageSource {+ if (file) {+ return { buffer: zeroCodeKitFiles.toBase64(file) };+ }+ const trimmed = (url ?? '').trim();+ if (trimmed !== '') {+ return { url: trimmed };+ }+ throw new Error('Provide either an Image File or an Image URL.');+}++function isPng(data: Buffer): boolean {+ return data.length >= PNG_SIGNATURE.length && data.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE);+}++function parseJson(data: Buffer): Record<string, unknown> | undefined {+ try {+ const parsed: unknown = JSON.parse(data.toString('utf8'));+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)+ ? Object.fromEntries(Object.entries(parsed))+ : undefined;+ } catch {+ return undefined;+ }+}++async function resolveImage(data: Buffer): Promise<ResolvedImage> {+ if (isPng(data)) {+ return { data, imageUrl: null };+ }+ const json = parseJson(data);+ const imageUrl = json && typeof json['imageUrl'] === 'string' ? json['imageUrl'] : undefined;+ if (imageUrl === undefined || imageUrl === '') {+ throw new Error('0CodeKit did not return a QR code image.');+ }+ const dataUri = imageUrl.match(/^data:[^;]+;base64,(.*)$/);+ if (dataUri) {+ return { data: Buffer.from(dataUri[1], 'base64'), imageUrl: null };+ }+ return { data: await zeroCodeKitFiles.download({ url: imageUrl, failure: 'Downloading the generated image failed.' }), imageUrl };+}++const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);++export type ImageSource = { buffer: string } | { url: string };++export type ResolvedImage = {+ data: Buffer;+ imageUrl: string | null;+};diff --git a/packages/pieces/community/0codekit/src/lib/common/output-schemas/business-ai.ts b/packages/pieces/community/0codekit/src/lib/common/output-schemas/business-ai.tsindex fa44f0958cf..d39f74ba8fa 100644--- a/packages/pieces/community/0codekit/src/lib/common/output-schemas/business-ai.ts+++ b/packages/pieces/community/0codekit/src/lib/common/output-schemas/business-ai.ts@@ -64,6 +64,67 @@ export const businessAiOutputSchemas = {},],},+ entityDetection: {+ fields: [+ { key: 'entity_count', label: 'Entity Count', format: 'number' },+ {+ key: 'entities',+ label: 'Entities',+ labelKey: 'text',+ listItems: [+ { key: 'text', label: 'Text' },+ { key: 'category', label: 'Category', description: 'For example Person, Location, Organization or DateTime.' },+ { key: 'sub_category', label: 'Sub-Category' },+ { key: 'offset', label: 'Offset', format: 'number' },+ { key: 'length', label: 'Length', format: 'number' },+ { key: 'confidence_score', label: 'Confidence Score', format: 'number', description: 'Between 0 and 1.' },+ ],+ },+ ],+ },+ languageDetection: {+ fields: [+ { key: 'language_name', label: 'Language Name' },+ { key: 'language_code', label: 'Language Code', description: 'Two-letter ISO 639-1 code.' },+ { key: 'confidence_score', label: 'Confidence Score', format: 'number', description: 'Between 0 and 1.' },+ ],+ },+ moodDetection: {+ fields: [+ { key: 'mood', label: 'Overall Mood', description: 'positive, neutral, negative or mixed.' },+ { key: 'positive_score', label: 'Positive Score', format: 'number' },+ { key: 'neutral_score', label: 'Neutral Score', format: 'number' },+ { key: 'negative_score', label: 'Negative Score', format: 'number' },+ {+ key: 'sentences',+ label: 'Sentences',+ labelKey: 'text',+ listItems: [+ { key: 'text', label: 'Text' },+ { key: 'mood', label: 'Mood' },+ ],+ },+ ],+ },+ pictureObjectRecognition: {+ fields: [+ { key: 'label_count', label: 'Label Count', format: 'number' },+ { key: 'labels', label: 'Labels', description: 'Short labels for the objects and scenes found in the image.' },+ ],+ },+ pictureTextRecognition: {+ fields: [+ { key: 'text', label: 'Text', description: 'All recognized lines joined with line breaks.' },+ { key: 'line_count', label: 'Line Count', format: 'number' },+ { key: 'lines', label: 'Lines' },+ ],+ },+ translateText: {+ fields: [+ { key: 'translation', label: 'Translation' },+ { key: 'target_language', label: 'Target Language', description: 'Two-letter ISO 639-1 code.' },+ ],+ },} satisfies Record<string, OutputSchema>;function vatValidationFields(): OutputSchema['fields'] {diff --git a/packages/pieces/community/0codekit/src/lib/common/output-schemas/code-url.ts b/packages/pieces/community/0codekit/src/lib/common/output-schemas/code-url.tsnew file mode 100644index 00000000000..4e1b49ad366--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/output-schemas/code-url.ts@@ -0,0 +1,138 @@+import { OutputSchema } from '@activepieces/pieces-framework';++export const zeroCodeKitCodeUrlOutputSchemas = {+ codeResult: {+ fields: [+ {+ key: 'result',+ label: 'Result',+ description: 'Whatever your code returned. Empty when the code returned nothing.',+ },+ ],+ },+ cryptoEncrypt: {+ fields: [+ {+ key: 'encrypted_text',+ label: 'Encrypted Text',+ description: 'Decrypt it with the same algorithm and secret key.',+ },+ ],+ },+ cryptoDecrypt: {+ fields: [{ key: 'decrypted_text', label: 'Decrypted Text' }],+ },+ cryptoHash: {+ fields: [+ { key: 'hashed_text', label: 'Hash', description: 'The hash or HMAC signature, hex encoded.' },+ { key: 'algorithm', label: 'Algorithm' },+ ],+ },+ createScheduler: {+ fields: [+ { key: 'task_id', label: 'Scheduler ID', description: 'Use it to delete the scheduler.' },+ { key: 'next_execution', label: 'Next Run', format: 'datetime' },+ {+ key: 'end_date',+ label: 'End Date',+ format: 'datetime',+ description: 'When the scheduler stops. Empty when it runs until deleted.',+ },+ ],+ },+ listSchedulers: {+ fields: [+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'schedulers', label: 'Schedulers', labelKey: 'task_id', listItems: schedulerFields() },+ ],+ },+ deleteScheduler: {+ fields: [+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'task_id', label: 'Scheduler ID' },+ { key: 'message', label: 'Message' },+ ],+ },+ shortenedUrl: {+ fields: shortenedUrlFields(),+ },+ listShortenedUrls: {+ fields: [+ { key: 'count', label: 'Count', format: 'number' },+ {+ key: 'shortened_urls',+ label: 'Shortened URLs',+ labelKey: 'identifier',+ listItems: [...shortenedUrlFields(), { key: 'created_at', label: 'Created At', format: 'datetime' }],+ },+ ],+ },+ deleteShortenedUrl: {+ fields: [+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'identifier', label: 'Identifier' },+ { key: 'short_url', label: 'Short URL', format: 'url' },+ { key: 'message', label: 'Message' },+ ],+ },+ urlExpander: {+ fields: [+ { key: 'short_url', label: 'Short URL', format: 'url' },+ {+ key: 'expanded_url',+ label: 'Expanded URL',+ format: 'url',+ description: 'The final URL after following every redirect. Empty when it could not be resolved.',+ },+ ],+ },+ utmBuild: {+ fields: [{ key: 'url', label: 'URL', format: 'url', description: 'The URL with the UTM parameters added.' }],+ },+ utmParse: {+ fields: [+ { key: 'utm_source', label: 'UTM Source' },+ { key: 'utm_medium', label: 'UTM Medium' },+ { key: 'utm_campaign', label: 'UTM Campaign' },+ { key: 'utm_content', label: 'UTM Content' },+ { key: 'utm_term', label: 'UTM Term' },+ ],+ },+ advancedSwitch: {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean', description: 'True when at least one key matched.' },+ { key: 'count', label: 'Count', format: 'number' },+ {+ key: 'first_value',+ label: 'First Value',+ description: 'The value of the first matching key. Empty when nothing matched.',+ },+ { key: 'values', label: 'Values', description: 'The values of every matching key.' },+ ],+ },+} satisfies Record<string, OutputSchema>;++function shortenedUrlFields(): OutputSchema['fields'] {+ return [+ {+ key: 'identifier',+ label: 'Identifier',+ description: 'The ending of the short link after lyl.ai/. Use it to get, update or delete the link.',+ },+ { key: 'short_url', label: 'Short URL', format: 'url' },+ { key: 'destination', label: 'Destination', format: 'url', description: 'Where the short link redirects to.' },+ ];+}++function schedulerFields(): OutputSchema['fields'] {+ return [+ {+ key: 'task_id',+ label: 'Scheduler ID',+ description: 'Use it to delete the scheduler.',+ },+ { key: 'webhook', label: 'Webhook', format: 'url', description: 'The URL 0CodeKit calls on each run.' },+ { key: 'next_execution', label: 'Next Run', format: 'datetime' },+ { key: 'data', label: 'Data', description: 'The data sent to the webhook, as a JSON string.' },+ ];+}diff --git a/packages/pieces/community/0codekit/src/lib/common/output-schemas/files-storage.ts b/packages/pieces/community/0codekit/src/lib/common/output-schemas/files-storage.tsnew file mode 100644index 00000000000..58324f9f4dd--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/output-schemas/files-storage.ts@@ -0,0 +1,144 @@+import { OutputSchema } from '@activepieces/pieces-framework';++export const filesStorageOutputSchemas = {+ pdfPageCount: {+ fields: [{ key: 'page_count', label: 'Page Count', format: 'number' }],+ },+ createdPdf: {+ fields: savedFileFields(),+ },+ mergedPdf: {+ fields: [+ ...savedFileFields(),+ { key: 'merged_count', label: 'PDFs Merged', format: 'number', description: 'How many PDFs were combined into the file.' },+ ],+ },+ splitPdf: {+ itemLabel: '{file_name}',+ fields: [+ {+ key: 'parts',+ label: 'PDF Parts',+ value: '',+ description: 'One saved PDF per part, in page order.',+ listItems: savedFileFields(),+ },+ ],+ },+ generatedQrCode: {+ fields: [+ ...savedFileFields(),+ {+ key: 'image_url',+ label: 'Hosted Image URL',+ format: 'image',+ description: 'Public link to the QR code image when 0CodeKit hosts it. Empty when the image was returned directly.',+ },+ ],+ },+ decodedQrCode: {+ fields: [{ key: 'data', label: 'Decoded Data', description: 'The text or link stored in the QR code.' }],+ },+ imageExif: {+ fields: [+ {+ key: 'exif_data',+ label: 'EXIF Data',+ description:+ 'Metadata read from the image, grouped by section (such as image, EXIF and GPS). The sections and tags depend on the camera and file type, so every tag found is shown. Empty when the image has no EXIF data.',+ },+ ],+ },+ temporaryFile: {+ fields: [+ { key: 'url', label: 'Temporary File URL', format: 'url', description: 'Public link to the uploaded file. It expires after 24 hours.' },+ { key: 'file_name', label: 'File Name' },+ ],+ },+ globalVariable: {+ fields: variableFields(),+ },+ globalVariableList: {+ fields: [+ { key: 'count', label: 'Variable Count', format: 'number' },+ { key: 'variables', label: 'Variables', labelKey: 'variable_name', listItems: variableFields() },+ ],+ },+ deletedGlobalVariable: {+ fields: [+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'variable_name', label: 'Variable Name' },+ { key: 'message', label: 'Message' },+ ],+ },+ addedPermFile: {+ fields: [+ { key: 'file_id', label: 'File ID' },+ { key: 'url', label: 'File URL', format: 'url' },+ { key: 'file_name', label: 'File Name' },+ ],+ },+ permFile: {+ fields: [+ { key: 'file_id', label: 'File ID' },+ { key: 'url', label: 'File URL', format: 'url' },+ {+ key: 'file',+ label: 'File',+ format: 'url',+ description: 'Reference to the downloaded file saved in Activepieces. Empty when Link Only is turned on.',+ },+ { key: 'file_name', label: 'File Name', description: 'Empty when Link Only is turned on.' },+ { key: 'size_bytes', label: 'File Size', format: 'filesize', description: 'Empty when Link Only is turned on.' },+ ],+ },+ deletedPermFile: {+ fields: [+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'file_id', label: 'File ID' },+ { key: 'message', label: 'Message' },+ ],+ },+ permFileList: {+ fields: [+ { key: 'count', label: 'File Count', format: 'number' },+ {+ key: 'available_storage_kib',+ label: 'Available Storage (KiB)',+ format: 'number',+ description: 'Remaining perm storage on the account, in kibibytes.',+ },+ {+ key: 'files',+ label: 'Files',+ labelKey: 'file_name',+ listItems: [+ { key: 'file_id', label: 'File ID' },+ { key: 'file_name', label: 'File Name' },+ { key: 'url', label: 'File URL', format: 'url' },+ { key: 'size_kib', label: 'Size (KiB)', format: 'number' },+ ],+ },+ ],+ },+} satisfies Record<string, OutputSchema>;++function savedFileFields(): OutputSchema['fields'] {+ return [+ {+ key: 'file',+ label: 'File',+ format: 'url',+ description: 'Reference to the file saved in Activepieces. Pass it to any step that accepts a file.',+ },+ { key: 'file_name', label: 'File Name' },+ { key: 'size_bytes', label: 'File Size', format: 'filesize' },+ ];+}++function variableFields(): OutputSchema['fields'] {+ return [+ { key: 'variable_name', label: 'Variable Name' },+ { key: 'variable_value', label: 'Variable Value' },+ ];+}diff --git a/packages/pieces/community/0codekit/src/lib/common/pdf.ts b/packages/pieces/community/0codekit/src/lib/common/pdf.tsnew file mode 100644index 00000000000..d4aae287356--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/pdf.ts@@ -0,0 +1,140 @@+import { ApFile, Property } from '@activepieces/pieces-framework';+import { zeroCodeKitFiles } from './files';++export const zeroCodeKitPdf = {+ pdfFile,+ fileName,+ renderProps,+ renderOptions,+ download,+ baseName,+ isApFile,+ clean,+};++function pdfFile({ displayName, description }: { displayName: string; description: string }) {+ return Property.File({+ displayName,+ description,+ required: true,+ });+}++function fileName({ description }: { description: string }) {+ return Property.ShortText({+ displayName: 'File Name',+ description,+ required: false,+ placeholder: 'document.pdf',+ });+}++function renderProps() {+ return {+ format: Property.StaticDropdown({+ displayName: 'Page Size',+ description: 'The paper size of the PDF pages.',+ required: false,+ defaultValue: 'A4',+ options: {+ options: PAGE_FORMATS.map((format) => ({ label: format, value: format })),+ },+ }),+ landscape: Property.Checkbox({+ displayName: 'Landscape',+ description: 'Lay the pages out horizontally instead of vertically.',+ required: false,+ defaultValue: false,+ }),+ printBackground: Property.Checkbox({+ displayName: 'Print Background',+ description: 'Include background colors and images from the page.',+ required: false,+ defaultValue: true,+ }),+ margin: Property.ShortText({+ displayName: 'Margin',+ description: 'Space around the content on every side, with a unit such as `1cm`, `10mm`, `0.5in` or `20px`. Leave empty for no margin.',+ required: false,+ placeholder: '1cm',+ }),+ scale: Property.Number({+ displayName: 'Scale',+ description: 'Zoom level of the rendered page, between 0.1 and 2. Leave empty for 1 (actual size).',+ required: false,+ }),+ pageRanges: Property.ShortText({+ displayName: 'Page Ranges',+ description: 'Only keep these pages, for example `1-3,5`. Leave empty to keep all pages.',+ required: false,+ placeholder: '1-3,5',+ }),+ displayHeaderFooter: Property.Checkbox({+ displayName: 'Show Header and Footer',+ description: 'Print the default browser header and footer (date, title, page numbers) on every page.',+ required: false,+ defaultValue: false,+ }),+ };+}++function renderOptions(values: RenderOptionValues): Record<string, unknown> {+ const margin = clean(values.margin);+ const pageRanges = clean(values.pageRanges);+ const options: Record<string, unknown> = {+ format: values.format ?? 'A4',+ landscape: values.landscape ?? false,+ printBackground: values.printBackground ?? true,+ displayHeaderFooter: values.displayHeaderFooter ?? false,+ };+ if (margin !== undefined) {+ options['margin'] = { top: margin, bottom: margin, left: margin, right: margin };+ }+ if (values.scale !== undefined && values.scale !== null) {+ if (values.scale < 0.1 || values.scale > 2) {+ throw new Error('Scale must be between 0.1 and 2.');+ }+ options['scale'] = values.scale;+ }+ if (pageRanges !== undefined) {+ options['pageRanges'] = pageRanges;+ }+ return options;+}++async function download({ url, timeoutMs }: { url: string; timeoutMs?: number }): Promise<Buffer> {+ return zeroCodeKitFiles.download({ url, timeoutMs, failure: 'Could not download the split PDF part.' });+}++function baseName({ name, fallback }: { name: string | undefined | null; fallback: string }): string {+ const trimmed = (name ?? '').trim().replace(/\.pdf$/i, '');+ return trimmed === '' ? fallback : trimmed;+}++function isApFile(value: unknown): value is ApFile {+ return (+ value !== null &&+ typeof value === 'object' &&+ 'data' in value &&+ Buffer.isBuffer(value.data) &&+ 'filename' in value &&+ typeof value.filename === 'string'+ );+}++function clean(value: string | undefined | null): string | undefined {+ const trimmed = (value ?? '').trim();+ return trimmed === '' ? undefined : trimmed;+}++const PAGE_FORMATS = ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'Letter', 'Legal', 'Tabloid', 'Ledger'];++export type RenderOptionValues = {+ format?: string | null;+ landscape?: boolean | null;+ printBackground?: boolean | null;+ margin?: string | null;+ scale?: number | null;+ pageRanges?: string | null;+ displayHeaderFooter?: boolean | null;+};diff --git a/packages/pieces/community/0codekit/src/lib/common/scheduler.ts b/packages/pieces/community/0codekit/src/lib/common/scheduler.tsnew file mode 100644index 00000000000..2101e7aead1--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/scheduler.ts@@ -0,0 +1,121 @@+import { Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../auth';+import { zeroCodeKitApi } from './client';++export const zeroCodeKitScheduler = {+ listTasks,+ taskId,+ parseSchedule,+ stringifyData,+ toTask,+};++export const ONE_TIME = '1';++export const MULTIPLE_TIMES = '2';++export const CRON = '3';++export const RECURRING = '4';++async function listTasks(apiKey: string): Promise<SchedulerTask[]> {+ const response = await zeroCodeKitApi.post<ListTasksResponse>({+ apiKey,+ path: '/operator/scheduler/list',+ });+ return response.tasks ?? [];+}++function taskId({ description }: { description: string }) {+ return Property.Dropdown({+ auth: zeroCodeKitAuth,+ displayName: 'Scheduler',+ description,+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your 0CodeKit account first.' };+ }+ try {+ const tasks = await listTasks(auth.secret_text);+ if (tasks.length === 0) {+ return { disabled: true, options: [], placeholder: 'No schedulers found. Create one first.' };+ }+ return {+ disabled: false,+ options: tasks.map((task) => ({+ label: `${task.webhook} (next run ${task.nextExecution})`,+ value: task.taskId,+ })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: zeroCodeKitApi.describe({ error, fallback: 'Could not load schedulers.' }),+ };+ }+ },+ });+}++function parseSchedule({ intervalType, schedule }: { intervalType: string; schedule: string }): ScheduleValue {+ const trimmed = schedule.trim();+ if (trimmed === '') {+ throw new Error('Enter a Schedule for the selected Schedule Type.');+ }+ if (intervalType === ONE_TIME) {+ return toDateValue(trimmed);+ }+ if (intervalType === MULTIPLE_TIMES) {+ const parts = trimmed+ .split(/[\n,]/)+ .map((part) => part.trim())+ .filter((part) => part !== '');+ const values = parts.map(toDateValue);+ const numbers = values.filter((value): value is number => typeof value === 'number');+ return numbers.length === values.length ? numbers : parts;+ }+ return trimmed;+}++function toDateValue(value: string): string | number {+ return /^\d+$/.test(value) ? Number(value) : value;+}++function stringifyData(data: unknown): string {+ if (data === undefined || data === null || data === '') {+ return '{}';+ }+ return typeof data === 'string' ? data : JSON.stringify(data);+}++function toTask(task: SchedulerTask): SchedulerTaskOutput {+ return {+ task_id: task.taskId,+ webhook: task.webhook,+ next_execution: task.nextExecution,+ data: task.data ?? null,+ };+}++export type SchedulerTask = {+ taskId: string;+ webhook: string;+ nextExecution: string;+ data?: string;+};++export type ListTasksResponse = {+ tasks?: SchedulerTask[];+};++export type SchedulerTaskOutput = {+ task_id: string;+ webhook: string;+ next_execution: string;+ data: string | null;+};++type ScheduleValue = string | number | string[] | number[];diff --git a/packages/pieces/community/0codekit/src/lib/common/storage.ts b/packages/pieces/community/0codekit/src/lib/common/storage.tsnew file mode 100644index 00000000000..bee8522c00f--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/storage.ts@@ -0,0 +1,149 @@+import { Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../auth';+import { zeroCodeKitApi } from './client';+import { zeroCodeKitFiles } from './files';++export const zeroCodeKitStorage = {+ listVariables,+ listPermFiles,+ variableName,+ permFileId,+ download,+ fileNameFromUrl,+ toVariable,+ toPermFile,+};++async function listVariables(apiKey: string): Promise<GlobalVariable[]> {+ const response = await zeroCodeKitApi.post<ListVariablesResponse>({+ apiKey,+ path: '/storage/globalvariables/list',+ });+ return response.variables ?? [];+}++async function listPermFiles(apiKey: string): Promise<ListPermFilesResponse> {+ return zeroCodeKitApi.post<ListPermFilesResponse>({+ apiKey,+ path: '/storage/perm/list',+ });+}++function variableName({ description }: { description: string }) {+ return Property.Dropdown({+ auth: zeroCodeKitAuth,+ displayName: 'Variable Name',+ description,+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your 0CodeKit account first.' };+ }+ try {+ const variables = await listVariables(auth.secret_text);+ if (variables.length === 0) {+ return { disabled: true, options: [], placeholder: 'No global variables found. Add one first.' };+ }+ return {+ disabled: false,+ options: variables.map((variable) => ({ label: variable.variableName, value: variable.variableName })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: zeroCodeKitApi.describe({ error, fallback: 'Could not load global variables.' }),+ };+ }+ },+ });+}++function permFileId({ description }: { description: string }) {+ return Property.Dropdown({+ auth: zeroCodeKitAuth,+ displayName: 'File',+ description,+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your 0CodeKit account first.' };+ }+ try {+ const response = await listPermFiles(auth.secret_text);+ const files = response.files ?? [];+ if (files.length === 0) {+ return { disabled: true, options: [], placeholder: 'No perm files found. Upload one first.' };+ }+ return {+ disabled: false,+ options: files.map((file) => ({ label: `${file.fileName} (${file.size} KiB)`, value: file.fileId })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: zeroCodeKitApi.describe({ error, fallback: 'Could not load perm files.' }),+ };+ }+ },+ });+}++async function download(url: string): Promise<Buffer> {+ return zeroCodeKitFiles.download({ url, failure: 'Downloading the perm file failed.' });+}++function fileNameFromUrl({ url, fallback }: { url: string; fallback: string }): string {+ try {+ const segments = new URL(url).pathname.split('/').filter((segment) => segment !== '');+ const last = segments[segments.length - 1];+ const name = last === undefined ? '' : decodeURIComponent(last).replace(/[\\/]/g, '_').trim();+ return name === '' ? fallback : name;+ } catch {+ return fallback;+ }+}++function toVariable(variable: GlobalVariable): VariableOutput {+ return { variable_name: variable.variableName, variable_value: variable.variableValue };+}++function toPermFile(file: PermFile): PermFileOutput {+ return { file_id: file.fileId, file_name: file.fileName, url: file.url, size_kib: file.size };+}++export type GlobalVariable = {+ variableName: string;+ variableValue: string;+};++export type PermFile = {+ fileId: string;+ fileName: string;+ url: string;+ size: number;+};++export type ListVariablesResponse = {+ variables?: GlobalVariable[];+};++export type ListPermFilesResponse = {+ availableStorage?: number;+ files?: PermFile[];+};++export type VariableOutput = {+ variable_name: string;+ variable_value: string;+};++export type PermFileOutput = {+ file_id: string;+ file_name: string;+ url: string;+ size_kib: number;+};diff --git a/packages/pieces/community/0codekit/src/lib/common/url.ts b/packages/pieces/community/0codekit/src/lib/common/url.tsnew file mode 100644index 00000000000..e30fe5d85e8--- /dev/null+++ b/packages/pieces/community/0codekit/src/lib/common/url.ts@@ -0,0 +1,129 @@+import { Property } from '@activepieces/pieces-framework';+import { zeroCodeKitAuth } from '../auth';+import { zeroCodeKitApi } from './client';++export const zeroCodeKitUrl = {+ listShortenedUrls,+ createShortenedUrl,+ shortenedUrlIdentifier,+ shortUrlOf,+ toShortenedUrl,+ normalizeTextList,+};++export const SHORT_URL_BASE = 'https://lyl.ai';++async function listShortenedUrls(apiKey: string): Promise<ShortenedUrl[]> {+ const response = await zeroCodeKitApi.post<ListShortenedUrlsResponse>({+ apiKey,+ path: '/generate/shortenedurl/list',+ });+ return response.shortenedUrls ?? [];+}++async function createShortenedUrl({ apiKey, destination, custom }: CreateShortenedUrlParams): Promise<ShortenedUrlCreatedOutput> {+ const trimmedDestination = destination.trim();+ const response = await zeroCodeKitApi.post<CreateShortenedUrlResponse>({+ apiKey,+ path: '/generate/shortenedurl/add',+ body: {+ destination: trimmedDestination,+ custom: custom?.trim(),+ },+ });+ const identifier = response.identifier ?? custom?.trim() ?? null;+ return {+ identifier,+ short_url: response.shortenedUrl ?? (identifier === null ? null : shortUrlOf(identifier)),+ destination: trimmedDestination,+ };+}++function shortenedUrlIdentifier({ description }: { description: string }) {+ return Property.Dropdown({+ auth: zeroCodeKitAuth,+ displayName: 'Shortened URL',+ description,+ required: true,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return { disabled: true, options: [], placeholder: 'Connect your 0CodeKit account first.' };+ }+ try {+ const urls = await listShortenedUrls(auth.secret_text);+ if (urls.length === 0) {+ return { disabled: true, options: [], placeholder: 'No shortened URLs found. Create one first.' };+ }+ return {+ disabled: false,+ options: urls.map((url) => ({+ label: `${shortUrlOf(url.identifier)} → ${url.destination}`,+ value: url.identifier,+ })),+ };+ } catch (error) {+ return {+ disabled: true,+ options: [],+ placeholder: zeroCodeKitApi.describe({ error, fallback: 'Could not load shortened URLs.' }),+ };+ }+ },+ });+}++function shortUrlOf(identifier: string): string {+ return `${SHORT_URL_BASE}/${identifier}`;+}++function toShortenedUrl(url: ShortenedUrl): ShortenedUrlOutput {+ return {+ identifier: url.identifier,+ short_url: shortUrlOf(url.identifier),+ destination: url.destination,+ created_at: url.createdAt ?? null,+ };+}++function normalizeTextList(values: unknown[]): string[] {+ return values+ .flat()+ .filter((value): value is string | number => typeof value === 'string' || typeof value === 'number')+ .map((value) => String(value).trim())+ .filter((value) => value.length > 0);+}++export type ShortenedUrl = {+ identifier: string;+ destination: string;+ createdAt?: string;+};++export type ListShortenedUrlsResponse = {+ shortenedUrls?: ShortenedUrl[];+};++export type CreateShortenedUrlResponse = {+ shortenedUrl?: string;+ identifier?: string;+};++export type CreateShortenedUrlParams = {+ apiKey: string;+ destination: string;+ custom?: string;+};++export type ShortenedUrlOutput = {+ identifier: string;+ short_url: string;+ destination: string;+ created_at: string | null;+};++export type ShortenedUrlCreatedOutput = {+ identifier: string | null;+ short_url: string | null;+ destination: string;+};diff --git a/packages/pieces/community/0codekit/test/actions.test.ts b/packages/pieces/community/0codekit/test/actions.test.tsindex 1be7cff61fd..55a88863b37 100644--- a/packages/pieces/community/0codekit/test/actions.test.ts+++ b/packages/pieces/community/0codekit/test/actions.test.ts@@ -63,8 +63,8 @@ beforeEach(() => {describe('piece metadata', () => {const actions = Object.values(zeroCodeKit.actions()).filter((action) => action.name !== 'custom_api_call');- it('registers all 33 actions plus Custom API Call', () => {- expect(Object.keys(zeroCodeKit.actions())).toHaveLength(34);+ it('registers all 74 actions plus Custom API Call', () => {+ expect(Object.keys(zeroCodeKit.actions())).toHaveLength(75);});it.each(actions.map((action) => [action.name, action]))('%s carries audience, aiMetadata and classification', (_, action) => {diff --git a/packages/pieces/community/0codekit/test/ai.test.ts b/packages/pieces/community/0codekit/test/ai.test.tsnew file mode 100644index 00000000000..1a828697bb1--- /dev/null+++ b/packages/pieces/community/0codekit/test/ai.test.ts@@ -0,0 +1,205 @@+import { HttpError } from '@activepieces/pieces-common';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { entityDetectionAction } from '../src/lib/actions/ai/entity-detection';+import { languageDetectionAction } from '../src/lib/actions/ai/language-detection';+import { moodDetectionAction } from '../src/lib/actions/ai/mood-detection';+import { pictureObjectRecognitionAction } from '../src/lib/actions/ai/picture-object-recognition';+import { pictureTextRecognitionAction } from '../src/lib/actions/ai/picture-text-recognition';+import { translateTextAction } from '../src/lib/actions/ai/translate-text';+import { runAction } from './helpers';++const sendRequest = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: {+ sendRequest: (...args: unknown[]) => sendRequest(...args),+ },+ };+});++function respond(body: unknown) {+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body });+}++function sent(index = 0) {+ return sendRequest.mock.calls[index][0];+}++beforeEach(() => {+ sendRequest.mockReset();+});++describe('actions metadata', () => {+ it.each([+ [entityDetectionAction, 'Entity Detection'],+ [languageDetectionAction, 'Language Detection'],+ [moodDetectionAction, 'Mood Detection'],+ [pictureObjectRecognitionAction, 'Picture Object Recognition'],+ [pictureTextRecognitionAction, 'Picture Text Recognition'],+ [translateTextAction, 'Translate Text'],+ ])('%# has the Workato display name and AI metadata', (action, displayName) => {+ expect(action.displayName).toBe(displayName);+ expect(action.audience).toBe('both');+ expect(action.classification).toBe('READ');+ expect(action.aiMetadata?.idempotent).toBe(true);+ expect(action.aiMetadata?.description?.length).toBeGreaterThan(20);+ });+});++describe('Entity Detection', () => {+ it('posts the text and flattens detections', async () => {+ respond({+ detections: [+ { text: 'Berlin', category: 'Location', subCategory: 'City', offset: 10, length: 6, confidenceScore: 0.98 },+ { text: 'Anna', category: 'Person', offset: 0, length: 4, confidenceScore: 0.9 },+ ],+ });+ const result = await runAction({ action: entityDetectionAction, propsValue: { text: ' Anna lives in Berlin ' } });+ expect(sent().url).toBe('https://v2.1saas.co/ai/entitydetection');+ expect(sent().method).toBe('POST');+ expect(sent().headers).toEqual({ auth: 'zck_test' });+ expect(sent().body).toEqual({ text: 'Anna lives in Berlin' });+ expect(result).toEqual({+ entity_count: 2,+ entities: [+ { text: 'Berlin', category: 'Location', sub_category: 'City', offset: 11, length: 6, confidence_score: 0.98 },+ { text: 'Anna', category: 'Person', sub_category: null, offset: 1, length: 4, confidence_score: 0.9 },+ ],+ });+ });++ it('returns offsets that point into the text as the user gave it', async () => {+ const input = '\n Anna lives in Berlin';+ respond({+ detections: [+ { text: 'Anna', category: 'Person', offset: 0, length: 4 },+ { text: 'Berlin', category: 'Location', offset: 14, length: 6 },+ ],+ });+ const result = await runAction({ action: entityDetectionAction, propsValue: { text: input } });+ expect(result).toMatchObject({+ entities: [+ { text: 'Anna', offset: input.indexOf('Anna') },+ { text: 'Berlin', offset: input.indexOf('Berlin') },+ ],+ });+ });++ it('returns an empty list when nothing is found', async () => {+ respond({ detections: [] });+ expect(await runAction({ action: entityDetectionAction, propsValue: { text: 'hello' } })).toEqual({ entity_count: 0, entities: [] });+ });++ it('rejects empty text without calling the API', async () => {+ await expect(runAction({ action: entityDetectionAction, propsValue: { text: ' ' } })).rejects.toThrow('Text cannot be empty.');+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('Language Detection', () => {+ it('maps the detected language', async () => {+ respond({ name: 'German', iso6391Name: 'de', confidenceScore: 1 });+ const result = await runAction({ action: languageDetectionAction, propsValue: { text: 'Guten Tag' } });+ expect(sent().url).toBe('https://v2.1saas.co/ai/languagedetection');+ expect(sent().body).toEqual({ text: 'Guten Tag' });+ expect(result).toEqual({ language_name: 'German', language_code: 'de', confidence_score: 1 });+ });++ it('surfaces 0CodeKit error messages', async () => {+ sendRequest.mockRejectedValueOnce(+ new HttpError({}, { status: 400, responseBody: { status: 400, errorMessage: 'Text too long', code: 'bad_request' } }),+ );+ await expect(runAction({ action: languageDetectionAction, propsValue: { text: 'x' } })).rejects.toThrow(+ '0CodeKit returned 400: Text too long (bad_request)',+ );+ });+});++describe('Mood Detection', () => {+ it('flattens the scores and sentences', async () => {+ respond({+ moodOverall: 'mixed',+ moodScore: { positive: 0.5, neutral: 0.1, negative: 0.4 },+ moodPerSentence: [+ { mood: 'positive', text: 'I love it.' },+ { mood: 'negative', text: 'Shipping was slow.' },+ ],+ });+ const result = await runAction({ action: moodDetectionAction, propsValue: { text: 'I love it. Shipping was slow.' } });+ expect(sent().url).toBe('https://v2.1saas.co/ai/mooddetection');+ expect(sent().body).toEqual({ text: 'I love it. Shipping was slow.' });+ expect(result).toEqual({+ mood: 'mixed',+ positive_score: 0.5,+ neutral_score: 0.1,+ negative_score: 0.4,+ sentences: [+ { text: 'I love it.', mood: 'positive' },+ { text: 'Shipping was slow.', mood: 'negative' },+ ],+ });+ });++ it('tolerates a sparse response', async () => {+ respond({});+ expect(await runAction({ action: moodDetectionAction, propsValue: { text: 'ok' } })).toEqual({+ mood: null,+ positive_score: null,+ neutral_score: null,+ negative_score: null,+ sentences: [],+ });+ });+});++describe('Picture Object Recognition', () => {+ it('sends the image URL and returns labels', async () => {+ respond({ recognizedLabels: ['dog', 'beach'] });+ const result = await runAction({ action: pictureObjectRecognitionAction, propsValue: { imageUrl: ' https://example.com/dog.jpg ' } });+ expect(sent().url).toBe('https://v2.1saas.co/ai/pictureobjectrecognition');+ expect(sent().body).toEqual({ imageUrl: 'https://example.com/dog.jpg' });+ expect(result).toEqual({ label_count: 2, labels: ['dog', 'beach'] });+ });++ it('requires an image URL', async () => {+ await expect(runAction({ action: pictureObjectRecognitionAction, propsValue: { imageUrl: '' } })).rejects.toThrow('Image URL cannot be empty.');+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('Picture Text Recognition', () => {+ it('returns the lines and the joined text', async () => {+ respond({ recognizedTexts: ['INVOICE', 'Total: 42.00'] });+ const result = await runAction({ action: pictureTextRecognitionAction, propsValue: { imageUrl: 'https://example.com/scan.png' } });+ expect(sent().url).toBe('https://v2.1saas.co/ai/picturetextrecognition');+ expect(sent().body).toEqual({ imageUrl: 'https://example.com/scan.png' });+ expect(result).toEqual({ text: 'INVOICE\nTotal: 42.00', line_count: 2, lines: ['INVOICE', 'Total: 42.00'] });+ });++ it('handles a missing list', async () => {+ respond({});+ expect(await runAction({ action: pictureTextRecognitionAction, propsValue: { imageUrl: 'https://example.com/blank.png' } })).toEqual({+ text: '',+ line_count: 0,+ lines: [],+ });+ });+});++describe('Translate Text', () => {+ it('sends text and target language', async () => {+ respond({ translation: 'Hola, mundo!' });+ const result = await runAction({ action: translateTextAction, propsValue: { text: 'Hello, world!', resultLang: 'es' } });+ expect(sent().url).toBe('https://v2.1saas.co/ai/translate');+ expect(sent().body).toEqual({ text: 'Hello, world!', resultLang: 'es' });+ expect(result).toEqual({ translation: 'Hola, mundo!', target_language: 'es' });+ });++ it('requires a target language', async () => {+ await expect(runAction({ action: translateTextAction, propsValue: { text: 'Hello' } })).rejects.toThrow('Target Language cannot be empty.');+ expect(sendRequest).not.toHaveBeenCalled();+ });+});diff --git a/packages/pieces/community/0codekit/test/code.test.ts b/packages/pieces/community/0codekit/test/code.test.tsnew file mode 100644index 00000000000..bdc8cfa0cd8--- /dev/null+++ b/packages/pieces/community/0codekit/test/code.test.ts@@ -0,0 +1,340 @@+import { HttpError } from '@activepieces/pieces-common';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { runJavascriptCodeAction } from '../src/lib/actions/code/run-javascript-code';+import { runPythonCodeAction } from '../src/lib/actions/code/run-python-code';+import { cryptoDecryptAction } from '../src/lib/actions/crypto/crypto-decrypt';+import { cryptoEncryptAction } from '../src/lib/actions/crypto/crypto-encrypt';+import { cryptoHashAction } from '../src/lib/actions/crypto/crypto-hash';+import { createASchedulerAction } from '../src/lib/actions/scheduler/create-a-scheduler';+import { deleteASchedulerAction } from '../src/lib/actions/scheduler/delete-a-scheduler';+import { listSchedulersAction } from '../src/lib/actions/scheduler/list-schedulers';+import { CODE_TIMEOUT_MS } from '../src/lib/common/code';+import { loadDropdownOptions, runAction, TEST_AUTH } from './helpers';++const sendRequest = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: {+ sendRequest: (...args: unknown[]) => sendRequest(...args),+ },+ };+});++function respond(body: unknown) {+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body });+}++function fail({ status, body }: { status: number; body: unknown }) {+ sendRequest.mockRejectedValueOnce(new HttpError({}, { status, responseBody: body }));+}++function sent(index = 0) {+ return sendRequest.mock.calls[index][0];+}++beforeEach(() => {+ sendRequest.mockReset();+});++describe('metadata', () => {+ const actions: [string, MetadataAction, string, boolean][] = [+ ['Run Javascript Code', runJavascriptCodeAction, 'WRITE', false],+ ['Run Python Code', runPythonCodeAction, 'WRITE', false],+ ['Crypto Decrypt', cryptoDecryptAction, 'READ', true],+ ['Crypto Encrypt', cryptoEncryptAction, 'READ', true],+ ['Crypto Hash', cryptoHashAction, 'READ', true],+ ['Create a Scheduler', createASchedulerAction, 'WRITE', false],+ ['Delete a Scheduler', deleteASchedulerAction, 'DESTRUCTIVE', false],+ ['List Schedulers', listSchedulersAction, 'SEARCH', true],+ ];++ it.each(actions)('%s has the expected metadata', (displayName, action, classification, idempotent) => {+ expect(action.displayName).toBe(displayName);+ expect(action.classification).toBe(classification);+ expect(action.audience).toBe('both');+ expect(action.aiMetadata?.idempotent).toBe(idempotent);+ expect(action.aiMetadata?.description?.length).toBeGreaterThan(20);+ });++ it('Python states the credit cost', () => {+ expect(runPythonCodeAction.description).toContain('50 credits');+ });+});++describe('code', () => {+ it('JavaScript sends code with a timeout above 180 s and wraps an object result under result', async () => {+ respond({ total: 3 });+ const result = await runAction({ action: runJavascriptCodeAction, propsValue: { code: 'return { total: 3 };', dependencies: [] } });+ expect(sent().url).toBe('https://v2.1saas.co/code/javascript');+ expect(sent().headers).toEqual({ auth: 'zck_test' });+ expect(sent().timeout).toBe(CODE_TIMEOUT_MS);+ expect(CODE_TIMEOUT_MS).toBeGreaterThan(180_000);+ expect(sent().body).toEqual({ code: 'return { total: 3 };' });+ expect(result).toEqual({ result: { total: 3 } });+ });++ it('JavaScript wraps a primitive or array result', async () => {+ respond([1, 2]);+ expect(await runAction({ action: runJavascriptCodeAction, propsValue: { code: 'return [1, 2];' } })).toEqual({ result: [1, 2] });+ respond('');+ expect(await runAction({ action: runJavascriptCodeAction, propsValue: { code: '1' } })).toEqual({ result: null });+ });++ it('JavaScript injects inputs as a const and passes system packages', async () => {+ respond({ ok: true });+ await runAction({ action: runJavascriptCodeAction, propsValue: {+ code: 'return inputs.name;',+ inputs: { name: 'a"b' },+ dependencies: ['ffmpeg', ' '],+ } });+ expect(sent().body).toEqual({+ code: 'const inputs = {"name":"a\\"b"};\nreturn inputs.name;',+ dependencies: ['ffmpeg'],+ });+ });++ it('Python unwraps result, injects inputs and passes libraries', async () => {+ respond({ result: { sum: 5 } });+ const result = await runAction({ action: runPythonCodeAction, propsValue: {+ code: 'result = {"sum": inputs["a"] + 2}',+ inputs: { a: 3 },+ requirements: ['requests'],+ } });+ expect(sent().url).toBe('https://v2.1saas.co/code/python');+ expect(sent().timeout).toBe(CODE_TIMEOUT_MS);+ expect(sent().body).toEqual({+ code: 'inputs = __import__("json").loads("{\\"a\\":3}")\nresult = {"sum": inputs["a"] + 2}',+ requirements: ['requests'],+ });+ expect(result).toEqual({ result: { sum: 5 } });+ });++ it('Python wraps a scalar result', async () => {+ respond({ result: 42 });+ const result = await runAction({ action: runPythonCodeAction, propsValue: { code: 'result = 42', inputs: { a: 1 } } });+ expect(result).toEqual({ result: 42 });+ });++ it.each([+ ['a single future import', 'from __future__ import annotations\nresult = 1', 'from __future__ import annotations\n@\nresult = 1'],+ [+ 'a docstring and several future imports',+ '"""doc"""\nfrom __future__ import annotations\nfrom __future__ import division\nresult = 1',+ '"""doc"""\nfrom __future__ import annotations\nfrom __future__ import division\n@\nresult = 1',+ ],+ [+ 'a parenthesised future import',+ 'from __future__ import (\n annotations,\n division,\n)\nresult = 1',+ 'from __future__ import (\n annotations,\n division,\n)\n@\nresult = 1',+ ],+ [+ 'a backslash-continued future import',+ 'from __future__ import annotations, \\\n division\nresult = 1',+ 'from __future__ import annotations, \\\n division\n@\nresult = 1',+ ],+ ['no future import', 'import os\nresult = 1', '@\nimport os\nresult = 1'],+ ['a one-line module docstring', '"""Doc."""\nimport os\nresult = 1', '"""Doc."""\n@\nimport os\nresult = 1'],+ ['a multi-line module docstring', '# notes\n"""Doc.\n\nMore.\n"""\nresult = 1', '# notes\n"""Doc.\n\nMore.\n"""\n@\nresult = 1'],+ [+ 'a shebang, encoding comment and future import',+ '#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import annotations\nresult = 1',+ '#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import annotations\n@\nresult = 1',+ ],+ [+ 'a multi-line module docstring that mentions a future import',+ '"""Notes.\nfrom __future__ import annotations\n"""\nresult = 1',+ '"""Notes.\nfrom __future__ import annotations\n"""\n@\nresult = 1',+ ],+ [+ 'code whose later docstring mentions a future import',+ 'def f():\n """x"""\n\nDOC = """\nfrom __future__ import annotations\n"""\nresult = 1',+ '@\ndef f():\n """x"""\n\nDOC = """\nfrom __future__ import annotations\n"""\nresult = 1',+ ],+ ])('Python defines inputs after %s', async (_label, code, expected) => {+ respond({ result: 1 });+ await runAction({ action: runPythonCodeAction, propsValue: { code, inputs: { a: 1 } } });+ expect(sent().body.code).toBe(expected.replace('@', 'inputs = __import__("json").loads("{\\"a\\":1}")'));+ });++ it.each([+ ['a use strict directive', "'use strict';\nreturn inputs.a;", "'use strict';\n@\nreturn inputs.a;"],+ ['a comment and a double-quoted directive', '// run\n"use strict"\nreturn inputs.a;', '// run\n"use strict"\n@\nreturn inputs.a;'],+ ['a hashbang', '#!/usr/bin/env bun\nreturn inputs.a;', '#!/usr/bin/env bun\n@\nreturn inputs.a;'],+ ['plain code', 'return inputs.a;', '@\nreturn inputs.a;'],+ ])('JavaScript defines inputs after %s', async (_label, code, expected) => {+ respond({ ok: true });+ await runAction({ action: runJavascriptCodeAction, propsValue: { code, inputs: { a: 1 } } });+ expect(sent().body.code).toBe(expected.replace('@', 'const inputs = {"a":1};'));+ });++ it.each([undefined, null, '', {}])('JavaScript sends the code unchanged when Inputs is %j', async (inputs) => {+ respond({ ok: true });+ await runAction({ action: runJavascriptCodeAction, propsValue: { code: 'return 1;', inputs } });+ expect(sent().body.code).toBe('return 1;');+ });++ it('JavaScript keeps a script that declares its own inputs when Inputs is blank', async () => {+ respond({ ok: true });+ const code = 'const inputs = { a: 1 };\nreturn inputs.a;';+ await runAction({ action: runJavascriptCodeAction, propsValue: { code } });+ expect(sent().body.code).toBe(code);+ expect(sent().body.code.match(/\bconst inputs\b/g)).toHaveLength(1);+ });++ it.each([undefined, null, '', {}])('Python defines inputs as an empty object when Inputs is %j', async (inputs) => {+ respond({ result: 0 });+ await runAction({ action: runPythonCodeAction, propsValue: { code: 'result = len(inputs)', inputs } });+ expect(sent().body.code).toBe('inputs = __import__("json").loads("{}")\nresult = len(inputs)');+ });++ it('surfaces the vendor error message', async () => {+ fail({ status: 400, body: { status: 400, errorMessage: 'NameError: x is not defined', code: 'bad_request' } });+ await expect(runAction({ action: runPythonCodeAction, propsValue: { code: 'result = x' } })).rejects.toThrow(+ '0CodeKit returned 400: NameError: x is not defined (bad_request)',+ );+ });++ it('explains the 180 s limit on a gateway timeout', async () => {+ fail({ status: 504, body: { errorMessage: 'Execution timed out' } });+ await expect(runAction({ action: runJavascriptCodeAction, propsValue: { code: 'while(true){}' } })).rejects.toThrow('limited to 180 seconds');+ });++ it('explains a client-side timeout', async () => {+ const abort = new Error('This operation was aborted');+ abort.name = 'AbortError';+ sendRequest.mockRejectedValueOnce(abort);+ await expect(runAction({ action: runJavascriptCodeAction, propsValue: { code: 'while(true){}' } })).rejects.toThrow(+ 'did not answer within 190 seconds',+ );+ });+});++describe('crypto', () => {+ it('Encrypt sends cipher, message and key', async () => {+ respond({ encryptedText: 'U2FsdGVk' });+ const result = await runAction({ action: cryptoEncryptAction, propsValue: { cryptoType: 'AES', message: 'hi', secretKey: 'k' } });+ expect(sent().url).toBe('https://v2.1saas.co/crypto/encrypt');+ expect(sent().body).toEqual({ cryptoType: 'AES', message: 'hi', secretKey: 'k' });+ expect(result).toEqual({ encrypted_text: 'U2FsdGVk' });+ });++ it('Decrypt sends ciphertext', async () => {+ respond({ decryptedText: 'hi' });+ const result = await runAction({ action: cryptoDecryptAction, propsValue: { cryptoType: 'RC4', ciphertext: 'U2F', secretKey: 'k' } });+ expect(sent().url).toBe('https://v2.1saas.co/crypto/decrypt');+ expect(sent().body).toEqual({ cryptoType: 'RC4', ciphertext: 'U2F', secretKey: 'k' });+ expect(result).toEqual({ decrypted_text: 'hi' });+ });++ it('Hash drops the key for plain algorithms', async () => {+ respond({ hashedText: 'abc' });+ const result = await runAction({ action: cryptoHashAction, propsValue: { hashType: 'SHA256', message: 'hi', secretKey: 'k' } });+ expect(sent().url).toBe('https://v2.1saas.co/crypto/hash');+ expect(sent().body).toEqual({ hashType: 'SHA256', message: 'hi' });+ expect(result).toEqual({ hashed_text: 'abc', algorithm: 'SHA256' });+ });++ it('Hash sends the key for HMAC and requires it', async () => {+ respond({ hashedText: 'def' });+ await runAction({ action: cryptoHashAction, propsValue: { hashType: 'HmacSHA256', message: 'hi', secretKey: 'k' } });+ expect(sent().body).toEqual({ hashType: 'HmacSHA256', message: 'hi', secretKey: 'k' });+ await expect(runAction({ action: cryptoHashAction, propsValue: { hashType: 'HmacSHA256', message: 'hi' } })).rejects.toThrow(+ 'needs a Secret Key',+ );+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });+});++describe('scheduler', () => {+ it('Create sends a one-time schedule with stringified data', async () => {+ respond({ taskId: 't1', nextExecution: '2026-12-31T09:00:00.000Z' });+ const result = await runAction({ action: createASchedulerAction, propsValue: {+ sendToWebhook: ' https://hook.test/a ',+ data: { a: 1 },+ intervalType: '1',+ schedule: '2026-12-31T09:00:00Z',+ } });+ expect(sent().url).toBe('https://v2.1saas.co/operator/scheduler/add');+ expect(sent().body).toEqual({+ sendToWebhook: 'https://hook.test/a',+ data: '{"a":1}',+ intervalType: 1,+ intervalOptions: '2026-12-31T09:00:00Z',+ });+ expect(result).toEqual({ task_id: 't1', next_execution: '2026-12-31T09:00:00.000Z', end_date: null });+ });++ it('Create parses timestamps, date lists, cron and period schedules', async () => {+ const cases: [string, string, unknown][] = [+ ['1', '1798707600', 1798707600],+ ['2', '1798707600, 1798794000', [1798707600, 1798794000]],+ ['2', '2026-12-31T09:00:00Z,\n2027-01-01T09:00:00Z', ['2026-12-31T09:00:00Z', '2027-01-01T09:00:00Z']],+ ['3', ' 0 9 * * 1 ', '0 9 * * 1'],+ ['4', 'days;2', 'days;2'],+ ];+ for (const [index, [intervalType, schedule, expected]] of cases.entries()) {+ respond({ taskId: 't', nextExecution: 'x' });+ await runAction({ action: createASchedulerAction, propsValue: {+ sendToWebhook: 'https://hook.test',+ intervalType,+ schedule,+ endDate: '2027-06-01T00:00:00Z',+ } });+ expect(sent(index).body.intervalOptions).toEqual(expected);+ expect(sent(index).body.intervalType).toBe(Number(intervalType));+ expect(sent(index).body.data).toBe('{}');+ expect(sent(index).body.endDate).toBe('2027-06-01T00:00:00Z');+ }+ });++ it('Create rejects an empty schedule', async () => {+ await expect(+ runAction({ action: createASchedulerAction, propsValue: { sendToWebhook: 'https://hook.test', intervalType: '3', schedule: ' ' } }),+ ).rejects.toThrow('Enter a Schedule');+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('Delete sends the task id', async () => {+ respond({ message: 'Task deleted.' });+ const result = await runAction({ action: deleteASchedulerAction, propsValue: { taskId: 't1' } });+ expect(sent().url).toBe('https://v2.1saas.co/operator/scheduler/del');+ expect(sent().body).toEqual({ taskId: 't1' });+ expect(result).toEqual({ deleted: true, task_id: 't1', message: 'Task deleted.' });+ });++ it('List maps tasks', async () => {+ respond({ tasks: [{ taskId: 't1', webhook: 'https://hook.test', nextExecution: 'n', data: '{}' }] });+ const result = await runAction({ action: listSchedulersAction, propsValue: {} });+ expect(sent().url).toBe('https://v2.1saas.co/operator/scheduler/list');+ expect(result).toEqual({+ count: 1,+ schedulers: [{ task_id: 't1', webhook: 'https://hook.test', next_execution: 'n', data: '{}' }],+ });+ });++ it('Scheduler dropdown lists tasks and reports errors', async () => {+ const taskIdDropdown = deleteASchedulerAction.props.taskId;+ respond({ tasks: [{ taskId: 't1', webhook: 'https://hook.test', nextExecution: 'n', data: '{}' }] });+ expect(await loadDropdownOptions({ dropdown: taskIdDropdown, auth: TEST_AUTH })).toEqual({+ disabled: false,+ options: [{ label: 'https://hook.test (next run n)', value: 't1' }],+ });+ respond({ tasks: [] });+ expect(await loadDropdownOptions({ dropdown: taskIdDropdown, auth: TEST_AUTH })).toMatchObject({ disabled: true });+ fail({ status: 401, body: { errorMessage: 'Invalid API key.' } });+ expect(await loadDropdownOptions({ dropdown: taskIdDropdown, auth: TEST_AUTH })).toMatchObject({+ disabled: true,+ placeholder: '0CodeKit returned 401: Invalid API key.',+ });+ });+});++type MetadataAction = {+ displayName: string;+ classification?: string;+ audience?: string;+ aiMetadata?: { description?: string; idempotent?: boolean };+};diff --git a/packages/pieces/community/0codekit/test/hardening.test.ts b/packages/pieces/community/0codekit/test/hardening.test.tsindex caf6068c562..eb574b52136 100644--- a/packages/pieces/community/0codekit/test/hardening.test.ts+++ b/packages/pieces/community/0codekit/test/hardening.test.ts@@ -1,6 +1,20 @@+import { readdirSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import { ApFile } from '@activepieces/pieces-framework';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { entityDetectionAction } from '../src/lib/actions/ai/entity-detection';import { validateIbanAction } from '../src/lib/actions/business/validate-iban';+import { runJavascriptCodeAction } from '../src/lib/actions/code/run-javascript-code';+import { generateQrCodeAction } from '../src/lib/actions/image/generate-qr-code';+import { createPdfFromHtmlAction } from '../src/lib/actions/pdf/create-pdf-from-html';+import { getPdfPageCountAction } from '../src/lib/actions/pdf/get-pdf-page-count';+import { splitPdfAction } from '../src/lib/actions/pdf/split-pdf';+import { getAPermFileAction } from '../src/lib/actions/storage/get-a-perm-file';+import { addTemporaryFileAction } from '../src/lib/actions/temp-file/add-temporary-file';import { zeroCodeKitApi, ZEROCODEKIT_TIMEOUT_MS } from '../src/lib/common/client';+import { zeroCodeKitFiles } from '../src/lib/common/files';+import { zeroCodeKitPdf } from '../src/lib/common/pdf';+import { zeroCodeKitStorage } from '../src/lib/common/storage';import { runAction } from './helpers';const sendRequest = vi.fn();@@ -15,6 +29,7 @@ vi.mock('@activepieces/pieces-common', async (importOriginal) => {};});+const PDF = new ApFile('in.pdf', Buffer.from('%PDF-in'), 'pdf');const STEP_LIMIT_MS = 600_000;const write = vi.fn();@@ -22,6 +37,11 @@ function respond(body: unknown) {sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body });}+function binary(text: string) {+ const buffer = Buffer.from(text);+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);+}+function call(index: number) {return sendRequest.mock.calls[index][0];}@@ -39,6 +59,35 @@ describe('request timeouts', () => {expect(call(0).timeout).toBe(30_000);});+ it('gives AI endpoints a 60 second timeout', async () => {+ respond({ entities: [] });+ await runAction({ action: entityDetectionAction, propsValue: { text: 'Berlin' }, write });+ expect(call(0).timeout).toBe(60_000);+ });++ it('gives JSON file endpoints a 120 second timeout', async () => {+ respond({ pageCount: 1 });+ await runAction({ action: getPdfPageCountAction, propsValue: { pdf: PDF }, write });+ expect(call(0).timeout).toBe(120_000);++ respond({ url: 'https://prod.0codekit.com/tmp/a.pdf', fileName: 'a.pdf' });+ await runAction({ action: addTemporaryFileAction, propsValue: { file: PDF }, write });+ expect(call(1).timeout).toBe(120_000);+ });++ it('gives binary file endpoints a 120 second timeout', async () => {+ respond(binary('%PDF-html'));+ await runAction({ action: createPdfFromHtmlAction, propsValue: { html: '<p>x</p>' }, write });+ expect(call(0).timeout).toBe(120_000);+ });++ it('keeps code runs under the step limit', async () => {+ respond({ ok: true });+ await runAction({ action: runJavascriptCodeAction, propsValue: { code: 'return 1' }, write });+ expect(call(0).timeout).toBeGreaterThan(180_000);+ expect(call(0).timeout).toBeLessThan(STEP_LIMIT_MS - 60_000);+ });+it('bounds every timeout class below the step limit', () => {for (const value of Object.values(ZEROCODEKIT_TIMEOUT_MS)) {expect(value).toBeGreaterThan(0);@@ -58,3 +107,145 @@ describe('request timeouts', () => {);});});++describe('downloads of links returned by 0CodeKit', () => {+ it('downloads https links on 0CodeKit domains without following redirects', async () => {+ respond(binary('%PDF-a'));+ await zeroCodeKitFiles.download({ url: 'https://prod.0codekit.com/files/a.pdf', failure: 'failed' });+ expect(call(0)).toMatchObject({+ method: 'GET',+ url: 'https://prod.0codekit.com/files/a.pdf',+ followRedirects: false,+ timeout: 120_000,+ responseType: 'arraybuffer',+ });+ expect(call(0).headers).toBeUndefined();+ });++ it.each([+ 'https://v2.1saas.co/files/a.pdf',+ 'https://storage.0codekit.com/a.pdf',+ 'https://PROD.0CODEKIT.COM/a.pdf',+ ])('accepts %s', (url) => {+ expect(() => zeroCodeKitFiles.assertZeroCodeKitUrl(url)).not.toThrow();+ });++ it.each([+ ['cloud metadata over http', 'http://169.254.169.254/latest/meta-data/'],+ ['cloud metadata over https', 'https://169.254.169.254/latest/meta-data/iam/security-credentials/'],+ ['GCP metadata host', 'https://metadata.google.internal/computeMetadata/v1/'],+ ['localhost', 'https://localhost/secret'],+ ['plain http on a 0CodeKit host', 'http://prod.0codekit.com/a.pdf'],+ ['look-alike suffix', 'https://prod.0codekit.com.evil.example/a.pdf'],+ ['look-alike prefix', 'https://evil0codekit.com/a.pdf'],+ ['short-link domain', 'https://lyl.ai/abc'],+ ['non-default port', 'https://prod.0codekit.com:8443/a.pdf'],+ ['embedded credentials', 'https://user:[email protected]/a.pdf'],+ ['file scheme', 'file:///etc/passwd'],+ ['not a URL', 'not a url'],+ ])('refuses %s before any request', async (_label, url) => {+ await expect(zeroCodeKitFiles.download({ url, failure: 'failed' })).rejects.toThrow(/Refusing to download|not a valid URL/);+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it.each([+ [301, '<html>Moved</html>'],+ [302, ''],+ [307, ''],+ ])('fails on a %s redirect instead of saving its body as the file', async (status, body) => {+ sendRequest.mockResolvedValueOnce({ status, headers: { location: 'https://elsewhere.example/a.pdf' }, body: binary(body) });+ await expect(zeroCodeKitFiles.download({ url: 'https://prod.0codekit.com/a.pdf', failure: 'Download failed.' })).rejects.toThrow(+ `Download failed. 0CodeKit answered with a redirect (${status}), which is not followed.`,+ );+ });++ it('Split PDF saves nothing when a part link redirects', async () => {+ respond({ pdfUrls: ['https://prod.0codekit.com/a.pdf'] });+ sendRequest.mockResolvedValueOnce({ status: 302, headers: {}, body: binary('') });+ await expect(runAction({ action: splitPdfAction, propsValue: { pdf: PDF, mode: 'interval', interval: 1 }, write })).rejects.toThrow(+ /redirect \(302\)/,+ );+ expect(write).not.toHaveBeenCalled();+ });++ it('Split PDF refuses a foreign part link before downloading any part', async () => {+ respond({ pdfUrls: ['https://prod.0codekit.com/a.pdf', 'http://169.254.169.254/latest/meta-data/'] });+ await expect(runAction({ action: splitPdfAction, propsValue: { pdf: PDF, mode: 'interval', interval: 1 }, write })).rejects.toThrow(+ /Refusing to download/,+ );+ expect(sendRequest).toHaveBeenCalledTimes(1);+ expect(write).not.toHaveBeenCalled();+ });++ it('Split PDF downloads parts with no redirects and a bounded timeout', async () => {+ respond({ pdfUrls: ['https://prod.0codekit.com/a.pdf'] });+ respond(binary('%PDF-a'));+ await runAction({ action: splitPdfAction, propsValue: { pdf: PDF, mode: 'interval', interval: 1 }, write });+ expect(call(1).followRedirects).toBe(false);+ expect(call(1).timeout).toBeGreaterThan(0);+ expect(call(1).timeout).toBeLessThanOrEqual(120_000);+ });++ it('Split PDF stops when the download budget is spent', async () => {+ const now = vi.spyOn(Date, 'now');+ now.mockReturnValueOnce(0).mockReturnValue(480_001);+ respond({ pdfUrls: ['https://prod.0codekit.com/a.pdf'] });+ await expect(runAction({ action: splitPdfAction, propsValue: { pdf: PDF, mode: 'interval', interval: 1 }, write })).rejects.toThrow(+ /took too long/,+ );+ expect(sendRequest).toHaveBeenCalledTimes(1);+ now.mockRestore();+ });++ it('Generate QR Code refuses a foreign image link', async () => {+ respond(binary(JSON.stringify({ imageUrl: 'https://169.254.169.254/qr.png' })));+ await expect(runAction({ action: generateQrCodeAction, propsValue: { data: 'hi' }, write })).rejects.toThrow(/Refusing to download/);+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });++ it('Get a Perm File refuses a foreign download link', async () => {+ respond({ url: 'https://attacker.example/f1.pdf' });+ await expect(runAction({ action: getAPermFileAction, propsValue: { fileId: 'f1' }, write })).rejects.toThrow(/Refusing to download/);+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });++ it('Get a Perm File with Link Only returns the link without downloading it', async () => {+ respond({ url: 'https://attacker.example/f1.pdf' });+ await expect(runAction({ action: getAPermFileAction, propsValue: { fileId: 'f1', linkOnly: true }, write })).resolves.toEqual({+ file_id: 'f1',+ url: 'https://attacker.example/f1.pdf',+ });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ });++ it('keeps path separators out of a downloaded file name', () => {+ expect(zeroCodeKitStorage.fileNameFromUrl({ url: 'https://prod.0codekit.com/f/..%2F..%2Fetc%2Fpasswd', fallback: 'f1' })).toBe(+ '.._.._etc_passwd',+ );+ expect(zeroCodeKitStorage.fileNameFromUrl({ url: 'https://prod.0codekit.com/', fallback: 'f1' })).toBe('f1');+ });+});++describe('file inputs', () => {+ it('recognises a file from another framework copy by its shape', () => {+ const foreign = { filename: 'a.pdf', extension: 'pdf', data: Buffer.from('x'), base64: 'eA==' };+ expect(zeroCodeKitPdf.isApFile(foreign)).toBe(true);+ expect(zeroCodeKitPdf.isApFile(PDF)).toBe(true);+ expect(zeroCodeKitPdf.isApFile({ filename: 'a.pdf' })).toBe(false);+ expect(zeroCodeKitPdf.isApFile(null)).toBe(false);+ });++ it('never uses instanceof ApFile in the piece source', () => {+ const offenders = sourceFiles(join(__dirname, '..', 'src')).filter((file) =>+ /instanceof\s+ApFile/.test(readFileSync(file, 'utf8')),+ );+ expect(offenders).toEqual([]);+ });+});++function sourceFiles(dir: string): string[] {+ return readdirSync(dir).flatMap((entry) => {+ const path = join(dir, entry);+ return statSync(path).isDirectory() ? sourceFiles(path) : path.endsWith('.ts') ? [path] : [];+ });+}diff --git a/packages/pieces/community/0codekit/test/image.test.ts b/packages/pieces/community/0codekit/test/image.test.tsnew file mode 100644index 00000000000..490e89fa793--- /dev/null+++ b/packages/pieces/community/0codekit/test/image.test.ts@@ -0,0 +1,167 @@+import { ApFile } from '@activepieces/pieces-framework';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { decodeQrCodeAction } from '../src/lib/actions/image/decode-qr-code';+import { generateQrCodeAction } from '../src/lib/actions/image/generate-qr-code';+import { imageExifAction } from '../src/lib/actions/image/image-exif';+import { addTemporaryFileAction } from '../src/lib/actions/temp-file/add-temporary-file';+import { runAction } from './helpers';++const sendRequest = vi.fn();+const write = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: {+ sendRequest: (...args: unknown[]) => sendRequest(...args),+ },+ };+});++const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);+const IMAGE = new ApFile('photo.jpg', Buffer.from('jpeg-bytes'), 'jpg');++function respond(body: unknown) {+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body });+}++function sent(index = 0) {+ return sendRequest.mock.calls[index][0];+}++function toArrayBuffer(data: Buffer): ArrayBuffer {+ return new Uint8Array(data).buffer;+}++beforeEach(() => {+ sendRequest.mockReset();+ write.mockReset();+ write.mockResolvedValue('file://stored');+});++describe('actions metadata', () => {+ it.each([+ [decodeQrCodeAction, 'Decode a QRCode'],+ [generateQrCodeAction, 'Generate a QRCode'],+ [imageExifAction, 'Image Exif'],+ [addTemporaryFileAction, 'Add a Temporary File and Recieve a URL'],+ ])('%# has the Workato display name and AI metadata', (action, displayName) => {+ expect(action.displayName).toBe(displayName);+ expect(action.audience).toBe('both');+ expect(action.classification).toBeDefined();+ expect(action.aiMetadata?.description?.length).toBeGreaterThan(20);+ });+});++describe('Decode a QRCode', () => {+ it('sends the file as base64 and returns the decoded data', async () => {+ respond({ data: 'https://example.com' });+ const result = await runAction({ action: decodeQrCodeAction, propsValue: { file: IMAGE, url: 'https://ignored.test/qr.png' }, write });+ expect(sent().url).toBe('https://v2.1saas.co/generate/qrcode/decode');+ expect(sent().headers).toEqual({ auth: 'zck_test' });+ expect(sent().body).toEqual({ buffer: IMAGE.base64 });+ expect(result).toEqual({ data: 'https://example.com' });+ });++ it('falls back to the URL', async () => {+ respond({ data: 'hello' });+ await runAction({ action: decodeQrCodeAction, propsValue: { url: ' https://example.com/qr.png ' }, write });+ expect(sent().body).toEqual({ url: 'https://example.com/qr.png' });+ });++ it('requires a file or a URL', async () => {+ await expect(runAction({ action: decodeQrCodeAction, propsValue: {}, write })).rejects.toThrow('Provide either an Image File or an Image URL.');+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('Image Exif', () => {+ it('returns the EXIF data', async () => {+ respond({ exifData: { Make: 'Canon' } });+ const result = await runAction({ action: imageExifAction, propsValue: { file: IMAGE }, write });+ expect(sent().url).toBe('https://v2.1saas.co/image/exif');+ expect(sent().body).toEqual({ buffer: IMAGE.base64 });+ expect(result).toEqual({ exif_data: { Make: 'Canon' } });+ });++ it('returns an empty object when there is no EXIF data', async () => {+ respond({});+ expect(await runAction({ action: imageExifAction, propsValue: { url: 'https://example.com/a.jpg' }, write })).toEqual({ exif_data: {} });+ });+});++describe('Generate a QRCode', () => {+ it('builds nested options and saves a binary PNG response', async () => {+ respond(toArrayBuffer(PNG));+ const result = await runAction({ action: generateQrCodeAction, propsValue: {+ data: 'https://example.com',+ fileName: 'ticket',+ width: 300,+ errorCorrectionLevel: 'H',+ dotsType: 'rounded',+ dotsColor: 'FF0000',+ cornersDotColor: '#00FF00',+ image: 'https://example.com/logo.png',+ hideBackgroundDots: true,+ }, write });+ expect(sent().url).toBe('https://v2.1saas.co/generate/qrcode/encode');+ expect(sent().responseType).toBe('arraybuffer');+ expect(sent().body).toEqual({+ data: 'https://example.com',+ width: 300,+ image: 'https://example.com/logo.png',+ qrOptions: { errorCorrectionLevel: 'H' },+ dotsOptions: { type: 'rounded', color: '#FF0000' },+ cornersDotOptions: { color: '#00FF00' },+ imageOptions: { hideBackgroundDots: true },+ });+ expect(write).toHaveBeenCalledWith({ fileName: 'ticket.png', data: PNG });+ expect(result).toEqual({ file: 'file://stored', file_name: 'ticket.png', size_bytes: PNG.length, image_url: null });+ });++ it('omits logo options when no logo is set', async () => {+ respond(toArrayBuffer(PNG));+ await runAction({ action: generateQrCodeAction, propsValue: { data: 'x', hideBackgroundDots: true }, write });+ expect(sent().body).toEqual({ data: 'x' });+ });++ it('downloads the image when the API returns an image URL', async () => {+ respond(toArrayBuffer(Buffer.from(JSON.stringify({ imageUrl: 'https://prod.0codekit.com/qr.png', fileName: 'qr.png' }))));+ respond(toArrayBuffer(PNG));+ const result = await runAction({ action: generateQrCodeAction, propsValue: { data: 'x', fileName: 'qr-code.png' }, write });+ expect(sent(1)).toMatchObject({ method: 'GET', url: 'https://prod.0codekit.com/qr.png', responseType: 'arraybuffer' });+ expect(write).toHaveBeenCalledWith({ fileName: 'qr-code.png', data: PNG });+ expect(result).toMatchObject({ file_name: 'qr-code.png', image_url: 'https://prod.0codekit.com/qr.png' });+ });++ it('decodes a data URI image URL without downloading', async () => {+ const dataUri = `data:image/png;base64,${PNG.toString('base64')}`;+ respond(toArrayBuffer(Buffer.from(JSON.stringify({ imageUrl: dataUri }))));+ await runAction({ action: generateQrCodeAction, propsValue: { data: 'x' }, write });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ expect(write).toHaveBeenCalledWith({ fileName: 'qr-code.png', data: PNG });+ });++ it('fails when the response has no image', async () => {+ respond(toArrayBuffer(Buffer.from('{}')));+ await expect(runAction({ action: generateQrCodeAction, propsValue: { data: 'x' }, write })).rejects.toThrow('did not return a QR code image');+ expect(write).not.toHaveBeenCalled();+ });+});++describe('Add a Temporary File and Recieve a URL', () => {+ it('uploads the file and returns the URL', async () => {+ respond({ url: 'https://temp.test/abc', fileName: 'photo.jpg' });+ const result = await runAction({ action: addTemporaryFileAction, propsValue: { file: IMAGE }, write });+ expect(sent().url).toBe('https://v2.1saas.co/storage/temp');+ expect(sent().body).toEqual({ buffer: IMAGE.base64, fileName: 'photo.jpg' });+ expect(result).toEqual({ url: 'https://temp.test/abc', file_name: 'photo.jpg' });+ });++ it('uses the custom file name', async () => {+ respond({ url: 'https://temp.test/abc', fileName: 'renamed.jpg' });+ await runAction({ action: addTemporaryFileAction, propsValue: { file: IMAGE, fileName: ' renamed.jpg ' }, write });+ expect(sent().body).toEqual({ buffer: IMAGE.base64, fileName: 'renamed.jpg' });+ });+});diff --git a/packages/pieces/community/0codekit/test/output-schemas-business-ai.test.ts b/packages/pieces/community/0codekit/test/output-schemas-business-ai.test.tsindex 803a52116e2..67e2e476cd6 100644--- a/packages/pieces/community/0codekit/test/output-schemas-business-ai.test.ts+++ b/packages/pieces/community/0codekit/test/output-schemas-business-ai.test.ts@@ -1,5 +1,11 @@import { OutputSchema } from '@activepieces/pieces-framework';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { entityDetectionAction } from '../src/lib/actions/ai/entity-detection';+import { languageDetectionAction } from '../src/lib/actions/ai/language-detection';+import { moodDetectionAction } from '../src/lib/actions/ai/mood-detection';+import { pictureObjectRecognitionAction } from '../src/lib/actions/ai/picture-object-recognition';+import { pictureTextRecognitionAction } from '../src/lib/actions/ai/picture-text-recognition';+import { translateTextAction } from '../src/lib/actions/ai/translate-text';import { lookupVatRatesAction } from '../src/lib/actions/business/lookup-vat-rates';import { validateBicAction } from '../src/lib/actions/business/validate-bic';import { validateEmailAction } from '../src/lib/actions/business/validate-email';@@ -61,13 +67,33 @@ const CASES: SchemaCase[] = [props: { text: 'the cat sat', keywords: ['cat'] },response: { findings: [{ keyword: 'cat', contains: true, foundPositions: [4] }] },},+ {+ action: entityDetectionAction,+ props: { text: 'Satya Nadella' },+ response: {+ detections: [{ text: 'Satya Nadella', category: 'Person', subCategory: null, offset: 0, length: 13, confidenceScore: 1 }],+ },+ },+ { action: languageDetectionAction, props: { text: 'Bonjour' }, response: { name: 'French', iso6391Name: 'fr', confidenceScore: 1 } },+ {+ action: moodDetectionAction,+ props: { text: 'I love this.' },+ response: {+ moodOverall: 'positive',+ moodScore: { positive: 0.9, neutral: 0.05, negative: 0.05 },+ moodPerSentence: [{ text: 'I love this.', mood: 'positive' }],+ },+ },+ { action: pictureObjectRecognitionAction, props: { imageUrl: 'https://example.com/a.jpg' }, response: { recognizedLabels: ['iguana'] } },+ { action: pictureTextRecognitionAction, props: { imageUrl: 'https://example.com/a.jpg' }, response: { recognizedTexts: ['Hello'] } },+ { action: translateTextAction, props: { text: 'Good morning', resultLang: 'de' }, response: { translation: 'Guten Morgen' } },];beforeEach(() => {sendRequest.mockReset();});-describe('business and text output schemas', () => {+describe('business, text and AI output schemas', () => {it.each(CASES.map((testCase) => [testCase.action.name, testCase]))('%s schema matches its run() output', async (_, testCase) => {sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: testCase.response });diff --git a/packages/pieces/community/0codekit/test/output-schemas-code-url.test.ts b/packages/pieces/community/0codekit/test/output-schemas-code-url.test.tsnew file mode 100644index 00000000000..df2692aef81--- /dev/null+++ b/packages/pieces/community/0codekit/test/output-schemas-code-url.test.ts@@ -0,0 +1,211 @@+import { OutputSchema } from '@activepieces/pieces-framework';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { runJavascriptCodeAction } from '../src/lib/actions/code/run-javascript-code';+import { runPythonCodeAction } from '../src/lib/actions/code/run-python-code';+import { cryptoDecryptAction } from '../src/lib/actions/crypto/crypto-decrypt';+import { cryptoEncryptAction } from '../src/lib/actions/crypto/crypto-encrypt';+import { cryptoHashAction } from '../src/lib/actions/crypto/crypto-hash';+import { createASchedulerAction } from '../src/lib/actions/scheduler/create-a-scheduler';+import { deleteASchedulerAction } from '../src/lib/actions/scheduler/delete-a-scheduler';+import { listSchedulersAction } from '../src/lib/actions/scheduler/list-schedulers';+import { advancedSwitchWithUrlAction } from '../src/lib/actions/url/advanced-switch-with-url';+import { createCustomShortenedUrlAction } from '../src/lib/actions/url/create-custom-shortened-url';+import { createShortenedUrlAction } from '../src/lib/actions/url/create-shortened-url';+import { deleteShortenedUrlAction } from '../src/lib/actions/url/delete-shortened-url';+import { getAShortenedUrlAction } from '../src/lib/actions/url/get-a-shortened-url';+import { listShortenedUrlsAction } from '../src/lib/actions/url/list-shortened-urls';+import { updateShortenedUrlAction } from '../src/lib/actions/url/update-shortened-url';+import { urlExpanderAction } from '../src/lib/actions/url/url-expander';+import { utmBuildAction } from '../src/lib/actions/url/utm-build';+import { utmParseAction } from '../src/lib/actions/url/utm-parse';+import { runAction, TestAction } from './helpers';++const sendRequest = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: {+ sendRequest: (...args: unknown[]) => sendRequest(...args),+ },+ };+});++const SHORT_URL = { identifier: 'a1', createdAt: '2026-09-27T20:09:41.222Z', destination: 'https://a.com' };+const TASK = { taskId: 't1', webhook: 'https://hook.test', nextExecution: '2030-01-01T00:00:00.000Z', data: '{}' };++const cases: SchemaCase[] = [+ {+ name: 'Run Javascript Code',+ action: runJavascriptCodeAction,+ body: { total: 3 },+ props: { code: 'return { total: 3 };' },+ },+ {+ name: 'Run Python Code',+ action: runPythonCodeAction,+ body: { result: { sum: 5 } },+ props: { code: 'result = {"sum": 5}' },+ },+ {+ name: 'Crypto Encrypt',+ action: cryptoEncryptAction,+ body: { encryptedText: 'U2FsdGVk' },+ props: { cryptoType: 'AES', message: 'hi', secretKey: 'k' },+ },+ {+ name: 'Crypto Decrypt',+ action: cryptoDecryptAction,+ body: { decryptedText: 'hi' },+ props: { cryptoType: 'AES', ciphertext: 'U2FsdGVk', secretKey: 'k' },+ },+ {+ name: 'Crypto Hash',+ action: cryptoHashAction,+ body: { hashedText: 'abc' },+ props: { hashType: 'SHA256', message: 'hi' },+ },+ {+ name: 'Create a Scheduler',+ action: createASchedulerAction,+ body: { taskId: 't1', nextExecution: '2030-01-01T00:00:00.000Z' },+ props: { sendToWebhook: 'https://hook.test', intervalType: '3', schedule: '0 9 * * *' },+ },+ {+ name: 'List Schedulers',+ action: listSchedulersAction,+ body: { tasks: [TASK] },+ props: {},+ list: 'schedulers',+ },+ {+ name: 'Delete a Scheduler',+ action: deleteASchedulerAction,+ body: { message: 'Task deleted.' },+ props: { taskId: 't1' },+ },+ {+ name: 'Create Shortened Url',+ action: createShortenedUrlAction,+ body: { shortenedUrl: 'https://lyl.ai/a1', identifier: 'a1' },+ props: { destination: 'https://a.com' },+ },+ {+ name: 'Create Custom Shortened Url',+ action: createCustomShortenedUrlAction,+ body: { shortenedUrl: 'https://lyl.ai/summer', identifier: 'summer' },+ props: { destination: 'https://a.com', custom: 'summer' },+ },+ {+ name: 'Get a Shortened Url',+ action: getAShortenedUrlAction,+ body: { destination: 'https://a.com' },+ props: { identifier: 'a1' },+ },+ {+ name: 'Update Shortened Url',+ action: updateShortenedUrlAction,+ body: { newDestination: 'https://b.com', identifier: 'a1' },+ props: { identifier: 'a1', destination: 'https://b.com' },+ },+ {+ name: 'List Shortened Urls',+ action: listShortenedUrlsAction,+ body: { shortenedUrls: [SHORT_URL] },+ props: {},+ list: 'shortened_urls',+ },+ {+ name: 'Delete Shortened Url',+ action: deleteShortenedUrlAction,+ body: { message: 'Successfully deleted shortened URL with id a1.' },+ props: { identifier: 'a1' },+ },+ {+ name: 'URL Expander',+ action: urlExpanderAction,+ body: { unshortenedUrl: 'https://example.com/long/page' },+ props: { url: 'https://lyl.ai/a1' },+ },+ {+ name: 'UTM Build',+ action: utmBuildAction,+ body: { url: 'https://example.com/?utm_source=news' },+ props: { url: 'https://example.com', utmSource: 'news' },+ },+ {+ name: 'UTM Parse',+ action: utmParseAction,+ body: { utm_source: 'news', utm_medium: 'email' },+ props: { url: 'https://example.com/?utm_source=news&utm_medium=email' },+ },+ {+ name: 'Advanced Switch with URL',+ action: advancedSwitchWithUrlAction,+ body: { found: ['Germany', 'France'] },+ props: { jsonUrl: 'https://example.com/map.json', keys: ['de', 'fr'] },+ },+];++beforeEach(() => {+ sendRequest.mockReset();+});++describe('code, crypto, scheduler and url output schemas', () => {+ it.each(cases)('$name output schema matches the run() output keys', async ({ action, body, props, list }) => {+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body });+ const result = await runAction({ action, propsValue: props });+ const schema = action.outputSchema;+ expect(schema).toBeDefined();+ expect(fieldKeys(schema?.fields)).toEqual(objectKeys(result));+ if (list !== undefined) {+ const listField = schema?.fields.find((field) => field.key === list);+ expect(listField?.labelKey).toBeDefined();+ expect(fieldKeys(listField?.listItems)).toEqual(objectKeys(firstItem({ result, key: list })));+ }+ });++ it('every schema field value path is the key itself', () => {+ const paths = cases.flatMap(({ action }) => action.outputSchema?.fields ?? []).filter((field) => field.value !== undefined);+ expect(paths).toEqual([]);+ });++ it.each([+ ['Run Javascript Code', runJavascriptCodeAction],+ ['Run Python Code', runPythonCodeAction],+ ])('%s output schema has a single top-level result field', (_name, action) => {+ expect(fieldKeys(action.outputSchema?.fields)).toEqual(['result']);+ });+});++function fieldKeys(fields: OutputSchema['fields'] | undefined): string[] {+ return (fields ?? []).map((field) => field.key).sort();+}++function objectKeys(value: unknown): string[] {+ if (value === null || typeof value !== 'object') {+ return [];+ }+ return Object.keys(value).sort();+}++function firstItem({ result, key }: { result: unknown; key: string }): unknown {+ if (result === null || typeof result !== 'object' || !(key in result)) {+ return undefined;+ }+ const items: unknown = Reflect.get(result, key);+ return Array.isArray(items) ? items[0] : undefined;+}++type SchemaCase = {+ name: string;+ action: SchemaAction;+ body: unknown;+ props: Record<string, unknown>;+ list?: string;+};++type SchemaAction = TestAction & {+ outputSchema?: OutputSchema;+};diff --git a/packages/pieces/community/0codekit/test/output-schemas-files-storage.test.ts b/packages/pieces/community/0codekit/test/output-schemas-files-storage.test.tsnew file mode 100644index 00000000000..0094e5b37cd--- /dev/null+++ b/packages/pieces/community/0codekit/test/output-schemas-files-storage.test.ts@@ -0,0 +1,189 @@+import { ApFile, OutputSchema } from '@activepieces/pieces-framework';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { decodeQrCodeAction } from '../src/lib/actions/image/decode-qr-code';+import { generateQrCodeAction } from '../src/lib/actions/image/generate-qr-code';+import { imageExifAction } from '../src/lib/actions/image/image-exif';+import { createPdfFromHtmlAction } from '../src/lib/actions/pdf/create-pdf-from-html';+import { createPdfFromUrlAction } from '../src/lib/actions/pdf/create-pdf-from-url';+import { getPdfPageCountAction } from '../src/lib/actions/pdf/get-pdf-page-count';+import { mergePdfsAction } from '../src/lib/actions/pdf/merge-pdfs';+import { splitPdfAction } from '../src/lib/actions/pdf/split-pdf';+import { addAGlobalVariableAction } from '../src/lib/actions/storage/add-a-global-variable';+import { addAPermFileAction } from '../src/lib/actions/storage/add-a-perm-file';+import { deleteAGlobalVariableAction } from '../src/lib/actions/storage/delete-a-global-variable';+import { deleteAPermFileAction } from '../src/lib/actions/storage/delete-a-perm-file';+import { getAGlobalVariableAction } from '../src/lib/actions/storage/get-a-global-variable';+import { getAPermFileAction } from '../src/lib/actions/storage/get-a-perm-file';+import { listGlobalVariablesAction } from '../src/lib/actions/storage/list-global-variables';+import { listPermFilesAction } from '../src/lib/actions/storage/list-perm-files';+import { addTemporaryFileAction } from '../src/lib/actions/temp-file/add-temporary-file';+import { runAction, TestAction } from './helpers';++const sendRequest = vi.fn();+const write = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: {+ sendRequest: (...args: unknown[]) => sendRequest(...args),+ },+ };+});++const PDF = new ApFile('in.pdf', Buffer.from('%PDF-in'), 'pdf');+const IMAGE = new ApFile('photo.jpg', Buffer.from('jpeg-bytes'), 'jpg');+const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);++function respond(body: unknown) {+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body });+}++function binary(data: Buffer | string) {+ const buffer = typeof data === 'string' ? Buffer.from(data) : data;+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);+}++function paths(fields: OutputSchema['fields']): string[] {+ return fields.map((field) => field.value ?? field.key).sort();+}++function keysOf(value: unknown): string[] {+ return isRecord(value) ? Object.keys(value).sort() : [];+}++function fieldAt({ schema, path }: { schema: OutputSchema | undefined; path: string }) {+ return (schema?.fields ?? []).find((field) => (field.value ?? field.key) === path);+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++beforeEach(() => {+ sendRequest.mockReset();+ write.mockReset();+ write.mockImplementation(async ({ fileName }: { fileName: string }) => `file://${fileName}`);+});++describe('files and storage output schemas', () => {+ const objectCases: [string, SchemaAction, () => void, Record<string, unknown>][] = [+ ['Get PDF page count', getPdfPageCountAction, () => respond({ pageCount: 3 }), { pdf: PDF }],+ ['Create PDF from HTML', createPdfFromHtmlAction, () => respond(binary('%PDF-html')), { html: '<p>hi</p>' }],+ ['Create PDF from URL', createPdfFromUrlAction, () => respond(binary('%PDF-url')), { url: 'https://example.com' }],+ [+ 'Merge PDFs',+ mergePdfsAction,+ () => respond(binary('%PDF-merged')),+ { pdfs: [{ file: PDF }, { file: PDF }] },+ ],+ ['Generate QR code', generateQrCodeAction, () => respond(binary(PNG)), { data: 'https://example.com' }],+ ['Decode QR code', decodeQrCodeAction, () => respond({ data: 'hello' }), { file: IMAGE }],+ [+ 'Image EXIF',+ imageExifAction,+ () => respond({ exifData: { image: { Make: 'Canon' }, gps: {} } }),+ { file: IMAGE },+ ],+ [+ 'Add temporary file',+ addTemporaryFileAction,+ () => respond({ url: 'https://tmp.example/a.pdf', fileName: 'a.pdf' }),+ { file: PDF },+ ],+ [+ 'Add global variable',+ addAGlobalVariableAction,+ () => respond({ variableName: 'k', variableValue: 'v' }),+ { variableName: 'k', variableValue: 'v' },+ ],+ [+ 'Get global variable',+ getAGlobalVariableAction,+ () => respond({ variableName: 'k', variableValue: 'v' }),+ { variableName: 'k' },+ ],+ [+ 'List global variables',+ listGlobalVariablesAction,+ () => respond({ variables: [{ variableName: 'k', variableValue: 'v' }] }),+ {},+ ],+ ['Delete global variable', deleteAGlobalVariableAction, () => respond({ message: 'ok' }), { variableName: 'k' }],+ [+ 'Add perm file',+ addAPermFileAction,+ () => respond({ fileId: 'f1', url: 'https://prod.0codekit.com/a.pdf' }),+ { fileUrl: 'https://example.com/a.pdf', uploadName: 'a.pdf' },+ ],+ [+ 'Get perm file',+ getAPermFileAction,+ () => {+ respond({ url: 'https://prod.0codekit.com/a.pdf' });+ respond(binary('%PDF-perm'));+ },+ { fileId: 'f1' },+ ],+ ['Delete perm file', deleteAPermFileAction, () => respond({ message: 'ok' }), { fileId: 'f1' }],+ [+ 'List perm files',+ listPermFilesAction,+ () =>+ respond({+ availableStorage: 1024,+ files: [{ fileId: 'f1', fileName: 'a.pdf', url: 'https://prod.0codekit.com/a.pdf', size: 12 }],+ }),+ {},+ ],+ ];++ it.each(objectCases)('%s schema matches the run() output keys', async (_name, action, mock, propsValue) => {+ mock();+ const output = await runAction({ action, propsValue, write });+ expect(action.outputSchema).toBeDefined();+ expect(paths(action.outputSchema?.fields ?? [])).toEqual(keysOf(output));+ });++ it('Get perm file with Link Only returns a subset of the schema keys', async () => {+ respond({ url: 'https://prod.0codekit.com/a.pdf' });+ const output = await runAction({ action: getAPermFileAction, propsValue: { fileId: 'f1', linkOnly: true }, write });+ const schemaPaths = paths(getAPermFileAction.outputSchema?.fields ?? []);+ expect(keysOf(output).every((key) => schemaPaths.includes(key))).toBe(true);+ });++ it('List global variables item fields match each variable', async () => {+ respond({ variables: [{ variableName: 'k', variableValue: 'v' }] });+ const output = await runAction({ action: listGlobalVariablesAction, propsValue: {}, write });+ const field = fieldAt({ schema: listGlobalVariablesAction.outputSchema, path: 'variables' });+ const first = isRecord(output) && Array.isArray(output['variables']) ? output['variables'][0] : undefined;+ expect(paths(field?.listItems ?? [])).toEqual(keysOf(first));+ });++ it('List perm files item fields match each file', async () => {+ respond({ availableStorage: 1, files: [{ fileId: 'f1', fileName: 'a.pdf', url: 'https://x', size: 1 }] });+ const output = await runAction({ action: listPermFilesAction, propsValue: {}, write });+ const field = fieldAt({ schema: listPermFilesAction.outputSchema, path: 'files' });+ const first = isRecord(output) && Array.isArray(output['files']) ? output['files'][0] : undefined;+ expect(paths(field?.listItems ?? [])).toEqual(keysOf(first));+ });++ it('Split PDF wraps the top-level array and its item fields match each part', async () => {+ respond({ pdfUrls: ['https://prod.0codekit.com/a.pdf'] });+ respond(binary('%PDF-a'));+ const output = await runAction({ action: splitPdfAction, propsValue: { pdf: PDF, mode: 'interval', interval: 1 }, write });+ const schema = splitPdfAction.outputSchema;+ expect(Array.isArray(output)).toBe(true);+ expect(schema?.itemLabel).toBeDefined();+ expect(schema?.fields).toHaveLength(1);+ const wrapper = schema?.fields[0];+ expect(wrapper?.value).toBe('');+ const first = Array.isArray(output) ? output[0] : undefined;+ expect(paths(wrapper?.listItems ?? [])).toEqual(keysOf(first));+ });+});++type SchemaAction = TestAction & {+ outputSchema?: OutputSchema;+};diff --git a/packages/pieces/community/0codekit/test/pdf.test.ts b/packages/pieces/community/0codekit/test/pdf.test.tsnew file mode 100644index 00000000000..a2c25f4156b--- /dev/null+++ b/packages/pieces/community/0codekit/test/pdf.test.ts@@ -0,0 +1,180 @@+import { ApFile } from '@activepieces/pieces-framework';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createPdfFromHtmlAction } from '../src/lib/actions/pdf/create-pdf-from-html';+import { createPdfFromUrlAction } from '../src/lib/actions/pdf/create-pdf-from-url';+import { getPdfPageCountAction } from '../src/lib/actions/pdf/get-pdf-page-count';+import { mergePdfsAction } from '../src/lib/actions/pdf/merge-pdfs';+import { splitPdfAction } from '../src/lib/actions/pdf/split-pdf';+import { runAction } from './helpers';++const sendRequest = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: {+ sendRequest: (...args: unknown[]) => sendRequest(...args),+ },+ };+});++const PDF = new ApFile('in.pdf', Buffer.from('%PDF-in'), 'pdf');+const PDF_B64 = Buffer.from('%PDF-in').toString('base64');+const write = vi.fn();++function respond(body: unknown) {+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body });+}++function binary(text: string) {+ const buffer = Buffer.from(text);+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);+}++function call(index: number) {+ return sendRequest.mock.calls[index][0];+}++beforeEach(() => {+ sendRequest.mockReset();+ write.mockReset();+ write.mockImplementation(async ({ fileName }: { fileName: string }) => `file://${fileName}`);+});++describe('pdf actions', () => {+ it('Gets PDF page count sends the file as base64', async () => {+ respond({ pageCount: 7 });++ await expect(runAction({ action: getPdfPageCountAction, propsValue: { pdf: PDF }, write })).resolves.toEqual({ page_count: 7 });+ expect(call(0).url).toBe('https://v2.1saas.co/pdf/count');+ expect(call(0).headers).toEqual({ auth: 'zck_test' });+ expect(call(0).body).toEqual({ buffer: PDF_B64 });+ });++ it('Creates a PDF from HTML requests binary and saves it', async () => {+ respond(binary('%PDF-html'));++ const result = await runAction({ action: createPdfFromHtmlAction, propsValue: {+ html: '<h1>Hi</h1>',+ fileName: 'invoice',+ format: 'Letter',+ landscape: true,+ margin: ' 1cm ',+ scale: 1.5,+ pageRanges: '',+ }, write });++ expect(call(0).url).toBe('https://v2.1saas.co/pdf/html');+ expect(call(0).responseType).toBe('arraybuffer');+ expect(call(0).body).toEqual({+ html: '<h1>Hi</h1>',+ getAsUrl: false,+ options: {+ format: 'Letter',+ landscape: true,+ printBackground: true,+ displayHeaderFooter: false,+ scale: 1.5,+ margin: { top: '1cm', bottom: '1cm', left: '1cm', right: '1cm' },+ },+ });+ expect(write).toHaveBeenCalledWith({ fileName: 'invoice.pdf', data: Buffer.from('%PDF-html') });+ expect(result).toEqual({ file: 'file://invoice.pdf', file_name: 'invoice.pdf', size_bytes: 9 });+ });++ it('Creates a PDF from HTML rejects a scale out of range', async () => {+ await expect(runAction({ action: createPdfFromHtmlAction, propsValue: { html: '<p/>', scale: 3 }, write })).rejects.toThrow(/Scale/);+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('Creates a PDF file from URL sends the url with default options', async () => {+ respond(binary('%PDF-url'));++ const result = await runAction({ action: createPdfFromUrlAction, propsValue: { url: ' https://example.com ' }, write });++ expect(call(0).url).toBe('https://v2.1saas.co/pdf/html');+ expect(call(0).body).toEqual({+ url: 'https://example.com',+ getAsUrl: false,+ options: { format: 'A4', landscape: false, printBackground: true, displayHeaderFooter: false },+ });+ expect(result).toMatchObject({ file_name: 'webpage.pdf' });+ });++ it('Creates a PDF file from URL rejects a bare domain', async () => {+ await expect(runAction({ action: createPdfFromUrlAction, propsValue: { url: 'example.com' }, write })).rejects.toThrow(/https/);+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('Merges multiple PDFs keeps order and optional pages', async () => {+ respond(binary('%PDF-merged'));++ const result = await runAction({ action: mergePdfsAction, propsValue: {+ pdfs: [{ file: PDF, pages: ' 1-2 ' }, { file: PDF, pages: '' }],+ }, write });++ expect(call(0).url).toBe('https://v2.1saas.co/pdf/merge');+ expect(call(0).body).toEqual({+ files: [{ buffer: PDF_B64, pages: '1-2' }, { buffer: PDF_B64 }],+ getAsUrl: false,+ });+ expect(result).toMatchObject({ file_name: 'merged.pdf', merged_count: 2 });+ });++ it('Merges multiple PDFs accepts files built by the engine\'s own framework copy', async () => {+ respond(binary('%PDF-merged'));+ const foreignFile = {+ filename: 'in.pdf',+ data: Buffer.from('%PDF-in'),+ extension: 'pdf',+ get base64() {+ return this.data.toString('base64');+ },+ };++ await runAction({ action: mergePdfsAction, propsValue: { pdfs: [{ file: foreignFile }, { file: foreignFile }] }, write });++ expect(call(0).body).toEqual({ files: [{ buffer: PDF_B64 }, { buffer: PDF_B64 }], getAsUrl: false });+ });++ it('Merges multiple PDFs needs at least two files', async () => {+ await expect(runAction({ action: mergePdfsAction, propsValue: { pdfs: [{ file: PDF }] }, write })).rejects.toThrow(/at least two/);+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('Splits a PDF by interval and downloads every part', async () => {+ respond({ pdfUrls: ['https://prod.0codekit.com/a.pdf', 'https://prod.0codekit.com/b.pdf'] });+ respond(binary('%PDF-a'));+ respond(binary('%PDF-b'));++ const result = await runAction({ action: splitPdfAction, propsValue: { pdf: PDF, mode: 'interval', interval: 2, fileName: 'chapter.pdf' }, write });++ expect(call(0).url).toBe('https://v2.1saas.co/pdf/split');+ expect(call(0).body).toEqual({ buffer: PDF_B64, interval: 2 });+ expect(call(1)).toMatchObject({ method: 'GET', url: 'https://prod.0codekit.com/a.pdf', responseType: 'arraybuffer' });+ expect(call(2).url).toBe('https://prod.0codekit.com/b.pdf');+ expect(result).toEqual([+ { file: 'file://chapter-1.pdf', file_name: 'chapter-1.pdf', size_bytes: 6 },+ { file: 'file://chapter-2.pdf', file_name: 'chapter-2.pdf', size_bytes: 6 },+ ]);+ });++ it('Splits a PDF by page ranges', async () => {+ respond({ pdfUrls: [] });++ await expect(runAction({ action: splitPdfAction, propsValue: { pdf: PDF, mode: 'pages', pageRanges: ['1-3', ' ', '4-^1'] }, write })).resolves.toEqual([]);+ expect(call(0).body).toEqual({ buffer: PDF_B64, pages: ['1-3', '4-^1'] });+ });++ it('Splits a PDF rejects an invalid interval', async () => {+ await expect(runAction({ action: splitPdfAction, propsValue: { pdf: PDF, mode: 'interval', interval: 0 }, write })).rejects.toThrow(/Pages per File/);+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('surfaces 0CodeKit errors', async () => {+ sendRequest.mockRejectedValueOnce(new Error('boom'));++ await expect(runAction({ action: getPdfPageCountAction, propsValue: { pdf: PDF }, write })).rejects.toThrow('boom');+ });+});diff --git a/packages/pieces/community/0codekit/test/storage.test.ts b/packages/pieces/community/0codekit/test/storage.test.tsnew file mode 100644index 00000000000..d012c32e1be--- /dev/null+++ b/packages/pieces/community/0codekit/test/storage.test.ts@@ -0,0 +1,219 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { addAGlobalVariableAction } from '../src/lib/actions/storage/add-a-global-variable';+import { addAPermFileAction } from '../src/lib/actions/storage/add-a-perm-file';+import { deleteAGlobalVariableAction } from '../src/lib/actions/storage/delete-a-global-variable';+import { deleteAPermFileAction } from '../src/lib/actions/storage/delete-a-perm-file';+import { getAGlobalVariableAction } from '../src/lib/actions/storage/get-a-global-variable';+import { getAPermFileAction } from '../src/lib/actions/storage/get-a-perm-file';+import { listGlobalVariablesAction } from '../src/lib/actions/storage/list-global-variables';+import { listPermFilesAction } from '../src/lib/actions/storage/list-perm-files';+import { zeroCodeKitStorage } from '../src/lib/common/storage';+import { loadDropdownOptions, runAction, TEST_AUTH } from './helpers';++const sendRequest = vi.fn();+const write = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: {+ sendRequest: (...args: unknown[]) => sendRequest(...args),+ },+ };+});++function respond(body: unknown) {+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body });+}++function sent(index = 0) {+ return sendRequest.mock.calls[index][0];+}++beforeEach(() => {+ sendRequest.mockReset();+ write.mockReset();+ write.mockResolvedValue('file://saved');+});++describe('storage metadata', () => {+ const actions: [string, MetadataAction, string, boolean][] = [+ ['Add a Global Variable', addAGlobalVariableAction, 'WRITE', false],+ ['Delete a Global Variable', deleteAGlobalVariableAction, 'DESTRUCTIVE', false],+ ['Get a Global Variable', getAGlobalVariableAction, 'READ', true],+ ['List Global Variables', listGlobalVariablesAction, 'SEARCH', true],+ ['Add a Perm File', addAPermFileAction, 'WRITE', false],+ ['Delete a Perm File', deleteAPermFileAction, 'DESTRUCTIVE', false],+ ['Get a Perm File', getAPermFileAction, 'READ', true],+ ['List Perm Files', listPermFilesAction, 'SEARCH', true],+ ];++ it.each(actions)('%s has the expected metadata', (displayName, action, classification, idempotent) => {+ expect(action.displayName).toBe(displayName);+ expect(action.classification).toBe(classification);+ expect(action.audience).toBe('both');+ expect(action.aiMetadata?.idempotent).toBe(idempotent);+ expect(action.aiMetadata?.description?.length).toBeGreaterThan(20);+ });+});++describe('global variables', () => {+ it('Add sends name and value with the auth header', async () => {+ respond({ variableName: 'myVar', variableValue: 'hello' });+ const result = await runAction({ action: addAGlobalVariableAction, propsValue: { variableName: ' myVar ', variableValue: 'hello' }, write });+ expect(sent().url).toBe('https://v2.1saas.co/storage/globalvariables/add');+ expect(sent().headers).toEqual({ auth: 'zck_test' });+ expect(sent().body).toEqual({ variableName: 'myVar', variableValue: 'hello' });+ expect(result).toEqual({ variable_name: 'myVar', variable_value: 'hello' });+ });++ it('Add omits an empty name so 0CodeKit generates one', async () => {+ respond({ variableName: 'auto123', variableValue: 'x' });+ await runAction({ action: addAGlobalVariableAction, propsValue: { variableName: '', variableValue: 'x' }, write });+ expect(sent().body).toEqual({ variableValue: 'x' });+ });++ it('Delete sends the name as variableId', async () => {+ respond({ message: 'Successfully deleted global variable with id myVar.' });+ const result = await runAction({ action: deleteAGlobalVariableAction, propsValue: { variableName: 'myVar' }, write });+ expect(sent().url).toBe('https://v2.1saas.co/storage/globalvariables/del');+ expect(sent().body).toEqual({ variableId: 'myVar' });+ expect(result).toEqual({+ deleted: true,+ variable_name: 'myVar',+ message: 'Successfully deleted global variable with id myVar.',+ });+ });++ it('Get returns a flat variable', async () => {+ respond({ variableName: 'myVar', variableValue: 'hello' });+ const result = await runAction({ action: getAGlobalVariableAction, propsValue: { variableName: 'myVar' }, write });+ expect(sent().url).toBe('https://v2.1saas.co/storage/globalvariables/get');+ expect(sent().body).toEqual({ variableName: 'myVar' });+ expect(result).toEqual({ variable_name: 'myVar', variable_value: 'hello' });+ });++ it('List returns variables with a count', async () => {+ respond({ variables: [{ variableName: 'a', variableValue: '1' }, { variableName: 'b', variableValue: '2' }] });+ const result = await runAction({ action: listGlobalVariablesAction, propsValue: {}, write });+ expect(sent().url).toBe('https://v2.1saas.co/storage/globalvariables/list');+ expect(result).toEqual({+ count: 2,+ variables: [+ { variable_name: 'a', variable_value: '1' },+ { variable_name: 'b', variable_value: '2' },+ ],+ });+ });++ it('surfaces 0CodeKit error messages', async () => {+ sendRequest.mockRejectedValueOnce(new Error('boom'));+ await expect(runAction({ action: getAGlobalVariableAction, propsValue: { variableName: 'missing' }, write })).rejects.toThrow('boom');+ });+});++describe('perm files', () => {+ it('Add uploads a file as base64 with its name', async () => {+ respond({ fileId: 'f1', url: 'https://prod.0codekit.com/f1/report.pdf' });+ const result = await runAction({ action: addAPermFileAction, propsValue: {+ file: { filename: 'report.pdf', extension: 'pdf', data: Buffer.from('pdf'), base64: 'cGRm' },+ }, write });+ expect(sent().url).toBe('https://v2.1saas.co/storage/perm/add');+ expect(sent().body).toEqual({ fileBuffer: 'cGRm', uploadName: 'report.pdf' });+ expect(result).toEqual({ file_id: 'f1', url: 'https://prod.0codekit.com/f1/report.pdf', file_name: 'report.pdf' });+ });++ it('Add uploads from a URL with a custom name', async () => {+ respond({ fileId: 'f2', url: 'https://prod.0codekit.com/f2/a.png' });+ await runAction({ action: addAPermFileAction, propsValue: { fileUrl: ' https://example.com/a.png ', uploadName: 'a.png' }, write });+ expect(sent().body).toEqual({ fileUrl: 'https://example.com/a.png', uploadName: 'a.png' });+ });++ it('Add rejects when neither file nor URL is given', async () => {+ await expect(runAction({ action: addAPermFileAction, propsValue: { fileUrl: ' ' }, write })).rejects.toThrow(/File or a File URL/);+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('Delete sends the file id', async () => {+ respond({ message: 'deleted' });+ const result = await runAction({ action: deleteAPermFileAction, propsValue: { fileId: 'f1' }, write });+ expect(sent().url).toBe('https://v2.1saas.co/storage/perm/del');+ expect(sent().body).toEqual({ fileId: 'f1' });+ expect(result).toEqual({ deleted: true, file_id: 'f1', message: 'deleted' });+ });++ it('Get returns only the link when Link Only is on', async () => {+ respond({ url: 'https://prod.0codekit.com/f1/report.pdf' });+ const result = await runAction({ action: getAPermFileAction, propsValue: { fileId: 'f1', linkOnly: true }, write });+ expect(sent().url).toBe('https://v2.1saas.co/storage/perm/get');+ expect(sent().body).toEqual({ fileId: 'f1', getAsUrl: true });+ expect(sendRequest).toHaveBeenCalledTimes(1);+ expect(result).toEqual({ file_id: 'f1', url: 'https://prod.0codekit.com/f1/report.pdf' });+ });++ it('Get downloads the file and stores it without base64 in the output', async () => {+ respond({ url: 'https://prod.0codekit.com/f1/my%20report.pdf' });+ respond(new TextEncoder().encode('pdf-bytes').buffer);+ const result = await runAction({ action: getAPermFileAction, propsValue: { fileId: 'f1' }, write });+ expect(sent(1).url).toBe('https://prod.0codekit.com/f1/my%20report.pdf');+ expect(sent(1).responseType).toBe('arraybuffer');+ expect(write).toHaveBeenCalledWith({ fileName: 'my report.pdf', data: Buffer.from('pdf-bytes') });+ expect(result).toEqual({+ file_id: 'f1',+ url: 'https://prod.0codekit.com/f1/my%20report.pdf',+ file: 'file://saved',+ file_name: 'my report.pdf',+ size_bytes: 9,+ });+ });++ it('Get fails clearly when no link comes back', async () => {+ respond({});+ await expect(runAction({ action: getAPermFileAction, propsValue: { fileId: 'f1' }, write })).rejects.toThrow(/download link/);+ });++ it('List returns flat files, count and remaining storage', async () => {+ respond({+ availableStorage: 1000,+ files: [{ fileId: 'f1', fileName: 'report.pdf', url: 'https://prod.0codekit.com/f1', size: 12 }],+ });+ const result = await runAction({ action: listPermFilesAction, propsValue: {}, write });+ expect(sent().url).toBe('https://v2.1saas.co/storage/perm/list');+ expect(result).toEqual({+ count: 1,+ available_storage_kib: 1000,+ files: [{ file_id: 'f1', file_name: 'report.pdf', url: 'https://prod.0codekit.com/f1', size_kib: 12 }],+ });+ });+});++describe('storage dropdowns', () => {+ it('variable dropdown lists names from the list endpoint', async () => {+ respond({ variables: [{ variableName: 'a', variableValue: '1' }] });+ const prop = zeroCodeKitStorage.variableName({ description: 'd' });+ const options = await loadDropdownOptions({ dropdown: prop, auth: TEST_AUTH });+ expect(options).toEqual({ disabled: false, options: [{ label: 'a', value: 'a' }] });+ });++ it('perm file dropdown uses file ids as values', async () => {+ respond({ availableStorage: 1, files: [{ fileId: 'f1', fileName: 'r.pdf', url: 'u', size: 3 }] });+ const prop = zeroCodeKitStorage.permFileId({ description: 'd' });+ const options = await loadDropdownOptions({ dropdown: prop, auth: TEST_AUTH });+ expect(options).toEqual({ disabled: false, options: [{ label: 'r.pdf (3 KiB)', value: 'f1' }] });+ });++ it('dropdowns ask for a connection first', async () => {+ const prop = zeroCodeKitStorage.permFileId({ description: 'd' });+ const options = await loadDropdownOptions({ dropdown: prop, auth: undefined });+ expect(options).toMatchObject({ disabled: true });+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++type MetadataAction = {+ displayName: string;+ classification?: string;+ audience?: string;+ aiMetadata?: { description?: string; idempotent?: boolean };+};diff --git a/packages/pieces/community/0codekit/test/url.test.ts b/packages/pieces/community/0codekit/test/url.test.tsnew file mode 100644index 00000000000..89c0422058b--- /dev/null+++ b/packages/pieces/community/0codekit/test/url.test.ts@@ -0,0 +1,214 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { advancedSwitchWithUrlAction } from '../src/lib/actions/url/advanced-switch-with-url';+import { createCustomShortenedUrlAction } from '../src/lib/actions/url/create-custom-shortened-url';+import { createShortenedUrlAction } from '../src/lib/actions/url/create-shortened-url';+import { deleteShortenedUrlAction } from '../src/lib/actions/url/delete-shortened-url';+import { getAShortenedUrlAction } from '../src/lib/actions/url/get-a-shortened-url';+import { listShortenedUrlsAction } from '../src/lib/actions/url/list-shortened-urls';+import { updateShortenedUrlAction } from '../src/lib/actions/url/update-shortened-url';+import { urlExpanderAction } from '../src/lib/actions/url/url-expander';+import { utmBuildAction } from '../src/lib/actions/url/utm-build';+import { utmParseAction } from '../src/lib/actions/url/utm-parse';+import { zeroCodeKitUrl } from '../src/lib/common/url';+import { loadDropdownOptions, runAction, TEST_AUTH } from './helpers';++const sendRequest = vi.fn();++vi.mock('@activepieces/pieces-common', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();+ return {+ ...actual,+ httpClient: {+ sendRequest: (...args: unknown[]) => sendRequest(...args),+ },+ };+});++function respond(body: unknown) {+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body });+}++function sent(index = 0) {+ return sendRequest.mock.calls[index][0];+}++beforeEach(() => {+ sendRequest.mockReset();+});++describe('url metadata', () => {+ const actions: [string, MetadataAction, string, boolean][] = [+ ['Create Shortened Url', createShortenedUrlAction, 'WRITE', false],+ ['Create Custom Shortened Url', createCustomShortenedUrlAction, 'WRITE', false],+ ['Delete Shortened Url', deleteShortenedUrlAction, 'DESTRUCTIVE', false],+ ['Get a Shortened Url', getAShortenedUrlAction, 'READ', true],+ ['List Shortened Urls', listShortenedUrlsAction, 'SEARCH', true],+ ['Update Shortened Url', updateShortenedUrlAction, 'WRITE', true],+ ['URL Expander', urlExpanderAction, 'READ', true],+ ['UTM Build', utmBuildAction, 'READ', true],+ ['UTM Parse', utmParseAction, 'READ', true],+ ['Advanced Switch with URL', advancedSwitchWithUrlAction, 'READ', true],+ ];++ it.each(actions)('%s has the expected metadata', (displayName, action, classification, idempotent) => {+ expect(action.displayName).toBe(displayName);+ expect(action.classification).toBe(classification);+ expect(action.audience).toBe('both');+ expect(action.aiMetadata?.idempotent).toBe(idempotent);+ expect(action.aiMetadata?.description?.length).toBeGreaterThan(20);+ });+});++describe('shortened urls', () => {+ it('Create sends only the destination with the auth header', async () => {+ respond({ shortenedUrl: 'https://lyl.ai/to4w5vyb', identifier: 'to4w5vyb' });+ const result = await runAction({ action: createShortenedUrlAction, propsValue: { destination: ' https://0codekit.com ' } });+ expect(sent().url).toBe('https://v2.1saas.co/generate/shortenedurl/add');+ expect(sent().headers).toEqual({ auth: 'zck_test' });+ expect(sent().body).toEqual({ destination: 'https://0codekit.com' });+ expect(result).toEqual({+ identifier: 'to4w5vyb',+ short_url: 'https://lyl.ai/to4w5vyb',+ destination: 'https://0codekit.com',+ });+ });++ it('Create Custom sends the custom ending', async () => {+ respond({ shortenedUrl: 'https://lyl.ai/summer', identifier: 'summer' });+ const result = await runAction({ action: createCustomShortenedUrlAction, propsValue: { destination: 'https://0codekit.com', custom: ' summer ' } });+ expect(sent().url).toBe('https://v2.1saas.co/generate/shortenedurl/add');+ expect(sent().body).toEqual({ destination: 'https://0codekit.com', custom: 'summer' });+ expect(result).toEqual({ identifier: 'summer', short_url: 'https://lyl.ai/summer', destination: 'https://0codekit.com' });+ });++ it('Create Custom rejects a blank ending', async () => {+ await expect(runAction({ action: createCustomShortenedUrlAction, propsValue: { destination: 'https://a.com', custom: ' ' } })).rejects.toThrow(/custom ending/);+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('Delete sends the identifier', async () => {+ respond({ message: 'Successfully deleted shortened URL with id to4w5vyb.' });+ const result = await runAction({ action: deleteShortenedUrlAction, propsValue: { identifier: 'to4w5vyb' } });+ expect(sent().url).toBe('https://v2.1saas.co/generate/shortenedurl/del');+ expect(sent().body).toEqual({ identifier: 'to4w5vyb' });+ expect(result).toEqual({+ deleted: true,+ identifier: 'to4w5vyb',+ short_url: 'https://lyl.ai/to4w5vyb',+ message: 'Successfully deleted shortened URL with id to4w5vyb.',+ });+ });++ it('Get returns the destination', async () => {+ respond({ destination: 'https://0codekit.com' });+ const result = await runAction({ action: getAShortenedUrlAction, propsValue: { identifier: 'to4w5vyb' } });+ expect(sent().url).toBe('https://v2.1saas.co/generate/shortenedurl/get');+ expect(sent().body).toEqual({ identifier: 'to4w5vyb' });+ expect(result).toEqual({ identifier: 'to4w5vyb', short_url: 'https://lyl.ai/to4w5vyb', destination: 'https://0codekit.com' });+ });++ it('List returns flat links with a count', async () => {+ respond({ shortenedUrls: [{ identifier: 'a1', createdAt: '2026-01-01T00:00:00.000Z', destination: 'https://a.com' }] });+ const result = await runAction({ action: listShortenedUrlsAction, propsValue: {} });+ expect(sent().url).toBe('https://v2.1saas.co/generate/shortenedurl/list');+ expect(result).toEqual({+ count: 1,+ shortened_urls: [+ { identifier: 'a1', short_url: 'https://lyl.ai/a1', destination: 'https://a.com', created_at: '2026-01-01T00:00:00.000Z' },+ ],+ });+ });++ it('Update sends identifier and new destination', async () => {+ respond({ newDestination: 'https://example.com', identifier: 'a1' });+ const result = await runAction({ action: updateShortenedUrlAction, propsValue: { identifier: 'a1', destination: ' https://example.com ' } });+ expect(sent().url).toBe('https://v2.1saas.co/generate/shortenedurl/put');+ expect(sent().body).toEqual({ identifier: 'a1', destination: 'https://example.com' });+ expect(result).toEqual({ identifier: 'a1', short_url: 'https://lyl.ai/a1', destination: 'https://example.com' });+ });++ it('surfaces 0CodeKit error messages', async () => {+ sendRequest.mockRejectedValueOnce(new Error('boom'));+ await expect(runAction({ action: getAShortenedUrlAction, propsValue: { identifier: 'missing' } })).rejects.toThrow('boom');+ });+});++describe('url tools', () => {+ it('URL Expander returns the expanded URL', async () => {+ respond({ unshortenedUrl: 'https://example.com/long/page' });+ const result = await runAction({ action: urlExpanderAction, propsValue: { url: ' https://bit.ly/abc ' } });+ expect(sent().url).toBe('https://v2.1saas.co/operator/urlexpander');+ expect(sent().body).toEqual({ url: 'https://bit.ly/abc' });+ expect(result).toEqual({ short_url: 'https://bit.ly/abc', expanded_url: 'https://example.com/long/page' });+ });++ it('UTM Build nests only filled parameters under utm', async () => {+ respond({ url: 'https://example.com/?utm_source=news&utm_campaign=spring' });+ const result = await runAction({ action: utmBuildAction, propsValue: {+ url: 'https://example.com/',+ utmSource: ' news ',+ utmMedium: '',+ utmCampaign: 'spring',+ } });+ expect(sent().url).toBe('https://v2.1saas.co/operator/utm/build');+ expect(sent().body).toEqual({ url: 'https://example.com/', utm: { utm_source: 'news', utm_campaign: 'spring' } });+ expect(result).toEqual({ url: 'https://example.com/?utm_source=news&utm_campaign=spring' });+ });++ it('UTM Parse returns null for missing parameters', async () => {+ respond({ utm_source: 'news', utm_medium: 'email' });+ const result = await runAction({ action: utmParseAction, propsValue: { url: 'https://example.com/?utm_source=news&utm_medium=email' } });+ expect(sent().url).toBe('https://v2.1saas.co/operator/utm/parse');+ expect(result).toEqual({ utm_source: 'news', utm_medium: 'email', utm_campaign: null, utm_content: null, utm_term: null });+ });++ it('Advanced Switch with URL sends external JSON URL and keys', async () => {+ respond({ found: ['Germany', 'France'] });+ const result = await runAction({ action: advancedSwitchWithUrlAction, propsValue: { jsonUrl: ' https://example.com/map.json ', keys: ['DE', ' FR ', ''] } });+ expect(sent().url).toBe('https://v2.1saas.co/operator/advancedswitch');+ expect(sent().body).toEqual({ external: true, json: 'https://example.com/map.json', key: ['DE', 'FR'] });+ expect(result).toEqual({ found: true, count: 2, first_value: 'Germany', values: ['Germany', 'France'] });+ });++ it('Advanced Switch with URL wraps a single value', async () => {+ respond({ found: 'Germany' });+ const result = await runAction({ action: advancedSwitchWithUrlAction, propsValue: { jsonUrl: 'https://example.com/map.json', keys: ['DE'] } });+ expect(result).toEqual({ found: true, count: 1, first_value: 'Germany', values: ['Germany'] });+ });++ it('Advanced Switch with URL rejects empty keys', async () => {+ await expect(runAction({ action: advancedSwitchWithUrlAction, propsValue: { jsonUrl: 'https://a.com/x.json', keys: [' '] } })).rejects.toThrow(/at least one key/);+ expect(sendRequest).not.toHaveBeenCalled();+ });+});++describe('shortened url dropdown', () => {+ it('labels options with short link and destination', async () => {+ respond({ shortenedUrls: [{ identifier: 'a1', createdAt: 'x', destination: 'https://a.com' }] });+ const prop = zeroCodeKitUrl.shortenedUrlIdentifier({ description: 'd' });+ const options = await loadDropdownOptions({ dropdown: prop, auth: TEST_AUTH });+ expect(sent().url).toBe('https://v2.1saas.co/generate/shortenedurl/list');+ expect(options).toEqual({ disabled: false, options: [{ label: 'https://lyl.ai/a1 → https://a.com', value: 'a1' }] });+ });++ it('asks for a connection first', async () => {+ const prop = zeroCodeKitUrl.shortenedUrlIdentifier({ description: 'd' });+ const options = await loadDropdownOptions({ dropdown: prop, auth: undefined });+ expect(options).toMatchObject({ disabled: true });+ expect(sendRequest).not.toHaveBeenCalled();+ });++ it('shows an empty-state placeholder', async () => {+ respond({ shortenedUrls: [] });+ const prop = zeroCodeKitUrl.shortenedUrlIdentifier({ description: 'd' });+ const options = await loadDropdownOptions({ dropdown: prop, auth: TEST_AUTH });+ expect(options).toMatchObject({ disabled: true, placeholder: 'No shortened URLs found. Create one first.' });+ });+});++type MetadataAction = {+ displayName: string;+ classification?: string;+ audience?: string;+ aiMetadata?: { description?: string; idempotent?: boolean };+};