Ir al contenido

Datos y almacenamiento

Almacenamiento de documentos limitado al espacio de trabajo y respaldado por LiteDB. Requiere un espacio de trabajo abierto.

MétodoFirmaAsyncDescripción
put(collection, key, data)NoAlmacena un documento
get(collection, key) → StoreDoc | nullNoRecupera un documento
list(collection, options?) → StoreDoc[]NoLista documentos de una colección
search(collection, query, options?) → StoreDoc[]NoBusca texto dentro de una colección
delete(collection, key) → booleanNoElimina un documento
count(collection) → numberNoCuenta documentos
clear(collection)NoElimina todos los documentos de una colección
collections() → string[]NoLista todos los nombres de colección

StoreDoc:

{
key: string
data: any
createdAt: string // ISO 8601
updatedAt: string // ISO 8601
}

StoreListOptions:

{
limit?: number // default: 100
offset?: number // default: 0
sort?: string // "key", "createdAt", "updatedAt" (default)
order?: string // "asc" or "desc" (default)
}
async function main() {
// Store data
g.store.put("products", "item-1", {
name: "Widget",
price: 9.99,
inStock: true
});
// Retrieve it
const doc = g.store.get("products", "item-1");
if (doc) g.log("Found: " + doc.data.name);
// Search
const results = g.store.search("products", "Widget");
g.log("Matches: " + results.length);
}


Cola persistente limitada al espacio de trabajo, con niveles de prioridad y soporte de cola de rechazos. Requiere un espacio de trabajo abierto.

MétodoFirmaAsyncDescripción
enqueue(name, data, options?)NoAñade un elemento a una cola
dequeue(name) → QueueItem | nullNoToma el siguiente elemento
commit(checkoutId)NoMarca un elemento tomado como completado
abort(checkoutId, error?) → booleanNoDevuelve un elemento a la cola o lo mueve a rechazos si superó los reintentos
peek(name) → QueueItem | nullNoVe el siguiente elemento sin tomarlo
count(name) → numberNoCuenta elementos pendientes
clear(name)NoElimina todos los elementos de una cola
list(name, options?) → QueueItem[]NoLista elementos pendientes
queues() → string[]NoLista todos los nombres de cola
deadLetter(name, options?) → DeadLetterItem[]NoLista elementos en la cola de rechazos
retry(name, deadLetterId)NoVuelve a poner en cola un elemento rechazado
waitForItem(name, options?) → Promise<QueueItem | null>Bloquea hasta que haya un elemento disponible

QueueEnqueueOptions:

{
priority?: number // 0=low, 1=normal (default), 2=high
maxRetries?: number // default: 3
}

QueueItem:

{
id: number
data: any
priority: number
attempts: number
maxRetries: number
enqueuedAt: string
lastAttemptAt?: string
lastError?: string
}
async function main() {
// Enqueue work items
g.queue.enqueue("urls", { url: "https://example.com/page1" });
g.queue.enqueue("urls", { url: "https://example.com/page2" }, { priority: 2 });
// Process items
const item = g.queue.dequeue("urls");
if (!item) return g.log("Queue empty");
await g.nav.navigateToUrl(item.data.url);
const html = await g.page.getDom();
// Mark complete
g.queue.commit(item.id);
}


## g.search.* — búsqueda de texto completo

Sección titulada «## g.search.* — búsqueda de texto completo»

Índice Lucene.NET limitado al espacio de trabajo. Admite operadores booleanos, comodines, coincidencia aproximada y consultas por campo. Requiere un espacio de trabajo abierto.

MétodoFirmaAsyncDescripción
index(fields)NoIndexa un documento; debe incluir _key y _collection
query(queryString, options?) → SearchResult[]NoBusca en el índice con sintaxis Lucene
delete(collection, key)NoElimina un documento del índice
deleteByCollection(collection) → numberNoElimina todos los documentos de una colección
count(collection?) → numberNoCuenta documentos indexados
clear()NoLimpia todo el índice

SearchResult:

{
key: string
collection: string
score: number // Lucene relevance score
fields: Record<string, string>
}
async function main() {
// Index documents
g.search.index({
_key: "article-1",
_collection: "articles",
title: "Getting Started with Guida",
body: "Guida is a scriptable browser..."
});
// Query with Lucene syntax
const results = g.search.query("scriptable browser", { collection: "articles" });
for (const r of results) {
g.log(r.fields.title + " (score: " + r.score + ")");
}
}


## g.s3.* — almacenamiento de objetos compatible con S3

Sección titulada «## g.s3.* — almacenamiento de objetos compatible con S3»

Almacenamiento compatible con S3 mediante MinIO SDK. Funciona con AWS S3, MinIO y cualquier servicio compatible con S3. El parámetro conn es el nombre de una credencial que contiene la cadena de conexión. Bloqueado para scripts originados por MCP.

MétodoFirmaAsyncDescripción
listBuckets(conn) → Promise<S3BucketInfo[]>Lista todos los buckets accesibles
bucketExists(conn, bucket) → Promise<boolean>Comprueba si existe un bucket
listObjects(conn, bucket, options?) → Promise<S3ObjectInfo[]>Lista objetos de un bucket
getObjectText(conn, bucket, key) → Promise<string>Descarga un objeto como texto UTF-8
getObject(conn, bucket, key, localPath) → PromiseDescarga un objeto a un archivo local
putObjectText(conn, bucket, key, content, contentType?) → PromiseSube texto como objeto
putObject(conn, bucket, key, localPath, contentType?) → PromiseSube un archivo local como objeto
deleteObject(conn, bucket, key) → PromiseElimina un objeto
objectExists(conn, bucket, key) → Promise<boolean>Comprueba si existe un objeto
createBucket(conn, bucket, region?) → PromiseCrea un bucket nuevo
copyObject(conn, srcBucket, srcKey, dstBucket, dstKey) → PromiseCopia del lado servidor, sin pasar datos por el cliente
getPresignedUrl(conn, bucket, key, options?) → Promise<string>Genera una URL prefirmada con caducidad

S3ListOptions:

{
prefix?: string // filter objects by key prefix
maxKeys?: number // max objects to return (default: 1000)
}

S3BucketInfo:

{
name: string
creationDate: string // ISO 8601
}

S3ObjectInfo:

{
key: string // object key (path)
size: number // size in bytes
lastModified: string // ISO 8601
etag: string // entity tag (hash)
}

S3PresignedUrlOptions:

{
method?: string // "GET" (download, default) or "PUT" (upload)
expiry?: number // URL expiry in seconds (default: 3600)
}
async function main() {
// List CSV files in a bucket
const files = await g.s3.listObjects("my-s3", "data-bucket", {
prefix: "exports/"
});
g.log("Found " + files.length + " objects");
// Upload scraped data
await g.s3.putObjectText(
"my-s3", "data-bucket", "exports/results.json",
JSON.stringify({ items: [1, 2, 3] }),
"application/json"
);
// Generate a shareable link
const url = await g.s3.getPresignedUrl("my-s3", "data-bucket", "exports/results.json", {
expiry: 86400 // 24 hours
});
g.log("Download link: " + url);
}


Operaciones MongoDB mediante MongoDB.Driver. El parámetro conn es el nombre de una credencial que contiene la cadena de conexión. Usa pooling automático de conexiones. Bloqueado para scripts originados por MCP.

MétodoFirmaAsyncDescripción
find(conn, db, collection, filter?, options?) → Promise<object[]>Busca documentos que coinciden con un filtro
findOne(conn, db, collection, filter?) → Promise<object | null>Busca el primer documento coincidente
insertOne(conn, db, collection, document) → Promise<MongoInsertResult>Inserta un documento
insertMany(conn, db, collection, documents) → Promise<MongoInsertManyResult>Inserta varios documentos
updateOne(conn, db, collection, filter, update) → Promise<MongoUpdateResult>Actualiza el primer documento coincidente
updateMany(conn, db, collection, filter, update) → Promise<MongoUpdateResult>Actualiza todos los documentos coincidentes
deleteOne(conn, db, collection, filter) → Promise<MongoDeleteResult>Elimina el primer documento coincidente
deleteMany(conn, db, collection, filter) → Promise<MongoDeleteResult>Elimina todos los documentos coincidentes
replaceOne(conn, db, collection, filter, replacement) → Promise<MongoUpdateResult>Reemplaza el primer documento coincidente
countDocuments(conn, db, collection, filter?) → Promise<number>Cuenta documentos coincidentes
listDatabases(conn) → Promise<string[]>Lista todos los nombres de base de datos
listCollections(conn, db) → Promise<string[]>Lista nombres de colección en una base
aggregate(conn, db, collection, pipeline) → Promise<object[]>Ejecuta una canalización de agregación
createIndex(conn, db, collection, keys, options?) → Promise<string>Crea un índice y devuelve su nombre
dropCollection(conn, db, collection) → PromiseElimina una colección
distinct(conn, db, collection, fieldName, filter?) → Promise<any[]>Obtiene valores distintos de un campo
bulkWrite(conn, db, collection, operations) → Promise<MongoBulkWriteResult>Ejecuta varias operaciones de escritura por lotes

MongoFindOptions:

{
sort?: object // e.g., { name: 1, age: -1 }
limit?: number
skip?: number
projection?: object // e.g., { name: 1, _id: 0 }
}

MongoInsertResult:

{
insertedId: string // the _id of the inserted document
}

MongoInsertManyResult:

{
insertedCount: number
insertedIds: string[]
}

MongoUpdateResult:

{
matchedCount: number
modifiedCount: number
}

MongoDeleteResult:

{
deletedCount: number
}

MongoIndexOptions:

{
unique?: boolean // enforce uniqueness
name?: string // custom index name
}

MongoBulkOperation:

{
type: string // "insertOne", "updateOne", "updateMany",
// "deleteOne", "deleteMany", "replaceOne"
filter?: object // for update/delete/replace
document?: object // for insertOne
update?: object // for updateOne/updateMany
replacement?: object // for replaceOne
}

MongoBulkWriteResult:

{
insertedCount: number
matchedCount: number
modifiedCount: number
deletedCount: number
}
async function main() {
const conn = "my-mongo"; // secret name with connection string
// Insert a document
const result = await g.mongodb.insertOne(conn, "scraping", "products", {
name: "Widget", price: 9.99, category: "tools"
});
g.log("Inserted: " + result.insertedId);
// Find with filter and sort
const docs = await g.mongodb.find(conn, "scraping", "products",
{ price: { $lt: 20 } },
{ sort: { price: 1 }, limit: 10 }
);
g.log("Found " + docs.length + " cheap products");
// Aggregation pipeline
const stats = await g.mongodb.aggregate(conn, "scraping", "products", [
{ $group: { _id: "$category", avgPrice: { $avg: "$price" }, count: { $sum: 1 } } },
{ $sort: { count: -1 } }
]);
for (const s of stats) {
g.log(s._id + ": " + s.count + " items, avg $" + s.avgPrice.toFixed(2));
}
}


Operaciones PostgreSQL mediante Npgsql. Usa parámetros posicionales $1, $2, ...; nunca interpole valores dentro de cadenas SQL. El parámetro conn es el nombre de una credencial que contiene la cadena de conexión. Usa pooling automático. Bloqueado para scripts originados por MCP.

MétodoFirmaAsyncDescripción
query(conn, sql, params?) → Promise<object[]>SELECT que devuelve todas las filas
queryOne(conn, sql, params?) → Promise<object | null>SELECT que devuelve la primera fila
execute(conn, sql, params?) → Promise<PgExecuteResult>INSERT/UPDATE/DELETE
scalar(conn, sql, params?) → Promise<any>Devuelve la primera columna de la primera fila
transaction(conn, callback) → Promise<any>Ejecuta el callback dentro de una transacción; solo JS
executeBatch(conn, statements) → Promise<PgBatchResult>Varias sentencias en una única transacción
copyFrom(conn, table, rows, options?) → Promise<PgCopyResult>Inserción por lotes mediante protocolo COPY
copyTo(conn, query, options?) → Promise<string[][]>Exportación por lotes mediante protocolo COPY
listDatabases(conn) → Promise<string[]>Lista nombres de bases no plantilla
listSchemas(conn, options?) → Promise<string[]>Lista nombres de esquema
listTables(conn, schema?) → Promise<PgTableInfo[]>Lista tablas y vistas con conteos de filas
describeTable(conn, table, schema?) → Promise<PgColumnInfo[]>Metadatos de columnas: tipos, nulabilidad, valores por defecto y PK
listIndexes(conn, table, schema?) → Promise<PgIndexInfo[]>Metadatos de índices con definiciones
listConstraints(conn, table, schema?) → Promise<PgConstraintInfo[]>Metadatos de restricciones: PK, FK, UNIQUE, CHECK

PgExecuteResult:

{
rowsAffected: number
}

PgTableInfo:

{
name: string
schema: string
type: string // "table" or "view"
estimatedRows: number // from pg_class.reltuples
}

PgColumnInfo:

{
name: string
type: string // e.g., "integer", "character varying", "timestamp with time zone"
nullable: boolean
defaultValue: string | null
isPrimaryKey: boolean
maxLength: number | null // for string types
}

PgIndexInfo:

{
name: string
columns: string[]
isUnique: boolean
isPrimary: boolean
definition: string // full CREATE INDEX statement
}

PgConstraintInfo:

{
name: string
type: string // "PRIMARY KEY", "FOREIGN KEY", "UNIQUE", "CHECK"
columns: string // comma-separated column names
definition: string // constraint definition
}

PgBatchStatement:

{
sql: string // SQL with $1, $2, ... positional parameters
params?: any[] // parameter values
}

PgBatchResult:

{
results: PgExecuteResult[] // per-statement rowsAffected counts
}

PgTransactionProxy — se pasa al callback de transaction:

{
query: (sql, params?) => Promise<object[]>
queryOne: (sql, params?) => Promise<object | null>
execute: (sql, params?) => Promise<PgExecuteResult>
scalar: (sql, params?) => Promise<any>
}

PgCopyFromOptions:

{
columns?: string[] // column names to map row values to (in order)
schema?: string // default: "public"
}

PgCopyToOptions:

{
schema?: string // default: "public" (only for table names, not SQL queries)
}

PgCopyResult:

{
rowsCopied: number
}

PgSchemaOptions:

{
includeSystem?: boolean // include pg_* and information_schema (default: false)
}
async function main() {
const conn = "my-postgres"; // secret name with connection string
try {
// Query with parameters
const rows = await g.postgres.query(conn,
"SELECT id, name, price FROM products WHERE price < $1 ORDER BY price",
[20.00]
);
g.log("Found " + rows.length + " products");
// Transaction with callback
const result = await g.postgres.transaction(conn, async (tx) => {
await tx.execute("INSERT INTO orders (product_id, qty) VALUES ($1, $2)", [42, 3]);
await tx.execute("UPDATE products SET stock = stock - $1 WHERE id = $2", [3, 42]);
return await tx.scalar("SELECT count(*) FROM orders");
});
g.log("Total orders: " + result);
// Bulk insert via COPY (much faster than row-by-row INSERT)
const copyResult = await g.postgres.copyFrom(conn, "products", [
["Widget A", 9.99, 100],
["Widget B", 14.99, 50],
["Widget C", 24.99, 25]
], { columns: ["name", "price", "stock"] });
g.log("Imported " + copyResult.rowsCopied + " rows");
} catch (e) {
g.log("Error: " + e.message);
}
}


Soporte nativo para consultar e indexar datos en clústeres Elasticsearch externos mediante Elastic.Clients.Elasticsearch. El parámetro conn es el nombre de una credencial que contiene el objeto JSON de conexión (url y opcionalmente apiKey o username/password). Bloqueado para scripts originados por MCP.

MétodoFirmaAsyncDescripción
ping(conn) → Promise<boolean>Verifica la conexión al clúster; devuelve true si tiene éxito
info(conn) → Promise<ElasticsearchInfoResult>Recupera metadatos del clúster: nombre, versión, tagline, etc.
createIndex(conn, indexName, mappingJson?) → Promise<boolean>Crea un índice con un mapping JSON opcional
deleteIndex(conn, indexName) → Promise<boolean>Elimina un índice existente
index(conn, indexName, id, document) → Promise<boolean>Indexa un único objeto JS en el clúster
get(conn, indexName, id) → Promise<any>Recupera un documento por ID; devuelve el objeto _source parseado
bulk(conn, indexName, documents, chunkSize?) → Promise<ElasticsearchBulkResult>Ingesta de alto rendimiento; divide arrays grandes para evitar límites de payload
search(conn, indexName, queryDsl) → Promise<any>Ejecuta un Query DSL JSON bruto como cadena u objeto JS y devuelve hits deserializados

ElasticsearchInfoResult:

{
name: string
clusterName: string
clusterUuid: string
version: string
tagline: string
}

ElasticsearchBulkResult:

{
total: number
successful: number
failed: number
}
async function main() {
const conn = "my-elastic"; // secret name
// Check connection
const isUp = await g.elasticsearch.ping(conn);
if (!isUp) return g.log("Connection failed");
// Bulk index documents
const docs = [{ id: 1, text: "A" }, { id: 2, text: "B" }];
const bulkRes = await g.elasticsearch.bulk(conn, "products", docs, 1000);
g.log(`Indexed ${bulkRes.successful} out of ${bulkRes.total}`);
// Query DSL search
const searchRes = await g.elasticsearch.search(conn, "products", {
query: { match_all: {} }
});
g.log(`Total hits: ${searchRes.hits.total.value}`);
}