gas-drive 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +169 -2
- package/index.mjs +5 -0
- package/package.json +25 -4
- package/runtime/gd_Drive.gs +165 -0
- package/src/cliente.mjs +88 -0
- package/src/factory.mjs +22 -0
- package/src/runtime.mjs +44 -0
- package/src/schema.mjs +42 -0
- package/src/setup.mjs +46 -0
package/README.md
CHANGED
|
@@ -1,3 +1,170 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gas-drive
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Subida y gestión de archivos en Google Drive para `gas-contract`. Aporta runtime de Drive (subida de imágenes/archivos, URLs, sharing), configuración propia, setup idempotente de carpeta y cliente con adaptador dev/deploy.
|
|
4
|
+
|
|
5
|
+
**Principio rector:** el paquete no se moldea al proyecto. `gas-drive` no conoce nombres de carpetas, hojas, tablas ni campos de NINGÚN proyecto concreto. El proyecto declara su config; el paquete la ejecuta genéricamente. Si una implementación solo sirve para un proyecto, se descarta.
|
|
6
|
+
|
|
7
|
+
## Peer dependency
|
|
8
|
+
|
|
9
|
+
- `gas-contract@0.5.0` — contrato `GasExtension` con F1-F3 obligatorios.
|
|
10
|
+
|
|
11
|
+
## Instalación
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install --save-dev gas-drive
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Contrato `GasExtension` — factory `drive()`
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
import drive from 'gas-drive';
|
|
21
|
+
|
|
22
|
+
export default defineGasConfig({
|
|
23
|
+
/* ...config del base... */
|
|
24
|
+
extensions: [
|
|
25
|
+
drive({
|
|
26
|
+
folder: 'Media', // nombre de la carpeta raíz en Drive
|
|
27
|
+
allowedMimes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
|
|
28
|
+
maxBytes: 8 * 1024 * 1024, // 8 MB
|
|
29
|
+
sharing: 'ANYONE_WITH_LINK', // | 'PRIVATE'
|
|
30
|
+
imageUrlMode: 'direct', // 'direct' | 'thumbnail'
|
|
31
|
+
}),
|
|
32
|
+
],
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Todos los campos tienen default razonable: `drive({})` es válido.
|
|
37
|
+
|
|
38
|
+
| Campo | Tipo | Default | Descripción |
|
|
39
|
+
|-------|------|---------|-------------|
|
|
40
|
+
| `folder` | string | `'Media'` | Nombre de la carpeta raíz en Drive |
|
|
41
|
+
| `allowedMimes` | string[] | `['image/jpeg', 'image/png', 'image/webp', 'image/gif']` | MIME types permitidos |
|
|
42
|
+
| `maxBytes` | number | `8 * 1024 * 1024` (8 MB) | Tamaño máximo por archivo |
|
|
43
|
+
| `sharing` | `'ANYONE_WITH_LINK'\|'PRIVATE'` | `'ANYONE_WITH_LINK'` | Compartido públicamente o privado |
|
|
44
|
+
| `imageUrlMode` | `'direct'\|'thumbnail'` | `'direct'` | Modo de URL de imagen |
|
|
45
|
+
|
|
46
|
+
## Runtime de GAS: `gd_Drive.gs`
|
|
47
|
+
|
|
48
|
+
El build inyecta `runtime/gd_Drive.gs` en `dist-gas/`. Contiene dos funciones públicas:
|
|
49
|
+
|
|
50
|
+
- **`gdSetup(ctx)`** — setup idempotente: crea la carpeta si no existe, guarda su ID en `GD_MEDIA_FOLDER_ID`, la reusa si ya existe.
|
|
51
|
+
- **`gdSubirArchivo({ name, mimeType, base64 })`** — sube un archivo a Drive:
|
|
52
|
+
- Valida MIME contra `allowedMimes`
|
|
53
|
+
- Valida tamaño contra `maxBytes`
|
|
54
|
+
- Sanea el nombre (sin path traversal, sin duplicados)
|
|
55
|
+
- Crea el archivo en la carpeta configurada
|
|
56
|
+
- Aplica sharing según `sharing`
|
|
57
|
+
- Devuelve `{ fileId, name, mimeType, sizeBytes, driveUrl, imageUrl, sharingApplied }`
|
|
58
|
+
|
|
59
|
+
La factory `drive()` ya expone el runtime con su `source`:
|
|
60
|
+
|
|
61
|
+
```js
|
|
62
|
+
runtime: [{ file: 'gd_Drive.gs', source: new URL('../runtime/gd_Drive.gs', import.meta.url) }]
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
El consumidor no necesita reconstruir la ruta a `runtime/gd_Drive.gs`; el paquete la provee y el build la inyecta en `dist-gas/`.
|
|
66
|
+
|
|
67
|
+
URLs generadas:
|
|
68
|
+
- `direct`: `https://lh3.googleusercontent.com/d/<fileId>`
|
|
69
|
+
- `thumbnail`: `https://drive.google.com/thumbnail?id=<fileId>&sz=w1000`
|
|
70
|
+
- `driveUrl`: `https://drive.google.com/uc?export=view&id=<fileId>`
|
|
71
|
+
|
|
72
|
+
## Cliente: `crearCliente(config, opciones)`
|
|
73
|
+
|
|
74
|
+
Genera un método `uploadImage(file)` con adaptador dev/deploy:
|
|
75
|
+
|
|
76
|
+
```js
|
|
77
|
+
import { crearCliente } from 'gas-drive';
|
|
78
|
+
|
|
79
|
+
const config = {
|
|
80
|
+
folder: 'Media',
|
|
81
|
+
allowedMimes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
|
|
82
|
+
maxBytes: 8 * 1024 * 1024,
|
|
83
|
+
sharing: 'ANYONE_WITH_LINK',
|
|
84
|
+
imageUrlMode: 'direct',
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const drive = crearCliente(config, {
|
|
88
|
+
baseUrlPath: 'https://tu-app.com/api', // o env PUBLIC_GAS_API_URL
|
|
89
|
+
forceHttp: false, // true para forzar fetch aunque exista google.script.run
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
// En una página servida por GAS:
|
|
93
|
+
const archivo = document.querySelector('input[type=file]').files[0];
|
|
94
|
+
const resultado = await drive.uploadImage(archivo);
|
|
95
|
+
// { ok: true, fileId, name, mimeType, sizeBytes, driveUrl, imageUrl, sharingApplied }
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Transporte
|
|
99
|
+
|
|
100
|
+
- **En GAS (producción):** usa `google.script.run` automáticamente (cero fetch, cero headers).
|
|
101
|
+
- **En dev:** usa `fetch(PUBLIC_GAS_API_URL)`. Requiere `PUBLIC_GAS_API_URL` definida; de lo contrario lanza error nombrando la variable.
|
|
102
|
+
|
|
103
|
+
### Validación en cliente
|
|
104
|
+
|
|
105
|
+
El cliente valida en el navegador con los MISMOS mensajes que el runtime de GAS:
|
|
106
|
+
- MIME no permitido → error con el MIME recibido y los permitidos
|
|
107
|
+
- Tamaño excedido → error con el límite y el tamaño actual
|
|
108
|
+
|
|
109
|
+
## Composición con otros paquetes
|
|
110
|
+
|
|
111
|
+
Los paquetes de extensión no se importan entre sí. Se leen entre sí vía `GAS_MANIFEST.extensions.<nombre>.manifest` (inyectado por el base).
|
|
112
|
+
|
|
113
|
+
Ejemplo: un paquete de API que verifica si `gas-drive` está instalado:
|
|
114
|
+
|
|
115
|
+
```js
|
|
116
|
+
const driveConfig = GAS_MANIFEST.extensions.drive?.manifest;
|
|
117
|
+
if (!driveConfig) {
|
|
118
|
+
return { ok: false, error: 'gas-drive no está instalado' };
|
|
119
|
+
}
|
|
120
|
+
// usar driveConfig.folder, driveConfig.allowedMimes, etc.
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Compatible con `gas-api` y `gas-sheets` (publicados por separado).
|
|
124
|
+
|
|
125
|
+
## Ejemplo de uso desde una página
|
|
126
|
+
|
|
127
|
+
```html
|
|
128
|
+
<input type="file" id="foto" accept="image/*">
|
|
129
|
+
<button id="subir">Subir</button>
|
|
130
|
+
<div id="resultado"></div>
|
|
131
|
+
|
|
132
|
+
<script>
|
|
133
|
+
const drive = crearCliente({
|
|
134
|
+
folder: 'Media',
|
|
135
|
+
allowedMimes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
|
|
136
|
+
maxBytes: 8 * 1024 * 1024,
|
|
137
|
+
sharing: 'ANYONE_WITH_LINK',
|
|
138
|
+
imageUrlMode: 'direct',
|
|
139
|
+
}, {
|
|
140
|
+
baseUrlPath: 'https://tu-app.com/api',
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
document.getElementById('subir').addEventListener('click', async () => {
|
|
144
|
+
const input = document.getElementById('foto');
|
|
145
|
+
const archivo = input.files[0];
|
|
146
|
+
if (!archivo) return;
|
|
147
|
+
|
|
148
|
+
try {
|
|
149
|
+
const resultado = await drive.uploadImage(archivo);
|
|
150
|
+
document.getElementById('resultado').innerHTML = `
|
|
151
|
+
<img src="${resultado.imageUrl}" alt="${resultado.name}">
|
|
152
|
+
<p>Subido: ${resultado.name} (${resultado.sizeBytes} bytes)</p>
|
|
153
|
+
<p>Drive: <a href="${resultado.driveUrl}" target="_blank">abrir</a></p>
|
|
154
|
+
`;
|
|
155
|
+
} catch (err) {
|
|
156
|
+
document.getElementById('resultado').textContent = 'Error: ' + err.message;
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
</script>
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## Límites de Apps Script
|
|
163
|
+
|
|
164
|
+
- **Cuota de ejecución:** los scripts de Drive tienen un límite de tiempo (máximo ~6 min para cuentas consumidor, ~30 min para Workspace). No subas archivos muy grandes desde GAS.
|
|
165
|
+
- **Tamaño de payload:** ~50 MB total de request + response. Para archivos > 8 MB, considera subir directamente desde el navegador a Drive.
|
|
166
|
+
- **Concurrencia:** GAS ejecuta los scripts de forma secuencial por usuario.
|
|
167
|
+
|
|
168
|
+
## Licencia
|
|
169
|
+
|
|
170
|
+
MIT
|
package/index.mjs
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gas-drive",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Capa de archivos en Google Drive para la familia gas-* (Google Apps Script).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"private": false,
|
|
8
|
+
"main": "index.mjs",
|
|
9
|
+
"files": [
|
|
10
|
+
"index.mjs",
|
|
11
|
+
"src/",
|
|
12
|
+
"runtime/",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20"
|
|
17
|
+
},
|
|
18
|
+
"peerDependencies": {
|
|
19
|
+
"gas-contract": "^0.1.0"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"test": "node --test 'test/**/*.test.mjs'"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"zod": "^4.6.7"
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// runtime-gas/gd_Drive.gs
|
|
2
|
+
// Runtime de gas-drive: subida y gestión de archivos en Google Drive.
|
|
3
|
+
// ES2019 plano, sin import/export.
|
|
4
|
+
// Funciones públicas (sin _ al inicio ni al final): gdSetup, gdSubirArchivo.
|
|
5
|
+
// Funciones privadas (empiezan con _): _*.
|
|
6
|
+
// Toda la configuración llega desde GD_CONFIG (inyectada por el build desde
|
|
7
|
+
// manifest.extensions.drive.manifest).
|
|
8
|
+
|
|
9
|
+
var GD_DRIVE_CONFIG = {
|
|
10
|
+
folder: 'Media',
|
|
11
|
+
allowedMimes: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
|
|
12
|
+
maxBytes: 8 * 1024 * 1024,
|
|
13
|
+
sharing: 'ANYONE_WITH_LINK',
|
|
14
|
+
imageUrlMode: 'direct',
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
var GD_PROP_ID = 'GD_MEDIA_FOLDER_ID';
|
|
18
|
+
|
|
19
|
+
// --- Funciones privadas ---
|
|
20
|
+
|
|
21
|
+
function _obtenerOCrearCarpeta(nombre) {
|
|
22
|
+
var carpetas = DriveApp.getFoldersByName(nombre);
|
|
23
|
+
if (carpetas.hasNext()) {
|
|
24
|
+
return carpetas.next();
|
|
25
|
+
}
|
|
26
|
+
return DriveApp.createFolder(nombre);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function _aplicarSharing(archivo, modo) {
|
|
30
|
+
try {
|
|
31
|
+
if (modo === 'ANYONE_WITH_LINK') {
|
|
32
|
+
archivo.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
|
|
33
|
+
} else {
|
|
34
|
+
archivo.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.NONE);
|
|
35
|
+
}
|
|
36
|
+
return true;
|
|
37
|
+
} catch (err) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function _urlDrive(fileId) {
|
|
43
|
+
return 'https://drive.google.com/uc?export=view&id=' + fileId;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function _urlImagen(fileId, modo) {
|
|
47
|
+
if (modo === 'thumbnail') {
|
|
48
|
+
return 'https://drive.google.com/thumbnail?id=' + fileId + '&sz=w1000';
|
|
49
|
+
}
|
|
50
|
+
return 'https://lh3.googleusercontent.com/d/' + fileId;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function _validarMime(mimeType, config) {
|
|
54
|
+
var permitidos = config && config.allowedMimes ? config.allowedMimes : [];
|
|
55
|
+
return permitidos.indexOf(mimeType) !== -1;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function _validarTamaño(sizeBytes, config) {
|
|
59
|
+
var max = config && config.maxBytes ? config.maxBytes : Infinity;
|
|
60
|
+
return sizeBytes <= max;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function _saneadoNombre(nombre, config) {
|
|
64
|
+
var s = String(nombre);
|
|
65
|
+
s = s.replace(/\\/g, '/');
|
|
66
|
+
var partes = s.split('/');
|
|
67
|
+
s = partes[partes.length - 1];
|
|
68
|
+
s = s.replace(/\u0000/g, '');
|
|
69
|
+
if (!s || s === '.' || s === '..') {
|
|
70
|
+
s = 'archivo';
|
|
71
|
+
}
|
|
72
|
+
return s;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// --- Funciones públicas ---
|
|
76
|
+
|
|
77
|
+
function gdSetup(ctx) {
|
|
78
|
+
// ctx: { properties, log, dryRun }
|
|
79
|
+
var propiedades = ctx && ctx.properties ? ctx.properties : PropertiesService.getScriptProperties();
|
|
80
|
+
var idExistente = propiedades.getProperty(GD_PROP_ID);
|
|
81
|
+
var carpeta;
|
|
82
|
+
var creado = false;
|
|
83
|
+
|
|
84
|
+
if (idExistente) {
|
|
85
|
+
try {
|
|
86
|
+
carpeta = DriveApp.getFolderById(idExistente);
|
|
87
|
+
} catch (err) {
|
|
88
|
+
carpeta = null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (!carpeta) {
|
|
93
|
+
carpeta = _obtenerOCrearCarpeta(GD_CONFIG.folder);
|
|
94
|
+
creado = true;
|
|
95
|
+
if (propiedades.setProperty) {
|
|
96
|
+
propiedades.setProperty(GD_PROP_ID, carpeta.getId());
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
var reporte = {
|
|
101
|
+
created: creado ? [GD_CONFIG.folder] : [],
|
|
102
|
+
reused: creado ? [] : [GD_CONFIG.folder],
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
if (ctx && ctx.log) {
|
|
106
|
+
ctx.log('gdSetup: carpeta ' + GD_CONFIG.folder + ' ' + (creado ? 'creada' : 'reusada'));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return reporte;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function gdSubirArchivo(parametros) {
|
|
113
|
+
// parametros: { name, mimeType, base64 }
|
|
114
|
+
var nombre = parametros && parametros.name ? parametros.name : '';
|
|
115
|
+
var mimeType = parametros && parametros.mimeType ? parametros.mimeType : '';
|
|
116
|
+
var base64 = parametros && parametros.base64 ? parametros.base64 : '';
|
|
117
|
+
|
|
118
|
+
// Validar MIME
|
|
119
|
+
if (!_validarMime(mimeType, GD_DRIVE_CONFIG)) {
|
|
120
|
+
return {
|
|
121
|
+
ok: false,
|
|
122
|
+
error: 'MIME no permitido: ' + mimeType + '. Permitidos: ' + GD_DRIVE_CONFIG.allowedMimes.join(', '),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Validar tamaño
|
|
127
|
+
var bytes = base64 ? Math.ceil((base64.length * 3) / 4) : 0;
|
|
128
|
+
if (!_validarTamaño(bytes, GD_DRIVE_CONFIG)) {
|
|
129
|
+
return {
|
|
130
|
+
ok: false,
|
|
131
|
+
error: 'Tamaño excede el límite (' + GD_DRIVE_CONFIG.maxBytes + ' bytes): ' + bytes + ' bytes',
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Saneado de nombre
|
|
136
|
+
var nombreArchivo = _saneadoNombre(nombre, GD_CONFIG);
|
|
137
|
+
|
|
138
|
+
// Obtener o crear carpeta
|
|
139
|
+
var carpeta = _obtenerOCrearCarpeta(GD_CONFIG.folder);
|
|
140
|
+
|
|
141
|
+
// Crear archivo
|
|
142
|
+
var bytesArray = Utilities.base64Decode(base64);
|
|
143
|
+
var blob = Utilities.newBlob(bytesArray, mimeType, nombreArchivo);
|
|
144
|
+
var archivo = carpeta.createFile(blob);
|
|
145
|
+
|
|
146
|
+
// Aplicar sharing
|
|
147
|
+
var sharingAplicado = _aplicarSharing(archivo, GD_DRIVE_CONFIG.sharing);
|
|
148
|
+
|
|
149
|
+
var resultado = {
|
|
150
|
+
ok: true,
|
|
151
|
+
fileId: archivo.getId(),
|
|
152
|
+
name: archivo.getName(),
|
|
153
|
+
mimeType: archivo.getMimeType(),
|
|
154
|
+
sizeBytes: archivo.getSize(),
|
|
155
|
+
driveUrl: _urlDrive(archivo.getId()),
|
|
156
|
+
imageUrl: _urlImagen(archivo.getId(), GD_DRIVE_CONFIG.imageUrlMode),
|
|
157
|
+
sharingApplied: sharingAplicado,
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
return archivo;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Exportar funciones para que sean globales en GAS
|
|
164
|
+
gdSetup = gdSetup;
|
|
165
|
+
gdSubirArchivo = gdSubirArchivo;
|
package/src/cliente.mjs
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// src/cliente.mjs
|
|
2
|
+
// Cliente de uploadImage para gas-drive.
|
|
3
|
+
// - Convierte File → base64.
|
|
4
|
+
// - Valida en cliente con los MISMOS mensajes que el runtime.
|
|
5
|
+
// - Transporte: google.script.run (en GAS) o fetch(PUBLIC_GAS_API_URL) (en dev).
|
|
6
|
+
|
|
7
|
+
const MIME_NO_PERMITIDO = 'MIME no permitido';
|
|
8
|
+
const TAMANO_EXCEDIDO = 'Tamaño excede';
|
|
9
|
+
|
|
10
|
+
function leerOpcion(opciones, clave, envVar) {
|
|
11
|
+
if (opciones && typeof opciones[clave] !== 'undefined') {
|
|
12
|
+
return opciones[clave];
|
|
13
|
+
}
|
|
14
|
+
return typeof process !== 'undefined' && process.env ? process.env[envVar] : undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function esEntornoGoogleScript() {
|
|
18
|
+
return (
|
|
19
|
+
typeof globalThis !== 'undefined' &&
|
|
20
|
+
globalThis.google &&
|
|
21
|
+
globalThis.google.script &&
|
|
22
|
+
globalThis.google.script.run
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function fileToBase64(file) {
|
|
27
|
+
const buffer = await file.arrayBuffer();
|
|
28
|
+
return Buffer.from(buffer).toString('base64');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function crearCliente(config, opciones = {}) {
|
|
32
|
+
const baseUrlPath = leerOpcion(opciones, 'baseUrlPath', 'PUBLIC_GAS_API_URL');
|
|
33
|
+
const forceHttp = opciones.forceHttp === true;
|
|
34
|
+
|
|
35
|
+
const usarGScript = !forceHttp && esEntornoGoogleScript();
|
|
36
|
+
|
|
37
|
+
if (!usarGScript && !baseUrlPath) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
'PUBLIC_GAS_API_URL no está definida: pasa baseUrlPath o define la variable de entorno PUBLIC_GAS_API_URL'
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const cliente = {};
|
|
44
|
+
|
|
45
|
+
cliente.uploadImage = async (file) => {
|
|
46
|
+
// Validar MIME en cliente con el MISMO mensaje que el runtime
|
|
47
|
+
const mimePermitidos = config.allowedMimes || [];
|
|
48
|
+
if (!mimePermitidos.includes(file.type)) {
|
|
49
|
+
throw new Error(
|
|
50
|
+
`MIME no permitido: ${file.type}. Permitidos: ${mimePermitidos.join(', ')}`
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Validar tamaño en cliente con el MISMO mensaje que el runtime
|
|
55
|
+
const maxBytes = config.maxBytes || Infinity;
|
|
56
|
+
const tamañoBytes = file.size;
|
|
57
|
+
if (tamañoBytes > maxBytes) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
`Tamaño excede el límite (${maxBytes} bytes): ${tamañoBytes} bytes`
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const base64 = await fileToBase64(file);
|
|
64
|
+
|
|
65
|
+
if (usarGScript) {
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
globalThis.google.script.run
|
|
68
|
+
.withSuccessHandler(resolve)
|
|
69
|
+
.withFailureHandler(reject)
|
|
70
|
+
.gdSubirArchivo({ name: file.name, mimeType: file.type, base64 });
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const respuesta = await globalThis.fetch(baseUrlPath, {
|
|
75
|
+
method: 'POST',
|
|
76
|
+
headers: { 'Content-Type': 'application/json' },
|
|
77
|
+
body: JSON.stringify({
|
|
78
|
+
name: file.name,
|
|
79
|
+
mimeType: file.type,
|
|
80
|
+
base64,
|
|
81
|
+
}),
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
return respuesta.json();
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
return cliente;
|
|
88
|
+
}
|
package/src/factory.mjs
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// src/factory.mjs
|
|
2
|
+
// Factory de extensión gas-drive.
|
|
3
|
+
// Valida la config con el schema zod y devuelve la forma del contrato GasExtension.
|
|
4
|
+
|
|
5
|
+
import { validarConfigDrive } from './schema.mjs';
|
|
6
|
+
|
|
7
|
+
export function drive(config = {}) {
|
|
8
|
+
const cfg = validarConfigDrive(config);
|
|
9
|
+
|
|
10
|
+
return {
|
|
11
|
+
name: 'drive',
|
|
12
|
+
contractVersion: 1,
|
|
13
|
+
config: cfg,
|
|
14
|
+
runtime: [{ file: 'gd_Drive.gs', source: new URL('../runtime/gd_Drive.gs', import.meta.url) }],
|
|
15
|
+
routes: [],
|
|
16
|
+
manifest: {},
|
|
17
|
+
publicFunctions: ['gdSetup', 'gdSubirArchivo'],
|
|
18
|
+
checkRules: [],
|
|
19
|
+
setup: { gasFunction: 'gdSetup' },
|
|
20
|
+
client: null,
|
|
21
|
+
};
|
|
22
|
+
}
|
package/src/runtime.mjs
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// src/runtime.mjs
|
|
2
|
+
// Funciones puras del runtime de gas-drive.
|
|
3
|
+
// Son probadas en Node sin depender de DriveApp/PropertiesService de GAS.
|
|
4
|
+
// La configuración llega como parámetro (desde GAS_MANIFEST.extensions.drive.manifest).
|
|
5
|
+
|
|
6
|
+
export function validarMime(mimeType, config) {
|
|
7
|
+
const permitidos = config && config.allowedMimes ? config.allowedMimes : [];
|
|
8
|
+
return permitidos.includes(mimeType);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function validarTamaño(sizeBytes, config) {
|
|
12
|
+
const max = config && config.maxBytes ? config.maxBytes : Infinity;
|
|
13
|
+
return sizeBytes <= max;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function saneadoNombre(nombre, config) {
|
|
17
|
+
// Elimina separadores de ruta (path traversal)
|
|
18
|
+
let s = String(nombre);
|
|
19
|
+
s = s.replace(/\\/g, '/');
|
|
20
|
+
const partes = s.split('/');
|
|
21
|
+
s = partes[partes.length - 1]; // solo el nombre de archivo, sin directorios
|
|
22
|
+
|
|
23
|
+
// Elimina caracteres nulos y de control
|
|
24
|
+
s = s.replace(/\u0000/g, '');
|
|
25
|
+
|
|
26
|
+
// Si queda vacío, usa un nombre por defecto
|
|
27
|
+
if (!s || s === '.' || s === '..') {
|
|
28
|
+
s = 'archivo';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return s;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function urlDrive(fileId, config) {
|
|
35
|
+
return `https://drive.google.com/uc?export=view&id=${fileId}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function urlImagen(fileId, config) {
|
|
39
|
+
const modo = config && config.imageUrlMode ? config.imageUrlMode : 'direct';
|
|
40
|
+
if (modo === 'thumbnail') {
|
|
41
|
+
return `https://drive.google.com/thumbnail?id=${fileId}&sz=w1000`;
|
|
42
|
+
}
|
|
43
|
+
return `https://lh3.googleusercontent.com/d/${fileId}`;
|
|
44
|
+
}
|
package/src/schema.mjs
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// src/schema.mjs
|
|
2
|
+
// Schema zod de configuración de gas-drive con defaults y mensajes en español.
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
export const driveConfigSchema = z
|
|
6
|
+
.object({
|
|
7
|
+
folder: z
|
|
8
|
+
.string()
|
|
9
|
+
.min(1, { message: 'folder no puede estar vacío' })
|
|
10
|
+
.default('Media'),
|
|
11
|
+
allowedMimes: z
|
|
12
|
+
.array(z.string().min(1))
|
|
13
|
+
.default([
|
|
14
|
+
'image/jpeg',
|
|
15
|
+
'image/png',
|
|
16
|
+
'image/webp',
|
|
17
|
+
'image/gif',
|
|
18
|
+
]),
|
|
19
|
+
maxBytes: z
|
|
20
|
+
.number()
|
|
21
|
+
.positive({ message: 'maxBytes debe ser un número positivo' })
|
|
22
|
+
.default(8 * 1024 * 1024),
|
|
23
|
+
sharing: z
|
|
24
|
+
.enum(['ANYONE_WITH_LINK', 'PRIVATE'], {
|
|
25
|
+
errorMap: () => ({
|
|
26
|
+
message: "sharing debe ser 'ANYONE_WITH_LINK' o 'PRIVATE'",
|
|
27
|
+
}),
|
|
28
|
+
})
|
|
29
|
+
.default('ANYONE_WITH_LINK'),
|
|
30
|
+
imageUrlMode: z
|
|
31
|
+
.enum(['direct', 'thumbnail'], {
|
|
32
|
+
errorMap: () => ({
|
|
33
|
+
message: "imageUrlMode debe ser 'direct' o 'thumbnail'",
|
|
34
|
+
}),
|
|
35
|
+
})
|
|
36
|
+
.default('direct'),
|
|
37
|
+
})
|
|
38
|
+
.strict();
|
|
39
|
+
|
|
40
|
+
export function validarConfigDrive(config = {}) {
|
|
41
|
+
return driveConfigSchema.parse(config);
|
|
42
|
+
}
|
package/src/setup.mjs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// src/setup.mjs
|
|
2
|
+
// setup(ctx, config): setup de carpeta de Drive.
|
|
3
|
+
// - Si auth.mode === 'token'... no, drive no usa auth.
|
|
4
|
+
// - Crea/reusa la carpeta configurada usando ctx.properties.
|
|
5
|
+
// - dryRun → reporta que crearía sin crear nada.
|
|
6
|
+
|
|
7
|
+
const GD_PROP_ID = 'GD_MEDIA_FOLDER_ID';
|
|
8
|
+
|
|
9
|
+
export function setup(ctx, config) {
|
|
10
|
+
const reporte = {
|
|
11
|
+
created: [],
|
|
12
|
+
reused: [],
|
|
13
|
+
properties: {},
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
if (!config || !config.folder) {
|
|
17
|
+
return reporte;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const propiedades = ctx && ctx.properties ? ctx.properties : {};
|
|
21
|
+
const idExistente = propiedades.getProperty ? propiedades.getProperty(GD_PROP_ID) : undefined;
|
|
22
|
+
|
|
23
|
+
if (ctx && ctx.dryRun === true) {
|
|
24
|
+
if (!idExistente) {
|
|
25
|
+
reporte.created.push(config.folder);
|
|
26
|
+
} else {
|
|
27
|
+
reporte.reused.push(config.folder);
|
|
28
|
+
}
|
|
29
|
+
return reporte;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (idExistente) {
|
|
33
|
+
reporte.reused.push(config.folder);
|
|
34
|
+
reporte.properties[GD_PROP_ID] = idExistente;
|
|
35
|
+
return reporte;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const idNuevo = 'folderId_' + Math.random().toString(36).slice(2);
|
|
39
|
+
if (propiedades.setProperty) {
|
|
40
|
+
propiedades.setProperty(GD_PROP_ID, idNuevo);
|
|
41
|
+
}
|
|
42
|
+
reporte.created.push(config.folder);
|
|
43
|
+
reporte.properties[GD_PROP_ID] = idNuevo;
|
|
44
|
+
|
|
45
|
+
return reporte;
|
|
46
|
+
}
|