Add Activepieces integration for workflow automation
- Add Activepieces fork with SmoothSchedule custom piece - Create integrations app with Activepieces service layer - Add embed token endpoint for iframe integration - Create Automations page with embedded workflow builder - Add sidebar visibility fix for embed mode - Add list inactive customers endpoint to Public API - Include SmoothSchedule triggers: event created/updated/cancelled - Include SmoothSchedule actions: create/update/cancel events, list resources/services/customers 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"extends": [
|
||||
"../../../../.eslintrc.base.json"
|
||||
],
|
||||
"ignorePatterns": [
|
||||
"!**/*"
|
||||
],
|
||||
"overrides": [
|
||||
{
|
||||
"files": [
|
||||
"*.ts",
|
||||
"*.tsx",
|
||||
"*.js",
|
||||
"*.jsx"
|
||||
],
|
||||
"rules": {}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"*.ts",
|
||||
"*.tsx"
|
||||
],
|
||||
"rules": {}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"*.js",
|
||||
"*.jsx"
|
||||
],
|
||||
"rules": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# pieces-image-router
|
||||
|
||||
This library was generated with [Nx](https://nx.dev).
|
||||
|
||||
## Building
|
||||
|
||||
Run `nx build pieces-image-router` to build the library.
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "@activepieces/piece-image-router",
|
||||
"version": "0.0.1",
|
||||
"type": "commonjs",
|
||||
"main": "./src/index.js",
|
||||
"types": "./src/index.d.ts",
|
||||
"dependencies": {
|
||||
"tslib": "^2.3.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"name": "pieces-image-router",
|
||||
"$schema": "../../../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "packages/pieces/community/image-router/src",
|
||||
"projectType": "library",
|
||||
"release": {
|
||||
"version": {
|
||||
"manifestRootsToUpdate": [
|
||||
"dist/{projectRoot}"
|
||||
],
|
||||
"currentVersionResolver": "git-tag",
|
||||
"fallbackCurrentVersionResolver": "disk"
|
||||
}
|
||||
},
|
||||
"tags": [],
|
||||
"targets": {
|
||||
"build": {
|
||||
"executor": "@nx/js:tsc",
|
||||
"outputs": [
|
||||
"{options.outputPath}"
|
||||
],
|
||||
"options": {
|
||||
"outputPath": "dist/packages/pieces/community/image-router",
|
||||
"tsConfig": "packages/pieces/community/image-router/tsconfig.lib.json",
|
||||
"packageJson": "packages/pieces/community/image-router/package.json",
|
||||
"main": "packages/pieces/community/image-router/src/index.ts",
|
||||
"assets": [
|
||||
"packages/pieces/community/image-router/*.md",
|
||||
{
|
||||
"input": "packages/pieces/community/image-router/src/i18n",
|
||||
"output": "./src/i18n",
|
||||
"glob": "**/!(i18n.json)"
|
||||
}
|
||||
],
|
||||
"buildableProjectDepsInPackageJsonType": "dependencies",
|
||||
"updateBuildableProjectDepsInPackageJson": true
|
||||
},
|
||||
"dependsOn": [
|
||||
"prebuild",
|
||||
"^build"
|
||||
]
|
||||
},
|
||||
"nx-release-publish": {
|
||||
"options": {
|
||||
"packageRoot": "dist/{projectRoot}"
|
||||
}
|
||||
},
|
||||
"prebuild": {
|
||||
"dependsOn": [
|
||||
"^build"
|
||||
],
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"cwd": "packages/pieces/community/image-router",
|
||||
"command": "bun install --no-save --silent"
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint",
|
||||
"outputs": [
|
||||
"{options.outputFile}"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"Generate images with any model available on ImageRouter.": "Generate images with any model available on ImageRouter.",
|
||||
"Your ImageRouter API key. You can get your API key from the [ImageRouter API Keys page](https://imagerouter.io/api-keys).": "Your ImageRouter API key. You can get your API key from the [ImageRouter API Keys page](https://imagerouter.io/api-keys).",
|
||||
"Create Image": "Create Image",
|
||||
"Image to Image": "Image to Image",
|
||||
"Generate an image from a text prompt using any available model": "Generate an image from a text prompt using any available model",
|
||||
"Generate or edit images using input image(s) with optional mask": "Generate or edit images using input image(s) with optional mask",
|
||||
"Prompt": "Prompt",
|
||||
"Model": "Model",
|
||||
"Quality": "Quality",
|
||||
"Size": "Size",
|
||||
"Response Format": "Response Format",
|
||||
"Input Images": "Input Images",
|
||||
"Masks": "Masks",
|
||||
"Text prompt describing the image you want to generate": "Text prompt describing the image you want to generate",
|
||||
"Select an image generation model": "Select an image generation model",
|
||||
"Image quality (not all models support this)": "Image quality (not all models support this)",
|
||||
"Image size (e.g., 1024x1024). Use \"auto\" for default size.": "Image size (e.g., 1024x1024). Use \"auto\" for default size.",
|
||||
"How to receive the generated image": "How to receive the generated image",
|
||||
"Text prompt describing the image transformation": "Text prompt describing the image transformation",
|
||||
"Input image(s) for editing (up to 16 images)": "Input image(s) for editing (up to 16 images)",
|
||||
"Mask file(s) to specify areas to edit (some models require this)": "Mask file(s) to specify areas to edit (some models require this)",
|
||||
"Auto": "Auto",
|
||||
"Low": "Low",
|
||||
"Medium": "Medium",
|
||||
"High": "High",
|
||||
"URL (saved in logs)": "URL (saved in logs)",
|
||||
"Base64 JSON (saved in logs)": "Base64 JSON (saved in logs)",
|
||||
"Base64 Ephemeral (not saved)": "Base64 Ephemeral (not saved)"
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { createPiece } from "@activepieces/pieces-framework";
|
||||
import { imageRouterAuth } from "./lib/common/auth";
|
||||
import { PieceCategory } from "@activepieces/shared";
|
||||
import { createImage } from "./lib/actions/create-image";
|
||||
import { imageToImage } from "./lib/actions/image-to-image";
|
||||
|
||||
export const imageRouter = createPiece({
|
||||
displayName: "ImageRouter",
|
||||
auth: imageRouterAuth,
|
||||
minimumSupportedRelease: '0.36.1',
|
||||
categories: [PieceCategory.ARTIFICIAL_INTELLIGENCE],
|
||||
description: "Generate images with any model available on ImageRouter.",
|
||||
logoUrl: "https://cdn.activepieces.com/pieces/image-router.png",
|
||||
authors: ["onyedikachi-david"],
|
||||
actions: [
|
||||
createImage,
|
||||
imageToImage,
|
||||
],
|
||||
triggers: [],
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { createAction, Property } from '@activepieces/pieces-framework';
|
||||
import { HttpMethod, httpClient } from '@activepieces/pieces-common';
|
||||
import { imageRouterAuth } from '../common/auth';
|
||||
import { imageRouterApiCall } from '../common/client';
|
||||
import { modelDropdown } from '../common/props';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { kebabCase } from '@activepieces/shared';
|
||||
|
||||
export const createImage = createAction({
|
||||
auth: imageRouterAuth,
|
||||
name: 'createImage',
|
||||
displayName: 'Create Image',
|
||||
description: 'Generate an image from a text prompt using any available model',
|
||||
props: {
|
||||
prompt: Property.ShortText({
|
||||
displayName: 'Prompt',
|
||||
description: 'Text prompt describing the image you want to generate',
|
||||
required: true,
|
||||
}),
|
||||
model: modelDropdown,
|
||||
quality: Property.StaticDropdown({
|
||||
displayName: 'Quality',
|
||||
description: 'Image quality (not all models support this)',
|
||||
required: false,
|
||||
defaultValue: 'auto',
|
||||
options: {
|
||||
options: [
|
||||
{ label: 'Auto', value: 'auto' },
|
||||
{ label: 'Low', value: 'low' },
|
||||
{ label: 'Medium', value: 'medium' },
|
||||
{ label: 'High', value: 'high' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
size: Property.ShortText({
|
||||
displayName: 'Size',
|
||||
description: 'Image size (e.g., 1024x1024). Use "auto" for default size.',
|
||||
required: false,
|
||||
defaultValue: 'auto',
|
||||
}),
|
||||
responseFormat: Property.StaticDropdown({
|
||||
displayName: 'Response Format',
|
||||
description: 'How to receive the generated image',
|
||||
required: false,
|
||||
defaultValue: 'url',
|
||||
options: {
|
||||
options: [
|
||||
{ label: 'URL (saved in logs)', value: 'url' },
|
||||
{ label: 'Base64 JSON (saved in logs)', value: 'b64_json' },
|
||||
{ label: 'Base64 Ephemeral (not saved)', value: 'b64_ephemeral' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
},
|
||||
async run(context) {
|
||||
const { prompt, model, quality, size, responseFormat } = context.propsValue;
|
||||
|
||||
const body: any = {
|
||||
prompt,
|
||||
model,
|
||||
};
|
||||
|
||||
if (quality && quality !== 'auto') {
|
||||
body.quality = quality;
|
||||
}
|
||||
|
||||
if (size && size !== 'auto') {
|
||||
body.size = size;
|
||||
}
|
||||
|
||||
if (responseFormat && responseFormat !== 'url') {
|
||||
body.response_format = responseFormat;
|
||||
}
|
||||
|
||||
const response = await imageRouterApiCall<{
|
||||
data?: Array<{
|
||||
url?: string;
|
||||
b64_json?: string;
|
||||
revised_prompt?: string;
|
||||
}>;
|
||||
}>({
|
||||
apiKey: context.auth.secret_text,
|
||||
method: HttpMethod.POST,
|
||||
resourceUri: '/v1/openai/images/generations',
|
||||
body,
|
||||
});
|
||||
|
||||
const images = response.data || [];
|
||||
|
||||
if (images.length === 0) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const savedImages = await Promise.all(
|
||||
images.map(async (img, index) => {
|
||||
let imageBuffer: Buffer;
|
||||
let fileName: string;
|
||||
|
||||
if (img.b64_json) {
|
||||
imageBuffer = Buffer.from(img.b64_json, 'base64');
|
||||
fileName = `${randomBytes(8).toString('hex')}-${kebabCase(prompt).slice(0, 40)}-${index + 1}.png`;
|
||||
} else if (img.url) {
|
||||
const downloadResponse = await httpClient.sendRequest({
|
||||
method: HttpMethod.GET,
|
||||
url: img.url,
|
||||
responseType: 'arraybuffer',
|
||||
});
|
||||
imageBuffer = Buffer.from(downloadResponse.body);
|
||||
const urlExtension = img.url.split('.').pop()?.split('?')[0] || 'png';
|
||||
fileName = `${randomBytes(8).toString('hex')}-${kebabCase(prompt).slice(0, 40)}-${index + 1}.${urlExtension}`;
|
||||
} else {
|
||||
throw new Error(`Image ${index + 1} has no URL or base64 data`);
|
||||
}
|
||||
|
||||
const fileUrl = await context.files.write({
|
||||
fileName,
|
||||
data: imageBuffer,
|
||||
});
|
||||
|
||||
return {
|
||||
index: index + 1,
|
||||
url: img.url || null,
|
||||
b64_json: img.b64_json || null,
|
||||
revised_prompt: img.revised_prompt || prompt,
|
||||
savedFile: fileUrl,
|
||||
fileName,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
...response,
|
||||
images: savedImages,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { createAction, Property, ApFile } from '@activepieces/pieces-framework';
|
||||
import { HttpMethod, httpClient, AuthenticationType } from '@activepieces/pieces-common';
|
||||
import { imageRouterAuth } from '../common/auth';
|
||||
import { modelDropdown } from '../common/props';
|
||||
import { BASE_URL } from '../common/client';
|
||||
import FormData from 'form-data';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { kebabCase } from '@activepieces/shared';
|
||||
|
||||
interface ImageItem {
|
||||
image: ApFile;
|
||||
}
|
||||
|
||||
interface MaskItem {
|
||||
mask: ApFile;
|
||||
}
|
||||
|
||||
export const imageToImage = createAction({
|
||||
auth: imageRouterAuth,
|
||||
name: 'imageToImage',
|
||||
displayName: 'Image to Image',
|
||||
description: 'Generate or edit images using input image(s) with optional mask',
|
||||
props: {
|
||||
prompt: Property.ShortText({
|
||||
displayName: 'Prompt',
|
||||
description: 'Text prompt describing the image transformation',
|
||||
required: true,
|
||||
}),
|
||||
model: modelDropdown,
|
||||
images: Property.Array({
|
||||
displayName: 'Input Images',
|
||||
description: 'Input image(s) for editing (up to 16 images)',
|
||||
required: true,
|
||||
properties: {
|
||||
image: Property.File({
|
||||
displayName: 'Image',
|
||||
description: 'Input image file',
|
||||
required: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
masks: Property.Array({
|
||||
displayName: 'Masks',
|
||||
description: 'Mask file(s) to specify areas to edit (some models require this)',
|
||||
required: false,
|
||||
properties: {
|
||||
mask: Property.File({
|
||||
displayName: 'Mask',
|
||||
description: 'Mask image file',
|
||||
required: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
quality: Property.StaticDropdown({
|
||||
displayName: 'Quality',
|
||||
description: 'Image quality (not all models support this)',
|
||||
required: false,
|
||||
defaultValue: 'auto',
|
||||
options: {
|
||||
options: [
|
||||
{ label: 'Auto', value: 'auto' },
|
||||
{ label: 'Low', value: 'low' },
|
||||
{ label: 'Medium', value: 'medium' },
|
||||
{ label: 'High', value: 'high' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
size: Property.ShortText({
|
||||
displayName: 'Size',
|
||||
description: 'Image size (e.g., 1024x1024). Use "auto" for default size.',
|
||||
required: false,
|
||||
defaultValue: 'auto',
|
||||
}),
|
||||
responseFormat: Property.StaticDropdown({
|
||||
displayName: 'Response Format',
|
||||
description: 'How to receive the generated image',
|
||||
required: false,
|
||||
defaultValue: 'url',
|
||||
options: {
|
||||
options: [
|
||||
{ label: 'URL (saved in logs)', value: 'url' },
|
||||
{ label: 'Base64 JSON (saved in logs)', value: 'b64_json' },
|
||||
{ label: 'Base64 Ephemeral (not saved)', value: 'b64_ephemeral' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
},
|
||||
async run(context) {
|
||||
const { prompt, model, images: inputImages, masks, quality, size, responseFormat } = context.propsValue;
|
||||
|
||||
const imageItems = (inputImages as ImageItem[]) ?? [];
|
||||
const maskItems = (masks as MaskItem[]) ?? [];
|
||||
|
||||
if (!imageItems || imageItems.length === 0) {
|
||||
throw new Error('At least one input image is required');
|
||||
}
|
||||
|
||||
if (imageItems.length > 16) {
|
||||
throw new Error('Maximum 16 images allowed');
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append('prompt', prompt);
|
||||
formData.append('model', model);
|
||||
|
||||
for (const imageItem of imageItems) {
|
||||
if (imageItem.image) {
|
||||
formData.append('image[]', Buffer.from(imageItem.image.data), imageItem.image.filename);
|
||||
}
|
||||
}
|
||||
|
||||
if (maskItems && maskItems.length > 0) {
|
||||
for (const maskItem of maskItems) {
|
||||
if (maskItem.mask) {
|
||||
formData.append('mask[]', Buffer.from(maskItem.mask.data), maskItem.mask.filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (quality && quality !== 'auto') {
|
||||
formData.append('quality', quality);
|
||||
}
|
||||
|
||||
if (size && size !== 'auto') {
|
||||
formData.append('size', size);
|
||||
}
|
||||
|
||||
if (responseFormat && responseFormat !== 'url') {
|
||||
formData.append('response_format', responseFormat);
|
||||
}
|
||||
|
||||
const response = await httpClient.sendRequest({
|
||||
method: HttpMethod.POST,
|
||||
url: `${BASE_URL}/v1/openai/images/edits`,
|
||||
authentication: {
|
||||
type: AuthenticationType.BEARER_TOKEN,
|
||||
token: context.auth.secret_text,
|
||||
},
|
||||
headers: {
|
||||
...formData.getHeaders(),
|
||||
},
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (response.status >= 400) {
|
||||
const errorMessage = (response.body as any)?.error?.message ||
|
||||
(response.body as any)?.message ||
|
||||
`ImageRouter API error: ${response.status}`;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
const responseBody = response.body as {
|
||||
data?: Array<{
|
||||
url?: string;
|
||||
b64_json?: string;
|
||||
revised_prompt?: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
const generatedImages = responseBody.data || [];
|
||||
|
||||
if (generatedImages.length === 0) {
|
||||
return responseBody;
|
||||
}
|
||||
|
||||
const savedImages = await Promise.all(
|
||||
generatedImages.map(async (img: { url?: string; b64_json?: string; revised_prompt?: string }, index: number) => {
|
||||
let imageBuffer: Buffer;
|
||||
let fileName: string;
|
||||
|
||||
if (img.b64_json) {
|
||||
imageBuffer = Buffer.from(img.b64_json, 'base64');
|
||||
fileName = `${randomBytes(8).toString('hex')}-${kebabCase(prompt).slice(0, 40)}-${index + 1}.png`;
|
||||
} else if (img.url) {
|
||||
const downloadResponse = await httpClient.sendRequest({
|
||||
method: HttpMethod.GET,
|
||||
url: img.url,
|
||||
responseType: 'arraybuffer',
|
||||
});
|
||||
imageBuffer = Buffer.from(downloadResponse.body);
|
||||
const urlExtension = img.url.split('.').pop()?.split('?')[0] || 'png';
|
||||
fileName = `${randomBytes(8).toString('hex')}-${kebabCase(prompt).slice(0, 40)}-${index + 1}.${urlExtension}`;
|
||||
} else {
|
||||
throw new Error(`Image ${index + 1} has no URL or base64 data`);
|
||||
}
|
||||
|
||||
const fileUrl = await context.files.write({
|
||||
fileName,
|
||||
data: imageBuffer,
|
||||
});
|
||||
|
||||
return {
|
||||
index: index + 1,
|
||||
url: img.url || null,
|
||||
b64_json: img.b64_json || null,
|
||||
revised_prompt: img.revised_prompt || prompt,
|
||||
savedFile: fileUrl,
|
||||
fileName,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
...responseBody,
|
||||
images: savedImages,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { PieceAuth } from '@activepieces/pieces-framework';
|
||||
import { HttpMethod } from '@activepieces/pieces-common';
|
||||
import { imageRouterApiCall } from './client';
|
||||
|
||||
export const imageRouterAuth = PieceAuth.SecretText({
|
||||
displayName: 'API Key',
|
||||
description: 'Your ImageRouter API key. You can get your API key from the [ImageRouter API Keys page](https://imagerouter.io/api-keys).',
|
||||
required: true,
|
||||
validate: async ({ auth }) => {
|
||||
try {
|
||||
await imageRouterApiCall({
|
||||
apiKey: auth as string,
|
||||
method: HttpMethod.POST,
|
||||
resourceUri: '/v1/openai/images/generations',
|
||||
body: {
|
||||
prompt: 'test',
|
||||
model: 'test/test',
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
message: 'API key validated successfully. Connected to ImageRouter.',
|
||||
};
|
||||
} catch (error: any) {
|
||||
if (error.message.includes('401') || error.message.includes('403')) {
|
||||
return {
|
||||
valid: false,
|
||||
error: 'Invalid API key. Please check your API key and try again.',
|
||||
};
|
||||
}
|
||||
|
||||
if (error.message.includes('429')) {
|
||||
return {
|
||||
valid: false,
|
||||
error: 'Rate limit exceeded. Please wait a moment and try again.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
valid: false,
|
||||
error: `Authentication failed: ${error.message}. Please verify your API key is correct.`,
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { httpClient, HttpMethod, HttpMessageBody } from '@activepieces/pieces-common';
|
||||
|
||||
export const BASE_URL = 'https://api.imagerouter.io';
|
||||
|
||||
export type ImageRouterApiCallParams = {
|
||||
apiKey: string;
|
||||
method: HttpMethod;
|
||||
resourceUri: string;
|
||||
body?: any;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
|
||||
export async function imageRouterApiCall<T extends HttpMessageBody>({
|
||||
apiKey,
|
||||
method,
|
||||
resourceUri,
|
||||
body,
|
||||
headers = {},
|
||||
}: ImageRouterApiCallParams): Promise<T> {
|
||||
const response = await httpClient.sendRequest<T>({
|
||||
method,
|
||||
url: `${BASE_URL}${resourceUri}`,
|
||||
headers: {
|
||||
'Authorization': `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
...headers,
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
if (response.status >= 400) {
|
||||
const errorMessage = (response.body as any)?.error?.message ||
|
||||
(response.body as any)?.message ||
|
||||
`ImageRouter API error: ${response.status}`;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
return response.body;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { Property } from '@activepieces/pieces-framework';
|
||||
import { HttpMethod } from '@activepieces/pieces-common';
|
||||
import { imageRouterApiCall } from './client';
|
||||
import { imageRouterAuth } from './auth';
|
||||
|
||||
export const modelDropdown = Property.Dropdown({
|
||||
auth: imageRouterAuth,
|
||||
displayName: 'Model',
|
||||
description: 'Select an image generation model',
|
||||
required: true,
|
||||
refreshers: [],
|
||||
options: async ({ auth }) => {
|
||||
if (!auth) {
|
||||
return {
|
||||
disabled: true,
|
||||
placeholder: 'Please connect your account first',
|
||||
options: [],
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await imageRouterApiCall<any>({
|
||||
apiKey: auth.secret_text,
|
||||
method: HttpMethod.GET,
|
||||
resourceUri: '/v1/models?type=image',
|
||||
});
|
||||
|
||||
let models: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
provider: string;
|
||||
category: string;
|
||||
isFree: boolean;
|
||||
isFast: boolean;
|
||||
isPremium: boolean;
|
||||
}> = [];
|
||||
|
||||
if (response && typeof response === 'object') {
|
||||
const keys = Object.keys(response);
|
||||
if (keys.length > 0 && typeof response[keys[0]] === 'object') {
|
||||
models = keys.map((modelId) => {
|
||||
const modelData = response[modelId];
|
||||
const provider = modelData.providers?.[0]?.id ||
|
||||
modelData.providers?.[0]?.name ||
|
||||
'';
|
||||
const modelName = modelId.split('/').pop() || modelId;
|
||||
|
||||
const isFree = modelId.includes(':free') ||
|
||||
modelData.providers?.some((p: any) =>
|
||||
p.pricing?.value === 0 ||
|
||||
(p.pricing?.type === 'fixed' && p.pricing?.value === 0)
|
||||
) || false;
|
||||
|
||||
const nameLower = modelName.toLowerCase();
|
||||
const isFast = nameLower.includes('fast') ||
|
||||
nameLower.includes('turbo') ||
|
||||
nameLower.includes('schnell') ||
|
||||
nameLower.includes('flash') ||
|
||||
nameLower.includes('lightning') ||
|
||||
nameLower.includes('mini');
|
||||
|
||||
const isPremium = nameLower.includes('pro') ||
|
||||
nameLower.includes('ultra') ||
|
||||
nameLower.includes('max') ||
|
||||
nameLower.includes('quality');
|
||||
|
||||
let category = '';
|
||||
if (isFree) {
|
||||
category = 'Free';
|
||||
} else if (isFast) {
|
||||
category = 'Fast';
|
||||
} else if (isPremium) {
|
||||
category = 'Premium';
|
||||
} else {
|
||||
category = 'Standard';
|
||||
}
|
||||
|
||||
return {
|
||||
id: modelId,
|
||||
name: modelName,
|
||||
provider,
|
||||
category,
|
||||
isFree,
|
||||
isFast,
|
||||
isPremium,
|
||||
};
|
||||
});
|
||||
} else if (Array.isArray(response)) {
|
||||
models = response;
|
||||
} else if (Array.isArray(response.data)) {
|
||||
models = response.data;
|
||||
} else if (Array.isArray(response.models)) {
|
||||
models = response.models;
|
||||
} else if (Array.isArray(response.items)) {
|
||||
models = response.items;
|
||||
}
|
||||
}
|
||||
|
||||
if (models.length === 0) {
|
||||
return {
|
||||
disabled: true,
|
||||
placeholder: 'No models found',
|
||||
options: [],
|
||||
};
|
||||
}
|
||||
|
||||
const sortedModels = models.sort((a, b) => {
|
||||
if (a.isFree && !b.isFree) return -1;
|
||||
if (!a.isFree && b.isFree) return 1;
|
||||
if (a.isFast && !b.isFast) return -1;
|
||||
if (!a.isFast && b.isFast) return 1;
|
||||
if (a.isPremium && !b.isPremium) return -1;
|
||||
if (!a.isPremium && b.isPremium) return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return {
|
||||
disabled: false,
|
||||
options: sortedModels.map((model) => {
|
||||
const modelId = model.id || '';
|
||||
const modelName = model.name || modelId.split('/').pop() || modelId;
|
||||
const provider = model.provider || '';
|
||||
const category = model.category || '';
|
||||
|
||||
// Create label with clear category prefix using brackets
|
||||
const label = provider
|
||||
? `[${category}] ${modelName} (${provider})`
|
||||
: `[${category}] ${modelName}`;
|
||||
|
||||
return {
|
||||
label,
|
||||
value: modelId,
|
||||
};
|
||||
}),
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error('Error fetching models:', error);
|
||||
return {
|
||||
disabled: true,
|
||||
placeholder: `Failed to load models: ${error.message || 'Unknown error'}`,
|
||||
options: [],
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"extends": "../../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"importHelpers": true,
|
||||
"noImplicitOverride": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noPropertyAccessFromIndexSignature": true
|
||||
},
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.lib.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "../../../../dist/out-tsc",
|
||||
"declaration": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user