Saltearse al contenido

Los Fundamentos

Los plugins de StudioCMS son una herramienta poderosa que te permite extender la funcionalidad de StudioCMS. Proporcionan una manera simple y flexible de añadir nuevas características a tu proyecto StudioCMS. A continuación se muestra un desglose de los plugins de StudioCMS y cómo funcionan.

Los plugins de StudioCMS son similares a las Integraciones de Astro, pero tienen información adicional adjunta al objeto de función. Esta información es utilizada por StudioCMS para determinar cómo debe cargarse y utilizarse el complemento. Los plugins de StudioCMS se utilizan para extender la funcionalidad de StudioCMS añadiendo nuevas características o modificando las existentes.

type
type StudioCMSPlugin = {
identifier: string;
name: string;
studiocmsMinimumVersion: string;
integration?: AstroIntegration | AstroIntegration[] | undefined;
triggerSitemap?: boolean;
sitemaps?: Array<{
pluginName: string;
sitemapXMLEndpointPath: string | URL;
}> | undefined;
dashboardGridItems?: Array<{
name: string;
span: 1 | 2 | 3;
variant: "default" | "filled";
requiresPermission?: "owner" | "admin" | "editor" | "visitor";
header?: {
title: string;
icon?: HeroIconName;
};
body?: {
html: string;
components?: Record<string, string>;
sanitizeOpts?: SanitizeOptions;
};
}> | undefined;
settingsPage: {
fields: SettingsField[];
onSave: APIRoute;
} | undefined;
pageTypes: Array<{
label: string;
identifier: string;
description: string;
pageContentComponent: string;
}> | undefined;
}
StudioCMSPlugin
= {
/**
* Identificador del complemento desde el package.json
*/
identifier: string

Identificador del complemento desde el package.json

identifier
: string;
/**
* Etiqueta del complemento para mostrar en el Panel de Control de StudioCMS
*/
name: string

Etiqueta del complemento para mostrar en el Panel de Control de StudioCMS

name
: string;
/**
* Versión mínima de StudioCMS requerida para que el complemento funcione
*/
studiocmsMinimumVersion: string

Versión mínima de StudioCMS requerida para que el complemento funcione

studiocmsMinimumVersion
: string;
/**
* Integración(es) de Astro que proporciona el complemento
*/
integration?: AstroIntegration | AstroIntegration[] | undefined

Integración(es) de Astro que proporciona el complemento

integration
?:
(alias) interface AstroIntegration
import AstroIntegration
AstroIntegration
|
(alias) interface AstroIntegration
import AstroIntegration
AstroIntegration
[] | undefined;
/**
* Si es verdadero, el complemento habilitará la generación del mapa del sitio
*/
triggerSitemap?: boolean

Si es verdadero, el complemento habilitará la generación del mapa del sitio

triggerSitemap
?: boolean;
/**
* Permite que el complemento añada puntos finales del mapa del sitio
*/
sitemaps?: {
pluginName: string;
sitemapXMLEndpointPath: string | URL;
}[] | undefined

Permite que el complemento añada puntos finales del mapa del sitio

sitemaps
?:
interface Array<T>
Array
<{
/**
* Nombre del complemento
*/
pluginName: string

Nombre del complemento

pluginName
: string;
/**
* Ruta al archivo de punto final XML del mapa del sitio
*/
sitemapXMLEndpointPath: string | URL

Ruta al archivo de punto final XML del mapa del sitio

sitemapXMLEndpointPath
: string |
interface URL

URL class is a global reference for import { URL } from 'node:url' https://nodejs.org/api/url.html#the-whatwg-url-api

URL class is a global reference for import { URL } from 'url' https://nodejs.org/api/url.html#the-whatwg-url-api

@sincev10.0.0

@sincev10.0.0

URL
;
}> | undefined;
/**
* Permite que el complemento añada elementos personalizados a la cuadrícula del panel
*/
dashboardGridItems?: {
name: string;
span: 1 | 2 | 3;
variant: "default" | "filled";
requiresPermission?: "owner" | "admin" | "editor" | "visitor";
header?: {
title: string;
icon?: HeroIconName;
};
body?: {
html: string;
components?: Record<string, string>;
sanitizeOpts?: SanitizeOptions;
};
}[] | undefined

Permite que el complemento añada elementos personalizados a la cuadrícula del panel

dashboardGridItems
?:
interface Array<T>
Array
<{
/**
* Nombre del elemento de cuadrícula
*/
name: string

Nombre del elemento de cuadrícula

name
: string;
/**
* Extensión del elemento de cuadrícula
*/
span: 2 | 1 | 3

Extensión del elemento de cuadrícula

span
: 1 | 2 | 3;
/**
* Variante de tarjeta del elemento de cuadrícula
*/
variant: "default" | "filled"

Variante de tarjeta del elemento de cuadrícula

variant
: 'default' | 'filled';
/**
* Permiso requerido para ver el elemento de cuadrícula
*/
requiresPermission?: "owner" | "admin" | "editor" | "visitor"

Permiso requerido para ver el elemento de cuadrícula

requiresPermission
?: "owner" | "admin" | "editor" | "visitor";
/**
* Información del encabezado del elemento de cuadrícula
*/
header?: {
title: string;
icon?: HeroIconName;
}

Información del encabezado del elemento de cuadrícula

header
?: {
/**
* Título del elemento de cuadrícula
*/
title: string

Título del elemento de cuadrícula

title
: string;
/**
* Icono del elemento de cuadrícula
*/
icon?: "code-bracket-solid" | "code-bracket-square-solid" | "exclamation-circle" | "exclamation-circle-solid" | "exclamation-triangle" | "exclamation-triangle-solid" | "viewfinder-circle" | ... 1280 more ... | "x-mark-solid"

Icono del elemento de cuadrícula

icon
?:
type HeroIconName = "code-bracket-solid" | "code-bracket-square-solid" | "exclamation-circle" | "exclamation-circle-solid" | "exclamation-triangle" | "exclamation-triangle-solid" | "viewfinder-circle" | ... 1280 more ... | "x-mark-solid"
HeroIconName
;
};
/**
* Información del cuerpo del elemento de cuadrícula
*/
body?: {
html: string;
components?: Record<string, string>;
sanitizeOpts?: SanitizeOptions;
}

Información del cuerpo del elemento de cuadrícula

body
?: {
/**
* Contenido HTML del elemento de cuadrícula
*/
html: string

Contenido HTML del elemento de cuadrícula

html
: string;
/**
* Componente que se muestra en el elemento de cuadrícula
*/
components?: Record<string, string>

Componente que se muestra en el elemento de cuadrícula

components
?:
type Record<K extends keyof any, T> = { [P in K]: T; }

Construct a type with a set of properties K of type T

Record
<string, string>;
/**
* Opciones de sanitización para el contenido HTML
*/
sanitizeOpts?: SanitizeOptions

Opciones de sanitización para el contenido HTML

sanitizeOpts
?:
(alias) interface SanitizeOptions
import SanitizeOptions
SanitizeOptions
;
};
}> | undefined;
/**
* Si existe, el complemento tendrá su propia página de configuración
*/
settingsPage: {
fields: SettingsField[];
onSave: APIRoute;
} | undefined

Si existe, el complemento tendrá su propia página de configuración

settingsPage
: {
/**
* Campos según la especificación
*/
fields: ({
input: "checkbox";
label: string;
name: string;
required?: boolean | undefined;
readOnly?: boolean | undefined;
color?: "danger" | "success" | "warning" | "info" | "primary" | "mono" | undefined;
defaultChecked?: boolean | undefined;
size?: "sm" | "md" | "lg" | undefined;
} | ... 4 more ... | {
...;
})[]

Campos según la especificación

fields
:
type SettingsField = {
input: "checkbox";
label: string;
name: string;
required?: boolean | undefined;
readOnly?: boolean | undefined;
color?: "danger" | "success" | "warning" | "info" | "primary" | "mono" | undefined;
defaultChecked?: boolean | undefined;
size?: "sm" | "md" | "lg" | undefined;
} | ... 4 more ... | {
...;
}

Represents the type inferred from the SettingsFieldSchema schema.

This type is used to define the structure of settings fields within the application.

SettingsField
[];
/**
* Función que se ejecuta cuando se guarda la página de configuración
*
* Debe devolver una cadena si hay un error,
* de lo contrario devuelve true booleano para indicar éxito
*/
onSave: APIRoute

Función que se ejecuta cuando se guarda la página de configuración

Debe devolver una cadena si hay un error, de lo contrario devuelve true booleano para indicar éxito

onSave
:
type APIRoute<APIProps extends Record<string, any> = Record<string, any>, APIParams extends Record<string, string | undefined> = Record<string, string | undefined>> = (context: APIContext<APIProps, APIParams>) => Response | Promise<Response>
APIRoute
;
} | undefined;
/**
* Definición del tipo de página. Si está presente, el complemento quiere poder modificar el proceso de creación de páginas
*/
pageTypes: {
label: string;
identifier: string;
description: string;
pageContentComponent: string;
}[] | undefined

Definición del tipo de página. Si está presente, el complemento quiere poder modificar el proceso de creación de páginas

pageTypes
:
interface Array<T>
Array
<{
/**
* Etiqueta que se muestra en el input select
*/
label: string

Etiqueta que se muestra en el input select

label
: string;
/**
* Identificador que se guarda en la base de datos
* @example
* // Un solo tipo de página por complemento
* 'studiocms'
* '@studiocms/blog'
* // Múltiples tipos de página por complemento (Usa identificadores únicos para cada tipo para evitar conflictos)
* '@mystudiocms/plugin:pageType1'
* '@mystudiocms/plugin:pageType2'
* '@mystudiocms/plugin:pageType3'
* '@mystudiocms/plugin:pageType4'
*/
identifier: string

Identificador que se guarda en la base de datos

@example // Un solo tipo de página por complemento 'studiocms' '@studiocms/blog' // Múltiples tipos de página por complemento (Usa identificadores únicos para cada tipo para evitar conflictos) '@mystudiocms/plugin:pageType1' '@mystudiocms/plugin:pageType2' '@mystudiocms/plugin:pageType3' '@mystudiocms/plugin:pageType4'

identifier
: string;
/**
* Descripción que se muestra debajo del encabezado "Contenido de la Página" si se selecciona este tipo
*/
description: string

Descripción que se muestra debajo del encabezado "Contenido de la Página" si se selecciona este tipo

description
: string;
/**
* La ruta al componente real que se muestra para el contenido de la página
*
* El componente debe tener una prop `content` que sea una cadena para poder mostrar el contenido actual.
*
* **NOTA:** Actualmente, requiere que uses el id de formulario `page-content` para la salida de contenido. Tu editor también debe poder manejar el envío de formularios.
*
* @example
* ```ts
* import { createResolver } from 'astro-integration-kit';
* const { resolve } = createResolver(import.meta.url)
*
* {
* pageContentComponent: resolve('./components/MyContentEditor.astro'),
* }
* ```
*/
pageContentComponent: string

La ruta al componente real que se muestra para el contenido de la página

El componente debe tener una prop content que sea una cadena para poder mostrar el contenido actual.

NOTA: Actualmente, requiere que uses el id de formulario page-content para la salida de contenido. Tu editor también debe poder manejar el envío de formularios.

@example

import { createResolver } from 'astro-integration-kit';
const { resolve } = createResolver(import.meta.url)
{
pageContentComponent: resolve('./components/MyContentEditor.astro'),
}

pageContentComponent
: string;
}> | undefined;
};

Para definir un complemento de StudioCMS, necesitas crear un objeto que se ajuste al tipo StudioCMSPlugin. Este objeto debe parecerse a lo siguiente, teniendo en cuenta que las siguientes propiedades son requeridas:

  • identifier: El identificador del complemento del archivo package.json.
  • name: La etiqueta del complemento que se mostrará en el Panel de Control de StudioCMS.
  • studiocmsMinimumVersion: La versión mínima de StudioCMS requerida para que el complemento funcione.

Aquí hay un ejemplo de una definición de complemento de StudioCMS que incluye todas las propiedades requeridas y además proporciona una Integración Astro para realizar lógica personalizada:

my-plugin.ts
import {
function definePlugin(options: StudioCMSPluginOptions): StudioCMSPlugin

Defines a plugin for StudioCMS.

@paramoptions - The configuration options for the plugin.

@returnsThe plugin configuration.

definePlugin
} from 'studiocms/plugins';
import {
(alias) interface AstroIntegration
import AstroIntegration
AstroIntegration
} from 'astro';
// Define las opciones para el complemento e integración
interface
interface Options
Options
{
Options.foo: string
foo
: string;
}
// Define la integración Astro
const
const myIntegration: (options: Options) => AstroIntegration
myIntegration
= (
options: Options
options
:
interface Options
Options
):
(alias) interface AstroIntegration
import AstroIntegration
AstroIntegration
=> ({
AstroIntegration.name: string

The name of the integration.

name
: 'my-astro-integration',
AstroIntegration.hooks: {
'astro:config:setup'?: (options: {
config: AstroConfig;
command: "dev" | "build" | "preview" | "sync";
isRestart: boolean;
updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig;
addRenderer: (renderer: AstroRenderer) => void;
addWatchFile: (path: URL | string) => void;
injectScript: (stage: InjectedScriptStage, content: string) => void;
injectRoute: (injectRoute: InjectedRoute) => void;
addClientDirective: (directive: ClientDirectiveConfig) => void;
addDevToolbarApp: (entrypoint: DevToolbarAppEntry) => void;
addMiddleware: (mid: AstroIntegrationMiddleware) => void;
createCodegenDir: () => URL;
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
... 10 more ...;
'astro:routes:resolved'?: (options: {
routes: IntegrationResolvedRoute[];
logger: AstroIntegrationLogger;
}) => void | Promise<void>;
} & Partial<...>

The different hooks available to extend.

hooks
: {
"astro:config:setup": () => {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
('Hello from my Astro Integration!');
}
}
});
// Define el complemento de StudioCMS
export const
const myPlugin: (options: Options) => StudioCMSPlugin
myPlugin
= (
options: Options
options
:
interface Options
Options
) =>
function definePlugin(options: StudioCMSPluginOptions): StudioCMSPlugin

Defines a plugin for StudioCMS.

@paramoptions - The configuration options for the plugin.

@returnsThe plugin configuration.

definePlugin
({
identifier: string
identifier
: 'my-plugin',
name: string
name
: 'My Plugin',
studiocmsMinimumVersion: string
studiocmsMinimumVersion
: '0.1.0-beta.8',
integration?: AstroIntegration | AstroIntegration[] | undefined
integration
:
const myIntegration: (options: Options) => AstroIntegration
myIntegration
(
options: Options
options
), // Opcional, pero recomendado
});

En este ejemplo, definimos un complemento de StudioCMS llamado My Plugin que requiere la versión 0.1.0-beta.8 o superior de StudioCMS. El complemento también proporciona una Integración Astro que registra un mensaje en la consola cuando se llama al hook astro:config:setup.

Para más información sobre la creación de plugins, consulta la Guía Haciendo Plugins Útiles