@surnie/plugin-kit 0.0.0-stage → 0.2.1
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/LICENSE +21 -0
- package/README.md +29 -2
- package/dist/cli.js +2521 -0
- package/package.json +28 -4
- package/schema/manifest.schema.json +1029 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,2521 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { existsSync as existsSync7, readFileSync as readFileSync7 } from "node:fs";
|
|
5
|
+
|
|
6
|
+
// ../../scripts/signing-key.mjs
|
|
7
|
+
import { createPrivateKey, generateKeyPairSync } from "node:crypto";
|
|
8
|
+
import { Decrypter, Encrypter, armor } from "age-encryption";
|
|
9
|
+
var KEY_FILE_BEGIN = "-----BEGIN AGE ENCRYPTED FILE-----";
|
|
10
|
+
var MIN_PASSWORD_LENGTH = 12;
|
|
11
|
+
var DEFAULT_LOG_N = 18;
|
|
12
|
+
var SigningKeyError = class extends Error {
|
|
13
|
+
constructor(message) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = "SigningKeyError";
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
var fail = (message) => {
|
|
19
|
+
throw new SigningKeyError(message);
|
|
20
|
+
};
|
|
21
|
+
function isEncryptedKeyFile(text2) {
|
|
22
|
+
return typeof text2 === "string" && text2.trimStart().startsWith(KEY_FILE_BEGIN);
|
|
23
|
+
}
|
|
24
|
+
function assertPassword(password) {
|
|
25
|
+
if (typeof password !== "string" || password.length < MIN_PASSWORD_LENGTH) {
|
|
26
|
+
fail(`La contrase\xF1a tiene que tener al menos ${MIN_PASSWORD_LENGTH} caracteres.`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function ed25519Pem(privateKeyPem) {
|
|
30
|
+
let key;
|
|
31
|
+
try {
|
|
32
|
+
key = createPrivateKey(privateKeyPem);
|
|
33
|
+
} catch {
|
|
34
|
+
return fail("No es una clave privada legible (\xBFest\xE1 ya cifrada?).");
|
|
35
|
+
}
|
|
36
|
+
if (key.asymmetricKeyType !== "ed25519") fail(`La clave es ${key.asymmetricKeyType}, no Ed25519.`);
|
|
37
|
+
return key.export({ type: "pkcs8", format: "pem" });
|
|
38
|
+
}
|
|
39
|
+
async function encryptSigningKey(privateKeyPem, password, { logN = DEFAULT_LOG_N } = {}) {
|
|
40
|
+
assertPassword(password);
|
|
41
|
+
const pem = ed25519Pem(privateKeyPem);
|
|
42
|
+
const e = new Encrypter();
|
|
43
|
+
e.setPassphrase(password);
|
|
44
|
+
if (logN !== DEFAULT_LOG_N) e.setScryptWorkFactor(logN);
|
|
45
|
+
return armor.encode(await e.encrypt(pem));
|
|
46
|
+
}
|
|
47
|
+
async function decryptSigningKey(text2, password) {
|
|
48
|
+
if (!isEncryptedKeyFile(text2)) fail("La clave no est\xE1 cifrada: hay que cifrarla antes de usarla.");
|
|
49
|
+
let bytes;
|
|
50
|
+
try {
|
|
51
|
+
bytes = armor.decode(text2.trim());
|
|
52
|
+
} catch {
|
|
53
|
+
return fail("El fichero de la clave est\xE1 da\xF1ado.");
|
|
54
|
+
}
|
|
55
|
+
const d = new Decrypter();
|
|
56
|
+
d.addPassphrase(password);
|
|
57
|
+
let pem;
|
|
58
|
+
try {
|
|
59
|
+
pem = await d.decrypt(bytes, "text");
|
|
60
|
+
} catch {
|
|
61
|
+
return fail("No se puede abrir la clave: \xBFcontrase\xF1a incorrecta?");
|
|
62
|
+
}
|
|
63
|
+
return ed25519Pem(pem);
|
|
64
|
+
}
|
|
65
|
+
async function generateEncryptedSigningKey(password, options2) {
|
|
66
|
+
const { privateKey } = generateKeyPairSync("ed25519");
|
|
67
|
+
const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" });
|
|
68
|
+
return { file: await encryptSigningKey(privateKeyPem, password, options2), privateKeyPem };
|
|
69
|
+
}
|
|
70
|
+
function promptHidden(prompt, { input = process.stdin, output = process.stderr } = {}) {
|
|
71
|
+
if (!input.isTTY) return Promise.reject(new SigningKeyError("No hay terminal para pedir la contrase\xF1a."));
|
|
72
|
+
return new Promise((resolve5, reject) => {
|
|
73
|
+
output.write(prompt);
|
|
74
|
+
let value = "";
|
|
75
|
+
input.setRawMode(true);
|
|
76
|
+
input.resume();
|
|
77
|
+
input.setEncoding("utf8");
|
|
78
|
+
const finish = (err) => {
|
|
79
|
+
input.setRawMode(false);
|
|
80
|
+
input.pause();
|
|
81
|
+
input.off("data", onData);
|
|
82
|
+
output.write("\n");
|
|
83
|
+
if (err) reject(err);
|
|
84
|
+
else resolve5(value);
|
|
85
|
+
};
|
|
86
|
+
const onData = (chunk) => {
|
|
87
|
+
for (const ch of chunk) {
|
|
88
|
+
if (ch === "\r" || ch === "\n") return finish();
|
|
89
|
+
if (ch === "") return finish(new SigningKeyError("Cancelado."));
|
|
90
|
+
if (ch === "\x7F" || ch === "\b") value = value.slice(0, -1);
|
|
91
|
+
else if (ch >= " ") value += ch;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
input.on("data", onData);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
async function readPassword({ envVar, prompt, confirm = false, env = process.env, ask = promptHidden }) {
|
|
98
|
+
const fromEnv = envVar ? env[envVar] : void 0;
|
|
99
|
+
if (fromEnv !== void 0 && fromEnv !== "") {
|
|
100
|
+
if (confirm) assertPassword(fromEnv);
|
|
101
|
+
return fromEnv;
|
|
102
|
+
}
|
|
103
|
+
let password;
|
|
104
|
+
try {
|
|
105
|
+
password = await ask(prompt);
|
|
106
|
+
} catch (err) {
|
|
107
|
+
if (err instanceof SigningKeyError && envVar && /terminal/.test(err.message)) {
|
|
108
|
+
fail(`No hay terminal para pedir la contrase\xF1a: def\xEDnela en ${envVar}.`);
|
|
109
|
+
}
|
|
110
|
+
throw err;
|
|
111
|
+
}
|
|
112
|
+
if (confirm) {
|
|
113
|
+
assertPassword(password);
|
|
114
|
+
if (await ask("Rep\xEDtela: ") !== password) fail("Las dos contrase\xF1as no coinciden.");
|
|
115
|
+
}
|
|
116
|
+
return password;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/build.ts
|
|
120
|
+
import { spawn } from "node:child_process";
|
|
121
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
122
|
+
import { builtinModules } from "node:module";
|
|
123
|
+
|
|
124
|
+
// src/node-compat.ts
|
|
125
|
+
var NODE_COMPAT_MODULES = [
|
|
126
|
+
"buffer",
|
|
127
|
+
"crypto",
|
|
128
|
+
"events",
|
|
129
|
+
"http",
|
|
130
|
+
"https",
|
|
131
|
+
"path",
|
|
132
|
+
"process",
|
|
133
|
+
"stream",
|
|
134
|
+
"string_decoder",
|
|
135
|
+
"timers",
|
|
136
|
+
"url",
|
|
137
|
+
"util"
|
|
138
|
+
];
|
|
139
|
+
function compatModuleOf(specifier) {
|
|
140
|
+
const name = specifier.startsWith("node:") ? specifier.slice(5) : specifier;
|
|
141
|
+
return NODE_COMPAT_MODULES.includes(name) ? name : null;
|
|
142
|
+
}
|
|
143
|
+
function requireBanner(required) {
|
|
144
|
+
const names = [...new Set(required)].sort();
|
|
145
|
+
if (!names.length) return void 0;
|
|
146
|
+
const imports = names.map((n) => `import * as __surnie_${n} from "node:${n}";`).join("\n");
|
|
147
|
+
const table = names.map((n) => `${JSON.stringify(n)}: __surnie_${n}, ${JSON.stringify(`node:${n}`)}: __surnie_${n}`).join(", ");
|
|
148
|
+
return `${imports}
|
|
149
|
+
const require = (n) => { const m = { ${table} }[n]; if (!m) throw new Error(\`require("\${n}") no est\xE1 disponible en un plugin.\`); return m.default ?? m; };`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// src/types.ts
|
|
153
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
154
|
+
import { dirname, join } from "node:path";
|
|
155
|
+
|
|
156
|
+
// src/manifest.ts
|
|
157
|
+
import { z } from "zod";
|
|
158
|
+
|
|
159
|
+
// src/cron.ts
|
|
160
|
+
var FIELDS = [
|
|
161
|
+
{ name: "minuto", min: 0, max: 59 },
|
|
162
|
+
{ name: "hora", min: 0, max: 23 },
|
|
163
|
+
{ name: "d\xEDa del mes", min: 1, max: 31 },
|
|
164
|
+
{ name: "mes", min: 1, max: 12 },
|
|
165
|
+
{ name: "d\xEDa de la semana", min: 0, max: 7 }
|
|
166
|
+
];
|
|
167
|
+
var NUM = /^\d{1,2}$/;
|
|
168
|
+
function parseField(text2, { name, min, max }) {
|
|
169
|
+
const out = /* @__PURE__ */ new Set();
|
|
170
|
+
for (const part of text2.split(",")) {
|
|
171
|
+
const [range, stepText, extra] = part.split("/");
|
|
172
|
+
if (extra !== void 0) return `${name}: "${part}" no es v\xE1lido.`;
|
|
173
|
+
let step = 1;
|
|
174
|
+
if (stepText !== void 0) {
|
|
175
|
+
if (!NUM.test(stepText) || Number(stepText) < 1) return `${name}: el paso de "${part}" tiene que ser un n\xFAmero mayor que 0.`;
|
|
176
|
+
step = Number(stepText);
|
|
177
|
+
}
|
|
178
|
+
let from;
|
|
179
|
+
let to;
|
|
180
|
+
if (range === "*") {
|
|
181
|
+
from = min;
|
|
182
|
+
to = max;
|
|
183
|
+
} else {
|
|
184
|
+
const [a, b, more] = range.split("-");
|
|
185
|
+
if (more !== void 0 || !NUM.test(a) || b !== void 0 && !NUM.test(b)) return `${name}: "${part}" no es v\xE1lido.`;
|
|
186
|
+
from = Number(a);
|
|
187
|
+
to = b === void 0 ? stepText === void 0 ? from : max : Number(b);
|
|
188
|
+
}
|
|
189
|
+
if (from < min || to > max || from > to) return `${name}: "${part}" se sale de ${min}-${max}.`;
|
|
190
|
+
for (let v = from; v <= to; v += step) out.add(v);
|
|
191
|
+
}
|
|
192
|
+
return out;
|
|
193
|
+
}
|
|
194
|
+
function parseCron(expr) {
|
|
195
|
+
const parts = expr.trim().split(/\s+/);
|
|
196
|
+
if (parts.length !== 5) return { error: "Cinco columnas separadas por espacios: minuto, hora, d\xEDa del mes, mes y d\xEDa de la semana." };
|
|
197
|
+
const sets = [];
|
|
198
|
+
for (let i = 0; i < 5; i++) {
|
|
199
|
+
const r = parseField(parts[i], FIELDS[i]);
|
|
200
|
+
if (typeof r === "string") return { error: r };
|
|
201
|
+
sets.push(r);
|
|
202
|
+
}
|
|
203
|
+
const dow = sets[4];
|
|
204
|
+
if (dow.has(7)) {
|
|
205
|
+
dow.delete(7);
|
|
206
|
+
dow.add(0);
|
|
207
|
+
}
|
|
208
|
+
return { minute: sets[0], hour: sets[1], dom: sets[2], month: sets[3], dow, domAny: parts[2] === "*", dowAny: parts[4] === "*" };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/manifest.ts
|
|
212
|
+
var PLUGIN_CONTRACT = 0;
|
|
213
|
+
var NAMESPACE_PATTERN = /^[a-z][a-z0-9]{2,15}$/;
|
|
214
|
+
var RESERVED_NAMESPACES = /* @__PURE__ */ new Set([
|
|
215
|
+
// Del motor y de la plataforma.
|
|
216
|
+
"surnie",
|
|
217
|
+
"engine",
|
|
218
|
+
"admin",
|
|
219
|
+
"api",
|
|
220
|
+
"system",
|
|
221
|
+
"core",
|
|
222
|
+
"plugin",
|
|
223
|
+
"plugins",
|
|
224
|
+
"setup",
|
|
225
|
+
"login",
|
|
226
|
+
// Primer tramo de las tablas de sistema.
|
|
227
|
+
"media",
|
|
228
|
+
"users",
|
|
229
|
+
"user",
|
|
230
|
+
"roles",
|
|
231
|
+
"sessions",
|
|
232
|
+
"view",
|
|
233
|
+
"app",
|
|
234
|
+
"themes",
|
|
235
|
+
"backups",
|
|
236
|
+
"webhooks",
|
|
237
|
+
"webhook",
|
|
238
|
+
"model",
|
|
239
|
+
"account"
|
|
240
|
+
]);
|
|
241
|
+
var SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
|
|
242
|
+
var IDENT = /^[a-z][a-zA-Z0-9_]*$/;
|
|
243
|
+
var SUFFIX = /^[a-z][a-zA-Z0-9_]*$/;
|
|
244
|
+
var PERMISSION_ID = /^[a-z][a-zA-Z0-9]{0,39}$/;
|
|
245
|
+
var text = (max, what) => z.string({ error: `${what}: tiene que ser un texto.` }).trim().min(1, { error: `${what}: no puede estar vac\xEDo.` }).max(max, { error: `${what}: como mucho ${max} caracteres.` });
|
|
246
|
+
function uniqueList(item, what) {
|
|
247
|
+
return z.array(item).min(1, { error: `${what}: al menos uno.` }).refine((list) => new Set(list).size === list.length, { error: `${what}: hay repetidos.` }).meta({ uniqueItems: true });
|
|
248
|
+
}
|
|
249
|
+
var HOST_LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/;
|
|
250
|
+
var TLD = /^(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/;
|
|
251
|
+
var LOCAL_SUFFIXES = ["localhost", "local", "internal", "intranet", "lan", "home", "arpa", "test", "invalid", "example"];
|
|
252
|
+
function isValidDomain(host) {
|
|
253
|
+
if (host.length > 253) return false;
|
|
254
|
+
const labels = host.split(".");
|
|
255
|
+
if (labels.length < 2 || !labels.every((l) => HOST_LABEL.test(l))) return false;
|
|
256
|
+
const tld = labels[labels.length - 1];
|
|
257
|
+
return TLD.test(tld) && !LOCAL_SUFFIXES.includes(tld);
|
|
258
|
+
}
|
|
259
|
+
var CONTENT_ACTIONS = ["read", "create", "update", "delete", "publish"];
|
|
260
|
+
var USER_FIELDS = ["name", "email", "locale", "createdAt"];
|
|
261
|
+
var permissionBase = {
|
|
262
|
+
id: z.string().regex(PERMISSION_ID, { error: "Id de permiso: letras y d\xEDgitos, empieza por min\xFAscula, hasta 40." }).meta({ description: "Id estable del permiso (no cambiarlo entre versiones): as\xED se sabe qu\xE9 es nuevo al actualizar." }),
|
|
263
|
+
/** Para qué lo quiere, en una frase: el admin lo lee antes de aceptar. */
|
|
264
|
+
purpose: text(200, "purpose").meta({ description: "Para qu\xE9 lo quiere el plugin, en una frase: el admin lo lee antes de aceptar." })
|
|
265
|
+
};
|
|
266
|
+
var contentPermission = z.strictObject({
|
|
267
|
+
kind: z.literal("content"),
|
|
268
|
+
...permissionBase,
|
|
269
|
+
actions: uniqueList(z.enum(CONTENT_ACTIONS, { error: `actions: solo ${CONTENT_ACTIONS.join(", ")}.` }), "actions")
|
|
270
|
+
}).meta({ description: "Contenido del proyecto: el admin elige al instalar a qu\xE9 colecciones se lo da." });
|
|
271
|
+
var usersPermission = z.strictObject({
|
|
272
|
+
kind: z.literal("users"),
|
|
273
|
+
...permissionBase,
|
|
274
|
+
fields: uniqueList(z.enum(USER_FIELDS, { error: `fields: solo ${USER_FIELDS.join(", ")}.` }), "fields")
|
|
275
|
+
}).meta({ description: "Leer campos de las cuentas del panel. Nunca la contrase\xF1a, el rol ni las sesiones." });
|
|
276
|
+
var networkPermission = z.strictObject({
|
|
277
|
+
kind: z.literal("network"),
|
|
278
|
+
...permissionBase,
|
|
279
|
+
domains: uniqueList(
|
|
280
|
+
z.string().refine(isValidDomain, { error: "domains: un dominio p\xFAblico, solo el nombre (p. ej. api.redsys.es)." }),
|
|
281
|
+
"domains"
|
|
282
|
+
)
|
|
283
|
+
}).meta({ description: "Dominios a los que el plugin podr\xE1 llamar (por la recepci\xF3n). Solo el nombre: api.ejemplo.com." });
|
|
284
|
+
var fieldsPermission = z.strictObject({
|
|
285
|
+
kind: z.literal("fields"),
|
|
286
|
+
...permissionBase,
|
|
287
|
+
fields: z.record(z.string(), z.looseObject({ type: z.string() }))
|
|
288
|
+
}).meta({ description: "Campos que el plugin a\xF1ade a colecciones del proyecto que elija el admin; con el prefijo del plugin." });
|
|
289
|
+
var permissionSchema = z.discriminatedUnion("kind", [contentPermission, usersPermission, networkPermission, fieldsPermission], {
|
|
290
|
+
error: "kind: content, users, network o fields."
|
|
291
|
+
});
|
|
292
|
+
var KEY = /^[a-z][a-zA-Z0-9]{0,39}$/;
|
|
293
|
+
var keyOf = (what) => z.string().regex(KEY, { error: `${what}: letras y d\xEDgitos, empieza por min\xFAscula, hasta 40 (es el nombre en el c\xF3digo).` });
|
|
294
|
+
var SETTING_TYPES = ["text", "number", "boolean", "select", "secret"];
|
|
295
|
+
var settingSchema = z.strictObject({
|
|
296
|
+
key: keyOf("key").meta({ description: "Nombre del ajuste en el c\xF3digo (settings.get / secrets.get)." }),
|
|
297
|
+
label: text(60, "label").meta({ description: "Nombre que ve el admin." }),
|
|
298
|
+
description: text(300, "description").optional().meta({ description: "Ayuda para el admin." }),
|
|
299
|
+
type: z.enum(SETTING_TYPES, { error: `type: ${SETTING_TYPES.join(", ")}.` }).meta({
|
|
300
|
+
description: "secret: cifrado, nunca vuelve al navegador y solo lo lee el plugin en el servidor."
|
|
301
|
+
}),
|
|
302
|
+
required: z.boolean().default(false).meta({ description: "El plugin no funciona sin \xE9l: el panel lo pide." }),
|
|
303
|
+
default: z.union([z.string(), z.number(), z.boolean()]).optional().meta({ description: "Valor por defecto (no en un secreto)." }),
|
|
304
|
+
options: z.array(z.strictObject({ value: text(100, "options.value"), label: text(100, "options.label") })).min(1, { error: "options: al menos una." }).optional().meta({ description: "Solo en select: las opciones." })
|
|
305
|
+
}).meta({ description: "Un ajuste del plugin que rellena el admin." });
|
|
306
|
+
var BEFORE_EVENTS = ["beforeCreate", "beforeUpdate", "beforeDelete"];
|
|
307
|
+
var AFTER_EVENTS = ["afterCreate", "afterUpdate", "afterDelete", "afterPublish", "afterUnpublish"];
|
|
308
|
+
var HOOK_EVENTS = [...BEFORE_EVENTS, ...AFTER_EVENTS];
|
|
309
|
+
var isBeforeEvent = (e) => BEFORE_EVENTS.includes(e);
|
|
310
|
+
var hookSchema = z.strictObject({
|
|
311
|
+
id: keyOf("id").meta({ description: "Nombre del hook en el c\xF3digo (hooks.<id>)." }),
|
|
312
|
+
event: z.enum(HOOK_EVENTS, { error: `event: ${HOOK_EVENTS.join(", ")}.` }),
|
|
313
|
+
on: z.union([
|
|
314
|
+
z.strictObject({ permission: z.string().meta({ description: "Id de un permiso de contenido: las colecciones que elija el admin." }) }),
|
|
315
|
+
z.strictObject({ collection: z.string().meta({ description: "Una colecci\xF3n o single type del propio plugin." }) })
|
|
316
|
+
]).meta({ description: "Sobre qu\xE9: { permission } (colecciones del proyecto que elija el admin) o { collection } (una suya)." }),
|
|
317
|
+
onError: z.enum(["block", "allow"], { error: "onError: block o allow." }).optional().meta({ description: 'Solo en los "antes": si el hook falla, block impide guardar y allow deja guardar.' })
|
|
318
|
+
}).meta({ description: "Un hook: el motor llama a hooks.<id> del c\xF3digo." });
|
|
319
|
+
var ROUTE_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
|
|
320
|
+
var ROUTE_PATH = /^\/$|^(?:\/(?:[a-z0-9][a-z0-9-]*|:[a-z][a-zA-Z0-9]*))+$/;
|
|
321
|
+
var routeSchema = z.strictObject({
|
|
322
|
+
id: keyOf("id").meta({ description: "Nombre de la ruta en el c\xF3digo (routes.<id>)." }),
|
|
323
|
+
method: z.enum(ROUTE_METHODS, { error: `method: ${ROUTE_METHODS.join(", ")}.` }),
|
|
324
|
+
path: z.string().max(200, { error: "path: como mucho 200 caracteres." }).regex(ROUTE_PATH, { error: "path: / o tramos /algo (min\xFAsculas, d\xEDgitos, guiones) y /:parametro." }).meta({ description: "Bajo /api/plugins/<namespace>: / o tramos /algo y /:parametro." }),
|
|
325
|
+
access: z.enum(["public", "token"], { error: "access: public o token." }).meta({
|
|
326
|
+
description: "public: cualquiera. token: un API token del proyecto con permiso para este plugin."
|
|
327
|
+
})
|
|
328
|
+
}).meta({ description: "Una ruta propia en /api/plugins/<namespace>/\u2026: el motor llama a routes.<id> del c\xF3digo." });
|
|
329
|
+
var taskSchema = z.strictObject({
|
|
330
|
+
id: keyOf("id").meta({ description: "Nombre de la tarea en el c\xF3digo (tasks.<id>)." }),
|
|
331
|
+
schedule: z.string().superRefine((expr, ctx) => {
|
|
332
|
+
const r = parseCron(expr);
|
|
333
|
+
if ("error" in r) ctx.addIssue({ code: "custom", message: `schedule: ${r.error}` });
|
|
334
|
+
}).meta({ description: 'Cu\xE1ndo, en cron (minuto hora d\xEDa-del-mes mes d\xEDa-de-la-semana), en UTC. P. ej. "*/15 * * * *".' })
|
|
335
|
+
}).meta({ description: "Una tarea programada: el motor llama a tasks.<id> del c\xF3digo." });
|
|
336
|
+
var LOCALE_PATTERN = /^[a-z]{2}(-[A-Z]{2})?$/;
|
|
337
|
+
var TEXT_KEY = /^%([a-zA-Z0-9_.-]{1,80})%$/;
|
|
338
|
+
var WIDGET_SIZES = ["s", "m", "l", "w"];
|
|
339
|
+
var panelPermission = z.strictObject({
|
|
340
|
+
id: keyOf("id").meta({ description: "Id del permiso (lo piden sus pantallas, widgets y acciones)." }),
|
|
341
|
+
label: text(80, "label").meta({ description: "Nombre en Ajustes \u2192 Roles." }),
|
|
342
|
+
description: text(300, "description").optional().meta({ description: "Qu\xE9 deja hacer, en Roles." })
|
|
343
|
+
}).meta({ description: "Un permiso del panel del plugin: sale en Ajustes \u2192 Roles; el admin lo tiene siempre." });
|
|
344
|
+
var panelNav = z.strictObject({
|
|
345
|
+
id: keyOf("id"),
|
|
346
|
+
label: text(60, "label").meta({ description: "Texto del enlace." }),
|
|
347
|
+
screen: keyOf("screen").meta({ description: "La pantalla a la que lleva (panel.screens)." }),
|
|
348
|
+
area: z.enum(["content", "settings"]).default("content").meta({ description: "D\xF3nde: content, en el apartado del plugin del panel de Contenido; settings, en Ajustes." }),
|
|
349
|
+
permission: keyOf("permission").optional().meta({ description: "Permiso del plugin que hace falta para verlo." })
|
|
350
|
+
}).meta({ description: "Una entrada de la barra lateral." });
|
|
351
|
+
var panelScreen = z.strictObject({
|
|
352
|
+
id: keyOf("id").meta({ description: "Nombre de la pantalla en ui.js (screens.<id>)." }),
|
|
353
|
+
title: text(80, "title").meta({ description: "T\xEDtulo de la pantalla." }),
|
|
354
|
+
permission: keyOf("permission").optional()
|
|
355
|
+
}).meta({ description: "Una pantalla propia: la pinta ui.js con los componentes de Surnie." });
|
|
356
|
+
var panelWidget = z.strictObject({
|
|
357
|
+
id: keyOf("id").meta({ description: "Nombre del widget en ui.js (widgets.<id>)." }),
|
|
358
|
+
title: text(60, "title"),
|
|
359
|
+
size: z.enum(WIDGET_SIZES).default("m").meta({ description: "Tama\xF1o en el dashboard: s, m, l o w." }),
|
|
360
|
+
permission: keyOf("permission").optional()
|
|
361
|
+
}).meta({ description: "Un widget del dashboard." });
|
|
362
|
+
var panelAction = z.strictObject({
|
|
363
|
+
id: keyOf("id").meta({ description: "Nombre de la acci\xF3n en server.js (actions.<id>)." }),
|
|
364
|
+
label: text(40, "label").meta({ description: "Texto del bot\xF3n." }),
|
|
365
|
+
on: z.union([
|
|
366
|
+
z.strictObject({ collection: z.string().meta({ description: "Una colecci\xF3n del plugin." }) }),
|
|
367
|
+
z.strictObject({ permission: z.string().meta({ description: "Un permiso de contenido: las colecciones que el admin le concedi\xF3." }) })
|
|
368
|
+
]).meta({ description: "Sobre qu\xE9 colecciones sale." }),
|
|
369
|
+
scope: z.enum(["record", "list"]).default("record").meta({ description: "record: en la ficha de un registro; list: sobre los marcados en el listado." }),
|
|
370
|
+
permission: keyOf("permission").optional(),
|
|
371
|
+
confirm: text(200, "confirm").optional().meta({ description: "Si la lleva, se pide confirmar con este texto antes de ejecutarla." }),
|
|
372
|
+
tone: z.enum(["default", "danger"]).default("default")
|
|
373
|
+
}).meta({ description: "Una acci\xF3n (un bot\xF3n) sobre registros: la ejecuta server.js (actions.<id>)." });
|
|
374
|
+
var panelSchema = z.strictObject({
|
|
375
|
+
permissions: z.array(panelPermission).default([]),
|
|
376
|
+
nav: z.array(panelNav).default([]),
|
|
377
|
+
screens: z.array(panelScreen).default([]),
|
|
378
|
+
widgets: z.array(panelWidget).default([]),
|
|
379
|
+
actions: z.array(panelAction).default([])
|
|
380
|
+
}).meta({ description: "Lo que el plugin a\xF1ade al panel (docs/plugins.md \xA76.2)." });
|
|
381
|
+
var modelItem = z.looseObject({ apiId: z.string(), fields: z.record(z.string(), z.looseObject({ type: z.string() })).optional() });
|
|
382
|
+
var pluginModel = z.strictObject({
|
|
383
|
+
collections: z.array(modelItem).default([]),
|
|
384
|
+
singleTypes: z.array(modelItem).default([]),
|
|
385
|
+
components: z.array(modelItem).default([])
|
|
386
|
+
});
|
|
387
|
+
var NAMESPACE_ERROR = "namespace: de 3 a 16 min\xFAsculas o d\xEDgitos, empieza por letra, sin '_' y no reservado.";
|
|
388
|
+
var baseManifest = z.strictObject({
|
|
389
|
+
/** El esquema JSON para el editor (autocompletado). El motor no lo usa. */
|
|
390
|
+
$schema: z.string().optional().meta({ description: "Esquema JSON del manifiesto, para el editor. El motor lo ignora." }),
|
|
391
|
+
contract: z.number({ error: "contract: un n\xFAmero." }).int({ error: "contract: un entero." }).meta({ description: "Versi\xF3n del contrato con el motor que usa el plugin. 0 = inestable." }),
|
|
392
|
+
namespace: z.string().regex(NAMESPACE_PATTERN, { error: NAMESPACE_ERROR }).refine((ns) => !RESERVED_NAMESPACES.has(ns), { error: NAMESPACE_ERROR }).meta({ description: "Prefijo de todo lo del plugin (seo \u2192 seo_title). De 3 a 16 min\xFAsculas o d\xEDgitos, sin '_'. \xDAnico en la plataforma." }),
|
|
393
|
+
/** Nombre visible (la ficha y el marco de sus pantallas). */
|
|
394
|
+
name: text(60, "name").meta({ description: "Nombre visible del plugin." }),
|
|
395
|
+
/** Una frase. */
|
|
396
|
+
description: text(200, "description").meta({ description: "Qu\xE9 hace el plugin, en una frase." }),
|
|
397
|
+
version: z.string().regex(SEMVER, { error: "version: X.Y.Z, sin 'v' ni sufijos." }).meta({ description: "Versi\xF3n del plugin: X.Y.Z." }),
|
|
398
|
+
permissions: z.strictObject({
|
|
399
|
+
/** Sin ellos el plugin no se instala. */
|
|
400
|
+
required: z.array(permissionSchema).default([]).meta({ description: "Sin ellos el plugin no se instala." }),
|
|
401
|
+
/** El admin puede negarlos; el plugin tiene que funcionar sin ellos. */
|
|
402
|
+
optional: z.array(permissionSchema).default([]).meta({ description: "El admin puede negarlos: el plugin tiene que funcionar sin ellos." })
|
|
403
|
+
}).default({ required: [], optional: [] }),
|
|
404
|
+
model: pluginModel.default({ collections: [], singleTypes: [], components: [] }).meta({ description: "Colecciones, single types y componentes propios, con la gram\xE1tica del modelo (JSON de pnpm model export)." }),
|
|
405
|
+
settings: z.array(settingSchema).default([]).meta({ description: "Ajustes que rellena el admin; los secret, cifrados." }),
|
|
406
|
+
hooks: z.array(hookSchema).default([]).meta({ description: "Hooks del plugin." }),
|
|
407
|
+
routes: z.array(routeSchema).default([]).meta({ description: "Rutas propias en /api/plugins/<namespace>/\u2026" }),
|
|
408
|
+
tasks: z.array(taskSchema).default([]).meta({ description: "Tareas programadas." }),
|
|
409
|
+
panel: panelSchema.default({ permissions: [], nav: [], screens: [], widgets: [], actions: [] }),
|
|
410
|
+
defaultLocale: z.string().regex(LOCALE_PATTERN, { error: "defaultLocale: un idioma como es, en o pt-BR." }).optional().meta({ description: "El idioma de las traducciones que vale si falta una clave en otro. Obligatorio si alg\xFAn texto es una clave (%clave%)." })
|
|
411
|
+
});
|
|
412
|
+
function crossChecks(m, ctx) {
|
|
413
|
+
const prefix = `${m.namespace}_`;
|
|
414
|
+
const issue = (path, message) => ctx.addIssue({ code: "custom", path, message });
|
|
415
|
+
const owned = (name) => typeof name === "string" && name.startsWith(prefix) && SUFFIX.test(name.slice(prefix.length));
|
|
416
|
+
const ids = /* @__PURE__ */ new Set();
|
|
417
|
+
for (const group of ["required", "optional"]) {
|
|
418
|
+
m.permissions[group].forEach((p, i) => {
|
|
419
|
+
if (ids.has(p.id)) issue(["permissions", group, i, "id"], `Id de permiso repetido: "${p.id}".`);
|
|
420
|
+
ids.add(p.id);
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
for (const kind of ["collections", "singleTypes", "components"]) {
|
|
424
|
+
m.model[kind].forEach((item, i) => {
|
|
425
|
+
if (!owned(item.apiId)) issue(["model", kind, i, "apiId"], `"${item.apiId}": el ID de la API tiene que empezar por "${prefix}".`);
|
|
426
|
+
for (const [name, f] of Object.entries(item.fields ?? {})) {
|
|
427
|
+
checkFieldRefs(f, ["model", kind, i, "fields", name], `${item.apiId}.${name}`);
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
const foreign = /* @__PURE__ */ new Set();
|
|
432
|
+
for (const group of ["required", "optional"]) {
|
|
433
|
+
m.permissions[group].forEach((p, i) => {
|
|
434
|
+
if (p.kind !== "fields") return;
|
|
435
|
+
const at = ["permissions", group, i, "fields"];
|
|
436
|
+
if (!Object.keys(p.fields).length) issue(at, "fields: al menos un campo.");
|
|
437
|
+
for (const [name, f] of Object.entries(p.fields)) {
|
|
438
|
+
if (!owned(name) || !IDENT.test(name)) issue([...at, name], `"${name}": un campo en una colecci\xF3n ajena tiene que empezar por "${prefix}".`);
|
|
439
|
+
if (foreign.has(name)) issue([...at, name], `"${name}": ya lo declara otro permiso.`);
|
|
440
|
+
foreign.add(name);
|
|
441
|
+
if (f.type === "relation" && (f.relation === "oneToMany" || f.mappedBy !== void 0)) {
|
|
442
|
+
issue([...at, name], `"${name}": un campo en una colecci\xF3n ajena no puede ser un lado inverso (oneToMany o mappedBy).`);
|
|
443
|
+
}
|
|
444
|
+
checkFieldRefs(f, [...at, name], name);
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
const unique = (list, key, where) => {
|
|
449
|
+
const seen = /* @__PURE__ */ new Set();
|
|
450
|
+
list.forEach((item, i) => {
|
|
451
|
+
if (seen.has(item[key])) issue([where, i, key], `${where}: "${String(item[key])}" est\xE1 repetido.`);
|
|
452
|
+
seen.add(item[key]);
|
|
453
|
+
});
|
|
454
|
+
};
|
|
455
|
+
unique(m.settings, "key", "settings");
|
|
456
|
+
unique(m.hooks, "id", "hooks");
|
|
457
|
+
unique(m.routes, "id", "routes");
|
|
458
|
+
unique(m.tasks, "id", "tasks");
|
|
459
|
+
unique(m.panel.permissions, "id", "panel.permissions");
|
|
460
|
+
unique(m.panel.nav, "id", "panel.nav");
|
|
461
|
+
unique(m.panel.screens, "id", "panel.screens");
|
|
462
|
+
unique(m.panel.widgets, "id", "panel.widgets");
|
|
463
|
+
unique(m.panel.actions, "id", "panel.actions");
|
|
464
|
+
const panelPermissions = new Set(m.panel.permissions.map((p) => p.id));
|
|
465
|
+
const screens = new Set(m.panel.screens.map((s2) => s2.id));
|
|
466
|
+
for (const [list, where] of [
|
|
467
|
+
[m.panel.nav, "panel.nav"],
|
|
468
|
+
[m.panel.screens, "panel.screens"],
|
|
469
|
+
[m.panel.widgets, "panel.widgets"],
|
|
470
|
+
[m.panel.actions, "panel.actions"]
|
|
471
|
+
]) {
|
|
472
|
+
list.forEach((item, i) => {
|
|
473
|
+
if (item.permission && !panelPermissions.has(item.permission)) {
|
|
474
|
+
issue([where, i, "permission"], `"${item.id}": "${item.permission}" no es un permiso de panel.permissions.`);
|
|
475
|
+
}
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
m.panel.nav.forEach((n, i) => {
|
|
479
|
+
if (!screens.has(n.screen)) issue(["panel.nav", i, "screen"], `"${n.id}": "${n.screen}" no es una pantalla de panel.screens.`);
|
|
480
|
+
});
|
|
481
|
+
for (const field3 of ["name", "description"]) {
|
|
482
|
+
if (TEXT_KEY.test(m[field3])) issue([field3], `${field3}: va en literal (sale en el cat\xE1logo y en la plataforma, donde no hay traducciones).`);
|
|
483
|
+
}
|
|
484
|
+
if (m.defaultLocale === void 0 && manifestTexts(m).some((t) => TEXT_KEY.test(t))) {
|
|
485
|
+
issue(["defaultLocale"], "Alg\xFAn texto es una clave (%clave%): defaultLocale dice el idioma que vale si falta en otro.");
|
|
486
|
+
}
|
|
487
|
+
m.settings.forEach((st, i) => {
|
|
488
|
+
const at = ["settings", i];
|
|
489
|
+
if (st.type === "secret" && st.default !== void 0) issue([...at, "default"], `"${st.key}": un secreto no lleva valor por defecto.`);
|
|
490
|
+
if (st.type === "select" ? !st.options : st.options) issue([...at, "options"], `"${st.key}": options va solo en select, y select la necesita.`);
|
|
491
|
+
if (st.default === void 0) return;
|
|
492
|
+
const ok = st.type === "number" ? typeof st.default === "number" : st.type === "boolean" ? typeof st.default === "boolean" : st.type === "select" ? st.options?.some((o) => o.value === st.default) : typeof st.default === "string";
|
|
493
|
+
if (!ok) issue([...at, "default"], `"${st.key}": el valor por defecto no encaja con el tipo ${st.type}.`);
|
|
494
|
+
});
|
|
495
|
+
const contentPermissions = new Set(
|
|
496
|
+
[...m.permissions.required, ...m.permissions.optional].filter((p) => p.kind === "content").map((p) => p.id)
|
|
497
|
+
);
|
|
498
|
+
const ownTypes = new Set([...m.model.collections, ...m.model.singleTypes].map((c) => c.apiId));
|
|
499
|
+
m.hooks.forEach((h, i) => {
|
|
500
|
+
const at = ["hooks", i];
|
|
501
|
+
if ("permission" in h.on && !contentPermissions.has(h.on.permission)) {
|
|
502
|
+
issue([...at, "on", "permission"], `"${h.id}": "${h.on.permission}" no es un permiso de contenido del manifiesto.`);
|
|
503
|
+
}
|
|
504
|
+
if ("collection" in h.on && !ownTypes.has(h.on.collection)) {
|
|
505
|
+
issue([...at, "on", "collection"], `"${h.id}": "${h.on.collection}" no es una colecci\xF3n ni un single type del plugin.`);
|
|
506
|
+
}
|
|
507
|
+
if (isBeforeEvent(h.event) && !h.onError) issue([...at, "onError"], `"${h.id}": un hook "antes" dice qu\xE9 pasa si falla (onError: block o allow).`);
|
|
508
|
+
if (!isBeforeEvent(h.event) && h.onError) issue([...at, "onError"], `"${h.id}": onError va solo en los hooks "antes" (los "despu\xE9s" se reintentan).`);
|
|
509
|
+
});
|
|
510
|
+
m.panel.actions.forEach((a, i) => {
|
|
511
|
+
const at = ["panel.actions", i, "on"];
|
|
512
|
+
if ("permission" in a.on && !contentPermissions.has(a.on.permission)) {
|
|
513
|
+
issue([...at, "permission"], `"${a.id}": "${a.on.permission}" no es un permiso de contenido del manifiesto.`);
|
|
514
|
+
}
|
|
515
|
+
if ("collection" in a.on && !m.model.collections.some((c) => c.apiId === a.on.collection)) {
|
|
516
|
+
issue([...at, "collection"], `"${a.id}": "${a.on.collection}" no es una colecci\xF3n del plugin.`);
|
|
517
|
+
}
|
|
518
|
+
});
|
|
519
|
+
const routes = /* @__PURE__ */ new Set();
|
|
520
|
+
m.routes.forEach((r, i) => {
|
|
521
|
+
const shape = `${r.method} ${r.path.replace(/:[a-zA-Z0-9]+/g, ":")}`;
|
|
522
|
+
if (routes.has(shape)) issue(["routes", i, "path"], `"${r.id}": ya hay otra ruta ${r.method} ${r.path}.`);
|
|
523
|
+
routes.add(shape);
|
|
524
|
+
});
|
|
525
|
+
function checkFieldRefs(f, path, who) {
|
|
526
|
+
if (f.type === "custom") issue(path, `"${who}": un plugin no puede usar custom fields (dependen del proyecto).`);
|
|
527
|
+
if (f.type === "relation" && !owned(f.relationTo)) issue(path, `"${who}": relationTo tiene que ser una colecci\xF3n del plugin ("${prefix}\u2026").`);
|
|
528
|
+
if (f.type === "component" && !owned(f.component)) issue(path, `"${who}": el componente tiene que ser del plugin ("${prefix}\u2026").`);
|
|
529
|
+
if (f.type === "dynamicblocks" && Array.isArray(f.components) && !f.components.every(owned)) {
|
|
530
|
+
issue(path, `"${who}": los componentes de los bloques tienen que ser del plugin ("${prefix}\u2026").`);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
var manifestSchema = baseManifest.superRefine(crossChecks);
|
|
535
|
+
function formatManifestIssues(error) {
|
|
536
|
+
return error.issues.map((i) => {
|
|
537
|
+
const where = i.path.map(String).join(".");
|
|
538
|
+
return where && !i.message.includes(where) ? `${where}: ${i.message}` : i.message;
|
|
539
|
+
}).join("\n");
|
|
540
|
+
}
|
|
541
|
+
function parseManifest(input, { contracts = [PLUGIN_CONTRACT] } = {}) {
|
|
542
|
+
const contract = input?.contract;
|
|
543
|
+
if (typeof contract === "number" && !contracts.includes(contract)) {
|
|
544
|
+
return { error: `contract: el plugin pide el contrato ${contract} y aqu\xED se admite ${contracts.join(" o ")}.` };
|
|
545
|
+
}
|
|
546
|
+
const r = manifestSchema.safeParse(input);
|
|
547
|
+
return r.success ? { manifest: r.data } : { error: formatManifestIssues(r.error) };
|
|
548
|
+
}
|
|
549
|
+
function manifestTexts(m) {
|
|
550
|
+
const out = [];
|
|
551
|
+
for (const p of [...m.permissions.required, ...m.permissions.optional]) out.push(p.purpose);
|
|
552
|
+
for (const st of m.settings) {
|
|
553
|
+
out.push(st.label);
|
|
554
|
+
if (st.description) out.push(st.description);
|
|
555
|
+
for (const o of st.options ?? []) out.push(o.label);
|
|
556
|
+
}
|
|
557
|
+
for (const p of m.panel.permissions) out.push(p.label, ...p.description ? [p.description] : []);
|
|
558
|
+
for (const n of m.panel.nav) out.push(n.label);
|
|
559
|
+
for (const s2 of m.panel.screens) out.push(s2.title);
|
|
560
|
+
for (const w of m.panel.widgets) out.push(w.title);
|
|
561
|
+
for (const a of m.panel.actions) out.push(a.label, ...a.confirm ? [a.confirm] : []);
|
|
562
|
+
return out;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// src/package.ts
|
|
566
|
+
import { createHash } from "node:crypto";
|
|
567
|
+
import { gunzipSync } from "node:zlib";
|
|
568
|
+
|
|
569
|
+
// src/ustar.ts
|
|
570
|
+
import { gzipSync } from "node:zlib";
|
|
571
|
+
var BLOCK = 512;
|
|
572
|
+
function octal(value, width) {
|
|
573
|
+
return value.toString(8).padStart(width - 1, "0") + "\0";
|
|
574
|
+
}
|
|
575
|
+
function header(name, size, prefix = "") {
|
|
576
|
+
const h = Buffer.alloc(BLOCK);
|
|
577
|
+
h.write(name, 0, 100, "ascii");
|
|
578
|
+
h.write(octal(420, 8), 100, "ascii");
|
|
579
|
+
h.write(octal(0, 8), 108, "ascii");
|
|
580
|
+
h.write(octal(0, 8), 116, "ascii");
|
|
581
|
+
h.write(octal(size, 12), 124, "ascii");
|
|
582
|
+
h.write(octal(0, 12), 136, "ascii");
|
|
583
|
+
h.write("0", 156, "ascii");
|
|
584
|
+
h.write("ustar\0", 257, "ascii");
|
|
585
|
+
h.write("00", 263, "ascii");
|
|
586
|
+
h.write(octal(0, 8), 329, "ascii");
|
|
587
|
+
h.write(octal(0, 8), 337, "ascii");
|
|
588
|
+
h.write(prefix, 345, 155, "ascii");
|
|
589
|
+
h.write(octal(checksum(h), 7) + " ", 148, "ascii");
|
|
590
|
+
return h;
|
|
591
|
+
}
|
|
592
|
+
function checksum(h) {
|
|
593
|
+
let sum = 0;
|
|
594
|
+
for (let i = 0; i < BLOCK; i++) sum += i >= 148 && i < 156 ? 32 : h[i];
|
|
595
|
+
return sum;
|
|
596
|
+
}
|
|
597
|
+
function padded(data) {
|
|
598
|
+
const rest = data.length % BLOCK;
|
|
599
|
+
return rest ? Buffer.concat([data, Buffer.alloc(BLOCK - rest)]) : data;
|
|
600
|
+
}
|
|
601
|
+
function field(h, start, length) {
|
|
602
|
+
const raw = h.subarray(start, start + length);
|
|
603
|
+
const end = raw.indexOf(0);
|
|
604
|
+
return raw.subarray(0, end < 0 ? length : end).toString("latin1");
|
|
605
|
+
}
|
|
606
|
+
function octalField(h, start, length, what, fail8) {
|
|
607
|
+
const text2 = h.subarray(start, start + length).toString("latin1");
|
|
608
|
+
const m = /^([0-7]+)[ \0]*$/.exec(text2);
|
|
609
|
+
if (!m) fail8(`Cabecera tar no v\xE1lida (${what}).`);
|
|
610
|
+
return parseInt(m[1], 8);
|
|
611
|
+
}
|
|
612
|
+
var isZero = (b) => b.every((x) => x === 0);
|
|
613
|
+
function gzipReproducible(tar) {
|
|
614
|
+
const gz = gzipSync(tar, { level: 9 });
|
|
615
|
+
gz[9] = 255;
|
|
616
|
+
return gz;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// src/package.ts
|
|
620
|
+
var PACKAGE_FILES = {
|
|
621
|
+
/** Lo que declara el plugin (manifest.ts). Obligatorio. */
|
|
622
|
+
"manifest.json": 256 * 1024,
|
|
623
|
+
/** Su lógica de servidor, compilada en un solo módulo. Opcional (un plugin solo de colecciones). */
|
|
624
|
+
"server.js": 2 * 1024 * 1024,
|
|
625
|
+
/** Su interfaz (pantallas y widgets en un Worker aislado, §6.3). Opcional. */
|
|
626
|
+
"ui.js": 2 * 1024 * 1024,
|
|
627
|
+
/**
|
|
628
|
+
* Sus traducciones (§6.2): `{ "<idioma>": { "<clave>": "<texto>" } }`. Las junta `pack` de los
|
|
629
|
+
* `locales/<idioma>.json` del proyecto. Opcional.
|
|
630
|
+
*/
|
|
631
|
+
"locales.json": 512 * 1024,
|
|
632
|
+
/** El registro firmado (autor y plataforma) con el sha256 de cada uno de los anteriores. */
|
|
633
|
+
"release.json": 64 * 1024
|
|
634
|
+
};
|
|
635
|
+
var MAX_PACKAGE_BYTES = 5 * 1024 * 1024;
|
|
636
|
+
var MAX_UNPACKED_BYTES = 10 * 1024 * 1024;
|
|
637
|
+
var NAMES = Object.keys(PACKAGE_FILES);
|
|
638
|
+
var SIGNED_FILES = ["manifest.json", "server.js", "ui.js", "locales.json"];
|
|
639
|
+
var MAX_LOCALES = 30;
|
|
640
|
+
var MAX_KEYS = 2e3;
|
|
641
|
+
var MAX_TEXT = 4e3;
|
|
642
|
+
var PluginPackageError = class extends Error {
|
|
643
|
+
};
|
|
644
|
+
var fail2 = (message) => {
|
|
645
|
+
throw new PluginPackageError(message);
|
|
646
|
+
};
|
|
647
|
+
function packageFileName(manifest) {
|
|
648
|
+
return `${manifest.namespace}-${manifest.version}.tgz`;
|
|
649
|
+
}
|
|
650
|
+
function fileDigests(files) {
|
|
651
|
+
const out = {};
|
|
652
|
+
for (const name of SIGNED_FILES) {
|
|
653
|
+
const data = files[name];
|
|
654
|
+
if (!data) continue;
|
|
655
|
+
out[name] = { sha256: createHash("sha256").update(data).digest("hex"), size: data.length };
|
|
656
|
+
}
|
|
657
|
+
return out;
|
|
658
|
+
}
|
|
659
|
+
function packPlugin(input, { contracts = [PLUGIN_CONTRACT] } = {}) {
|
|
660
|
+
const manifestBytes = Buffer.isBuffer(input.manifest) ? input.manifest : Buffer.from(input.manifest);
|
|
661
|
+
checkText("manifest.json", manifestBytes);
|
|
662
|
+
const manifest = parseManifestBytes(manifestBytes, contracts);
|
|
663
|
+
const files = { "manifest.json": manifestBytes };
|
|
664
|
+
for (const [name, value] of [["server.js", input.server], ["ui.js", input.ui], ["locales.json", input.locales], ["release.json", input.release]]) {
|
|
665
|
+
if (value !== void 0) files[name] = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
666
|
+
}
|
|
667
|
+
checkPackage(manifest, files);
|
|
668
|
+
const parts = [];
|
|
669
|
+
for (const name of [...NAMES].sort()) {
|
|
670
|
+
const data = files[name];
|
|
671
|
+
if (!data) continue;
|
|
672
|
+
if (data.length > PACKAGE_FILES[name]) fail2(`${name} ocupa ${data.length} bytes; el m\xE1ximo es ${PACKAGE_FILES[name]}.`);
|
|
673
|
+
checkText(name, data);
|
|
674
|
+
parts.push(header(name, data.length), padded(data));
|
|
675
|
+
}
|
|
676
|
+
parts.push(Buffer.alloc(BLOCK * 2));
|
|
677
|
+
const tar = Buffer.concat(parts);
|
|
678
|
+
if (tar.length > MAX_UNPACKED_BYTES) fail2(`El paquete descomprimido ocupa ${tar.length} bytes; el m\xE1ximo es ${MAX_UNPACKED_BYTES}.`);
|
|
679
|
+
const gz = gzipReproducible(tar);
|
|
680
|
+
if (gz.length > MAX_PACKAGE_BYTES) fail2(`El paquete ocupa ${gz.length} bytes; el m\xE1ximo es ${MAX_PACKAGE_BYTES}.`);
|
|
681
|
+
return gz;
|
|
682
|
+
}
|
|
683
|
+
function checkText(name, data) {
|
|
684
|
+
try {
|
|
685
|
+
new TextDecoder("utf-8", { fatal: true }).decode(data);
|
|
686
|
+
} catch {
|
|
687
|
+
fail2(`${name} no es texto UTF-8 v\xE1lido.`);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function readPluginPackage(gz, { contracts = [PLUGIN_CONTRACT] } = {}) {
|
|
691
|
+
if (gz.length > MAX_PACKAGE_BYTES) fail2(`El paquete ocupa ${gz.length} bytes; el m\xE1ximo es ${MAX_PACKAGE_BYTES}.`);
|
|
692
|
+
let tar = Buffer.alloc(0);
|
|
693
|
+
try {
|
|
694
|
+
tar = gunzipSync(gz, { maxOutputLength: MAX_UNPACKED_BYTES });
|
|
695
|
+
} catch (e) {
|
|
696
|
+
fail2(
|
|
697
|
+
e.code === "ERR_BUFFER_TOO_LARGE" ? `El paquete descomprimido pasa de ${MAX_UNPACKED_BYTES} bytes.` : "El paquete no es un .tgz v\xE1lido."
|
|
698
|
+
);
|
|
699
|
+
}
|
|
700
|
+
if (tar.length % BLOCK !== 0) fail2("El paquete no es un tar v\xE1lido (tama\xF1o).");
|
|
701
|
+
const files = {};
|
|
702
|
+
let off = 0;
|
|
703
|
+
for (; ; ) {
|
|
704
|
+
if (off + BLOCK > tar.length) fail2("El paquete no es un tar v\xE1lido (termina sin cierre).");
|
|
705
|
+
const h = tar.subarray(off, off + BLOCK);
|
|
706
|
+
if (isZero(h)) {
|
|
707
|
+
if (off + 2 * BLOCK > tar.length || !isZero(tar.subarray(off))) fail2("El paquete no es un tar v\xE1lido (datos tras el final).");
|
|
708
|
+
break;
|
|
709
|
+
}
|
|
710
|
+
if (octalField(h, 148, 8, "suma de control", fail2) !== checksum(h)) fail2("El paquete no es un tar v\xE1lido (suma de control).");
|
|
711
|
+
if (h.toString("latin1", 257, 263) !== "ustar\0" || h.toString("latin1", 263, 265) !== "00") {
|
|
712
|
+
fail2("El paquete no es un tar ustar.");
|
|
713
|
+
}
|
|
714
|
+
const name = field(h, 0, 100);
|
|
715
|
+
const type = String.fromCharCode(h[156]);
|
|
716
|
+
if (type !== "0") fail2(`"${name}" no es un fichero normal (tipo "${type === "\0" ? "\\0" : type}"): solo se admiten ficheros.`);
|
|
717
|
+
if (!isZero(h.subarray(157, 257))) fail2(`"${name}" lleva un destino de enlace.`);
|
|
718
|
+
if (!isZero(h.subarray(345, 500))) fail2(`"${name}" lleva un prefijo de ruta.`);
|
|
719
|
+
if (!NAMES.includes(name)) fail2(`El paquete lleva "${name}", que no es uno de ${NAMES.join(", ")}.`);
|
|
720
|
+
const fileName = name;
|
|
721
|
+
if (files[fileName]) fail2(`El paquete lleva "${name}" dos veces.`);
|
|
722
|
+
const size = octalField(h, 124, 12, "tama\xF1o", fail2);
|
|
723
|
+
if (size > PACKAGE_FILES[fileName]) fail2(`${name} ocupa ${size} bytes; el m\xE1ximo es ${PACKAGE_FILES[fileName]}.`);
|
|
724
|
+
const start = off + BLOCK;
|
|
725
|
+
const end = start + Math.ceil(size / BLOCK) * BLOCK;
|
|
726
|
+
if (end > tar.length) fail2(`"${name}" est\xE1 cortado.`);
|
|
727
|
+
if (!isZero(tar.subarray(start + size, end))) fail2(`"${name}" lleva datos tras su final.`);
|
|
728
|
+
const data = Buffer.from(tar.subarray(start, start + size));
|
|
729
|
+
checkText(name, data);
|
|
730
|
+
files[fileName] = data;
|
|
731
|
+
off = end;
|
|
732
|
+
}
|
|
733
|
+
const raw = files["manifest.json"];
|
|
734
|
+
if (!raw) fail2("El paquete no lleva manifest.json.");
|
|
735
|
+
const manifest = parseManifestBytes(raw, contracts);
|
|
736
|
+
checkPackage(manifest, files);
|
|
737
|
+
return { manifest, files, digests: fileDigests(files) };
|
|
738
|
+
}
|
|
739
|
+
function checkPackage(m, files) {
|
|
740
|
+
const locales = files["locales.json"] ? parseLocales(files["locales.json"]) : null;
|
|
741
|
+
const keys = manifestTexts(m).map((t) => TEXT_KEY.exec(t)?.[1]).filter((k) => k !== void 0);
|
|
742
|
+
if (keys.length || locales) {
|
|
743
|
+
if (!m.defaultLocale) fail2("manifest.json: con traducciones, defaultLocale dice el idioma que vale si falta una clave.");
|
|
744
|
+
const base = locales?.[m.defaultLocale];
|
|
745
|
+
if (!base) fail2(`Faltan las traducciones del idioma por defecto (locales/${m.defaultLocale}.json).`);
|
|
746
|
+
const missing = keys.find((k) => base[k] === void 0);
|
|
747
|
+
if (missing) fail2(`manifest.json usa "%${missing}%", que no est\xE1 en locales/${m.defaultLocale}.json.`);
|
|
748
|
+
}
|
|
749
|
+
if ((m.panel.screens.length || m.panel.widgets.length) && !files["ui.js"]) {
|
|
750
|
+
fail2("El manifiesto declara pantallas o widgets, pero el paquete no lleva su interfaz (src/ui.ts \u2192 ui.js).");
|
|
751
|
+
}
|
|
752
|
+
if (m.panel.actions.length && !files["server.js"]) {
|
|
753
|
+
fail2("El manifiesto declara acciones, pero el paquete no lleva su c\xF3digo de servidor (src/server.ts \u2192 server.js).");
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
function parseLocales(raw) {
|
|
757
|
+
let json2;
|
|
758
|
+
try {
|
|
759
|
+
json2 = JSON.parse(raw.toString("utf8"));
|
|
760
|
+
} catch {
|
|
761
|
+
return fail2("locales.json no es JSON v\xE1lido.");
|
|
762
|
+
}
|
|
763
|
+
if (!json2 || typeof json2 !== "object" || Array.isArray(json2)) fail2("locales.json: un objeto { idioma: { clave: texto } }.");
|
|
764
|
+
const entries = Object.entries(json2);
|
|
765
|
+
if (entries.length > MAX_LOCALES) fail2(`locales.json: como mucho ${MAX_LOCALES} idiomas.`);
|
|
766
|
+
const out = {};
|
|
767
|
+
for (const [locale, messages] of entries) {
|
|
768
|
+
if (!LOCALE_PATTERN.test(locale)) fail2(`locales.json: "${locale}" no es un idioma (es, en, pt-BR\u2026).`);
|
|
769
|
+
out[locale] = parseMessages(messages, `locales/${locale}.json`);
|
|
770
|
+
}
|
|
771
|
+
return out;
|
|
772
|
+
}
|
|
773
|
+
function parseMessages(messages, what) {
|
|
774
|
+
if (!messages || typeof messages !== "object" || Array.isArray(messages)) fail2(`${what}: un objeto { clave: texto }.`);
|
|
775
|
+
const list = Object.entries(messages);
|
|
776
|
+
if (list.length > MAX_KEYS) fail2(`${what}: como mucho ${MAX_KEYS} textos.`);
|
|
777
|
+
const out = {};
|
|
778
|
+
for (const [key, value] of list) {
|
|
779
|
+
if (!/^[a-zA-Z0-9_.-]{1,80}$/.test(key)) fail2(`${what}: "${key}" no es una clave v\xE1lida (letras, d\xEDgitos y . _ -).`);
|
|
780
|
+
if (typeof value !== "string") fail2(`${what}: "${key}" tiene que ser un texto.`);
|
|
781
|
+
if (value.length > MAX_TEXT) fail2(`${what}: "${key}" pasa de ${MAX_TEXT} caracteres.`);
|
|
782
|
+
out[key] = value;
|
|
783
|
+
}
|
|
784
|
+
return out;
|
|
785
|
+
}
|
|
786
|
+
function parseManifestBytes(raw, contracts = [PLUGIN_CONTRACT]) {
|
|
787
|
+
let json2;
|
|
788
|
+
try {
|
|
789
|
+
json2 = JSON.parse(raw.toString("utf8"));
|
|
790
|
+
} catch {
|
|
791
|
+
fail2("manifest.json no es JSON v\xE1lido.");
|
|
792
|
+
}
|
|
793
|
+
const parsed = parseManifest(json2, { contracts });
|
|
794
|
+
if ("error" in parsed) fail2(`manifest.json no es v\xE1lido:
|
|
795
|
+
${parsed.error}`);
|
|
796
|
+
return parsed.manifest;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// src/ui-components.ts
|
|
800
|
+
var s = (max = 500) => ({ type: "string", max });
|
|
801
|
+
var oneOf = (...values) => ({ type: "string", oneOf: values });
|
|
802
|
+
var num = { type: "number" };
|
|
803
|
+
var bool = { type: "boolean" };
|
|
804
|
+
var json = (max, ts) => ({ type: "json", max, ts });
|
|
805
|
+
var field2 = { name: s(80), label: s(120), required: bool, error: s(300), disabled: bool, hint: s(300) };
|
|
806
|
+
var UI_COMPONENTS = [
|
|
807
|
+
// Colocar
|
|
808
|
+
{ tag: "surnie-stack", properties: { gap: oneOf("s", "m", "l") }, events: [], children: true },
|
|
809
|
+
{ tag: "surnie-inline", properties: { gap: oneOf("s", "m", "l"), align: oneOf("start", "center", "end", "between") }, events: [], children: true },
|
|
810
|
+
{ tag: "surnie-box", properties: { padding: oneOf("none", "s", "m", "l"), border: bool }, events: [], children: true },
|
|
811
|
+
{ tag: "surnie-divider", properties: {}, events: [], children: false },
|
|
812
|
+
// Texto
|
|
813
|
+
{ tag: "surnie-heading", properties: { level: oneOf("1", "2", "3") }, events: [], children: true },
|
|
814
|
+
{
|
|
815
|
+
tag: "surnie-text",
|
|
816
|
+
properties: { tone: oneOf("default", "muted", "success", "warning", "danger"), size: oneOf("s", "m"), weight: oneOf("normal", "bold") },
|
|
817
|
+
events: [],
|
|
818
|
+
children: true
|
|
819
|
+
},
|
|
820
|
+
{ tag: "surnie-badge", properties: { tone: oneOf("neutral", "info", "success", "warning", "danger") }, events: [], children: true },
|
|
821
|
+
// Datos
|
|
822
|
+
{
|
|
823
|
+
tag: "surnie-table",
|
|
824
|
+
// columns: [{ key, label, align? }]; rows: [{ id, cells: { [key]: texto o número } }]
|
|
825
|
+
properties: {
|
|
826
|
+
columns: json(2e4, '{ key: string; label: string; align?: "start" | "end" }[]'),
|
|
827
|
+
rows: json(2e5, "{ id: string; cells: Record<string, string | number> }[]"),
|
|
828
|
+
sortKey: s(80),
|
|
829
|
+
sortDir: oneOf("asc", "desc"),
|
|
830
|
+
page: num,
|
|
831
|
+
pageCount: num,
|
|
832
|
+
empty: s(200)
|
|
833
|
+
},
|
|
834
|
+
events: ["sort", "page", "rowclick"],
|
|
835
|
+
details: { sort: '{ key: string; dir: "asc" | "desc" }', page: "{ page: number }", rowclick: "{ id: string }" },
|
|
836
|
+
children: false
|
|
837
|
+
},
|
|
838
|
+
{ tag: "surnie-stat", properties: { label: s(120), value: s(60), hint: s(200), tone: oneOf("default", "success", "warning", "danger") }, events: [], children: false },
|
|
839
|
+
// labels: ["ene", "feb"…]; series: [{ name, values: [número…] }]
|
|
840
|
+
{
|
|
841
|
+
tag: "surnie-chart",
|
|
842
|
+
properties: { kind: oneOf("line", "bar"), labels: json(2e4, "string[]"), series: json(1e5, "{ name: string; values: number[] }[]"), height: num },
|
|
843
|
+
events: [],
|
|
844
|
+
children: false
|
|
845
|
+
},
|
|
846
|
+
// items: [{ label, value }]
|
|
847
|
+
{ tag: "surnie-details", properties: { items: json(5e4, "{ label: string; value: string | number }[]") }, events: [], children: false },
|
|
848
|
+
// Formularios (`submit` lleva { values } con lo escrito en los campos con `name`)
|
|
849
|
+
{ tag: "surnie-form", properties: {}, events: ["submit"], details: { submit: "{ values: Record<string, unknown> }" }, children: true },
|
|
850
|
+
{ tag: "surnie-textfield", properties: { ...field2, value: s(5e3), placeholder: s(200) }, events: ["change"], details: { change: "{ value: string }" }, children: false },
|
|
851
|
+
{
|
|
852
|
+
tag: "surnie-numberfield",
|
|
853
|
+
properties: { ...field2, value: num, min: num, max: num, step: num },
|
|
854
|
+
events: ["change"],
|
|
855
|
+
details: { change: "{ value: number | null }" },
|
|
856
|
+
children: false
|
|
857
|
+
},
|
|
858
|
+
// options: [{ value, label }]
|
|
859
|
+
{
|
|
860
|
+
tag: "surnie-select",
|
|
861
|
+
properties: { ...field2, value: s(200), options: json(5e4, "{ value: string; label: string }[]") },
|
|
862
|
+
events: ["change"],
|
|
863
|
+
details: { change: "{ value: string }" },
|
|
864
|
+
children: false
|
|
865
|
+
},
|
|
866
|
+
{
|
|
867
|
+
tag: "surnie-checkbox",
|
|
868
|
+
properties: { name: s(80), label: s(200), checked: bool, disabled: bool },
|
|
869
|
+
events: ["change"],
|
|
870
|
+
details: { change: "{ checked: boolean }" },
|
|
871
|
+
children: false
|
|
872
|
+
},
|
|
873
|
+
// value: "AAAA-MM-DD"
|
|
874
|
+
{ tag: "surnie-datefield", properties: { ...field2, value: s(10) }, events: ["change"], details: { change: "{ value: string }" }, children: false },
|
|
875
|
+
{
|
|
876
|
+
tag: "surnie-textarea",
|
|
877
|
+
properties: { ...field2, value: s(2e4), rows: num, placeholder: s(200) },
|
|
878
|
+
events: ["change"],
|
|
879
|
+
details: { change: "{ value: string }" },
|
|
880
|
+
children: false
|
|
881
|
+
},
|
|
882
|
+
// Acciones (`submit`: envía el formulario que lo contiene)
|
|
883
|
+
{
|
|
884
|
+
tag: "surnie-button",
|
|
885
|
+
properties: { tone: oneOf("default", "primary", "danger"), disabled: bool, loading: bool, submit: bool },
|
|
886
|
+
events: ["press"],
|
|
887
|
+
details: { press: "null" },
|
|
888
|
+
children: true
|
|
889
|
+
},
|
|
890
|
+
// to: "screen:<id>" (una pantalla del plugin), "content:<apiId>[/<id>]" (contenido del panel) o https://… (dominios aprobados)
|
|
891
|
+
{ tag: "surnie-link", properties: { to: s(2e3) }, events: [], children: true },
|
|
892
|
+
// Estados
|
|
893
|
+
{ tag: "surnie-banner", properties: { tone: oneOf("info", "success", "warning", "danger"), title: s(200) }, events: [], children: true },
|
|
894
|
+
{ tag: "surnie-empty", properties: { title: s(200), description: s(500) }, events: [], children: true },
|
|
895
|
+
{ tag: "surnie-spinner", properties: { label: s(120) }, events: [], children: false },
|
|
896
|
+
// Navegación: tabs: [{ id, label }]; los hijos son el contenido de la pestaña elegida
|
|
897
|
+
{
|
|
898
|
+
tag: "surnie-tabs",
|
|
899
|
+
properties: { tabs: json(1e4, "{ id: string; label: string }[]"), selected: s(80) },
|
|
900
|
+
events: ["change"],
|
|
901
|
+
details: { change: "{ id: string }" },
|
|
902
|
+
children: true
|
|
903
|
+
}
|
|
904
|
+
];
|
|
905
|
+
|
|
906
|
+
// src/types.ts
|
|
907
|
+
var TYPES_FILE = join(".surnie", "types.d.ts");
|
|
908
|
+
var UI_TYPES_FILE = join(".surnie", "ui.d.ts");
|
|
909
|
+
var str = (s2) => JSON.stringify(s2);
|
|
910
|
+
var union = (values, none = "never") => values.length ? values.map(str).join(" | ") : none;
|
|
911
|
+
var COMMON = `/** Una entrada tal como la ve el plugin: solo los campos concedidos (el resto llega como null). */
|
|
912
|
+
type SurnieEntry = { id: string; [field: string]: unknown };
|
|
913
|
+
|
|
914
|
+
/** Consultas con el mismo formato que la API REST (filters, sort y pagination de estilo Strapi). */
|
|
915
|
+
type SurnieQuery = {
|
|
916
|
+
/** La colecci\xF3n: la que llega en un hook (event.collection) o una propia del plugin. */
|
|
917
|
+
collection: string;
|
|
918
|
+
locale?: string;
|
|
919
|
+
/** "published": lo publicado (en las colecciones con publicaci\xF3n); por defecto, el borrador. */
|
|
920
|
+
status?: "draft" | "published";
|
|
921
|
+
filters?: Record<string, unknown>;
|
|
922
|
+
sort?: string | string[];
|
|
923
|
+
pagination?: { page?: number; pageSize?: number };
|
|
924
|
+
fields?: string | string[];
|
|
925
|
+
};
|
|
926
|
+
|
|
927
|
+
type SurnieList = {
|
|
928
|
+
data: SurnieEntry[];
|
|
929
|
+
meta: { locale: string; pagination: { page: number; pageSize: number; pageCount: number; total: number } };
|
|
930
|
+
};
|
|
931
|
+
|
|
932
|
+
/** Lo que el anfitri\xF3n pasa a un hook "antes" (beforeCreate, beforeUpdate, beforeDelete). */
|
|
933
|
+
type SurnieBeforeEvent<E extends string> = {
|
|
934
|
+
event: E;
|
|
935
|
+
collection: string;
|
|
936
|
+
locale: string | null;
|
|
937
|
+
/** null al crear. */
|
|
938
|
+
id: string | null;
|
|
939
|
+
/** Los cambios que se van a guardar (solo los campos concedidos); null al borrar. */
|
|
940
|
+
data: Record<string, unknown> | null;
|
|
941
|
+
/** C\xF3mo est\xE1 ahora (null al crear). */
|
|
942
|
+
current: SurnieEntry | null;
|
|
943
|
+
};
|
|
944
|
+
|
|
945
|
+
/**
|
|
946
|
+
* La respuesta de un hook "antes": nada (sigue igual), { reject } (no se guarda, con este mensaje) o
|
|
947
|
+
* { patch } (cambios que el motor valida y aplica; solo campos concedidos).
|
|
948
|
+
*/
|
|
949
|
+
type SurnieBeforeAnswer = void | null | { reject: string } | { patch: Record<string, unknown> };
|
|
950
|
+
|
|
951
|
+
/** Lo que el anfitri\xF3n pasa a un hook "despu\xE9s" (por la cola, tras guardar). */
|
|
952
|
+
type SurnieAfterEvent<E extends string> = {
|
|
953
|
+
event: E;
|
|
954
|
+
collection: string;
|
|
955
|
+
locale: string | null;
|
|
956
|
+
/** La entrada (null si ya no existe). */
|
|
957
|
+
entry: SurnieEntry | null;
|
|
958
|
+
};
|
|
959
|
+
|
|
960
|
+
/** Qui\xE9n llama a una ruta: cualquiera (public) o un API token del proyecto (token). */
|
|
961
|
+
type SurnieCaller = { kind: "public" } | { kind: "token"; id: string; name: string };
|
|
962
|
+
|
|
963
|
+
type SurnieAwaitable<T> = T | Promise<T>;
|
|
964
|
+
|
|
965
|
+
/** Una colecci\xF3n (o global) que el admin ha concedido: su id, su nombre visible y los campos que puedes leer. */
|
|
966
|
+
type SurnieGrantedCollection = { collection: string; label: string; kind: "collection" | "single"; fields: string[] };
|
|
967
|
+
|
|
968
|
+
/** Un texto del plugin (de locales/<idioma>.json) en el idioma de quien mira; {nombre} se sustituye. */
|
|
969
|
+
type SurnieTranslate = (key: string, vars?: Record<string, string | number>) => string;
|
|
970
|
+
|
|
971
|
+
/** Qui\xE9n mira el panel: su id y su nombre (nunca su sesi\xF3n ni su rol). */
|
|
972
|
+
type SurnieViewer = { id: string; name: string };
|
|
973
|
+
|
|
974
|
+
/** El tercer argumento de una funci\xF3n o una acci\xF3n: qui\xE9n la pide, su idioma y los textos del plugin. */
|
|
975
|
+
type SurniePanelContext = { user: SurnieViewer; locale: string; t: SurnieTranslate };
|
|
976
|
+
|
|
977
|
+
/** Lo que devuelve una acci\xF3n: un aviso (opcional) y si el panel vuelve a leer la p\xE1gina (s\xED, por defecto). */
|
|
978
|
+
type SurnieActionAnswer = void | null | { toast?: string; tone?: "success" | "danger"; refresh?: boolean };
|
|
979
|
+
|
|
980
|
+
`;
|
|
981
|
+
function settingType(s2) {
|
|
982
|
+
const base = s2.type === "number" ? "number" : s2.type === "boolean" ? "boolean" : s2.type === "select" ? union((s2.options ?? []).map((o) => o.value), "string") : "string";
|
|
983
|
+
return s2.default === void 0 ? `${base} | null` : base;
|
|
984
|
+
}
|
|
985
|
+
function grantedType(p) {
|
|
986
|
+
if (p.kind === "content") return `{ kind: "content"; actions: (${union(p.actions)})[]; collections: SurnieGrantedCollection[] }`;
|
|
987
|
+
if (p.kind === "fields") return `{ kind: "fields"; collections: { collection: string; label: string }[] }`;
|
|
988
|
+
if (p.kind === "users") return `{ kind: "users"; fields: (${union(p.fields)})[] }`;
|
|
989
|
+
return `{ kind: "network"; domains: (${union(p.domains)})[] }`;
|
|
990
|
+
}
|
|
991
|
+
function routeParams(path) {
|
|
992
|
+
const names = [...path.matchAll(/:([a-zA-Z0-9]+)/g)].map((m) => m[1]);
|
|
993
|
+
return names.length ? `{ ${names.map((n) => `${n}: string`).join("; ")} }` : "Record<string, never>";
|
|
994
|
+
}
|
|
995
|
+
var doc = (text2) => ` /** ${text2.replace(/\*\//g, "*\\/")} */
|
|
996
|
+
`;
|
|
997
|
+
var UI_COMMON = `/** Ad\xF3nde puede llevar la interfaz: una pantalla del plugin, el contenido del panel o un dominio concedido. */
|
|
998
|
+
type SurnieLink = \`screen:\${string}\` | \`content:\${string}\` | \`https://\${string}\`;
|
|
999
|
+
|
|
1000
|
+
/** El segundo argumento de una pantalla o un widget. */
|
|
1001
|
+
type SurnieUiContext = {
|
|
1002
|
+
/** Los par\xE1metros de la direcci\xF3n de la pantalla (los que deja setParams). */
|
|
1003
|
+
readonly params: Readonly<Record<string, string>>;
|
|
1004
|
+
readonly locale: string;
|
|
1005
|
+
readonly user: Readonly<SurnieViewer>;
|
|
1006
|
+
readonly t: SurnieTranslate;
|
|
1007
|
+
/** Llama a functions.<nombre> del servidor del plugin, con los permisos de quien mira. */
|
|
1008
|
+
call<T = unknown>(name: string, input?: unknown): Promise<T>;
|
|
1009
|
+
toast(text: string, tone?: "success" | "danger"): void;
|
|
1010
|
+
navigate(to: SurnieLink): void;
|
|
1011
|
+
/** Deja el estado de la pantalla en la direcci\xF3n (p\xE1gina, pesta\xF1a\u2026), para enlazarla y recargarla; null lo quita. */
|
|
1012
|
+
setParams(params: Record<string, string | number | null>): void;
|
|
1013
|
+
};
|
|
1014
|
+
|
|
1015
|
+
/** Una pantalla o un widget: dibuja en \`root\` con los componentes de Surnie (surnie-*). */
|
|
1016
|
+
type SurnieRender = (root: Element, ctx: SurnieUiContext) => SurnieAwaitable<void>;
|
|
1017
|
+
`;
|
|
1018
|
+
var propType = (t) => t.type === "string" ? t.oneOf ? union([...t.oneOf]) : "string" : t.type === "json" ? t.ts : t.type;
|
|
1019
|
+
var camel = (tag) => tag.replace(/(^|-)([a-z])/g, (_, __, c) => c.toUpperCase());
|
|
1020
|
+
function uiComponentTypes() {
|
|
1021
|
+
const out = [];
|
|
1022
|
+
const jsx = [];
|
|
1023
|
+
for (const c of UI_COMPONENTS) {
|
|
1024
|
+
const name = `${camel(c.tag)}Element`;
|
|
1025
|
+
const props = Object.entries(c.properties).map(([k, t]) => ` ${k}?: ${propType(t)};`);
|
|
1026
|
+
const details = "details" in c ? c.details : {};
|
|
1027
|
+
const own = Object.keys(c.properties);
|
|
1028
|
+
out.push(`interface ${name} extends ${own.length ? `Omit<HTMLElement, ${union(own)}>` : "HTMLElement"} {
|
|
1029
|
+
${props.join("\n")}
|
|
1030
|
+
}`);
|
|
1031
|
+
const handlers = c.events.map((e) => ` on${e[0].toUpperCase()}${e.slice(1)}?: (event: CustomEvent<${details[e] ?? "unknown"}>) => void;`);
|
|
1032
|
+
jsx.push(
|
|
1033
|
+
` ${str(c.tag)}: { ${[...Object.entries(c.properties).map(([k, t]) => `${k}?: ${propType(t)}`), ...c.children ? ["children?: unknown"] : [], "key?: string | number", "ref?: unknown"].join("; ")}${handlers.length ? "; " + handlers.map((h) => h.trim().replace(/;$/, "")).join("; ") : ""} };`
|
|
1034
|
+
);
|
|
1035
|
+
}
|
|
1036
|
+
return `${out.join("\n\n")}
|
|
1037
|
+
|
|
1038
|
+
interface HTMLElementTagNameMap {
|
|
1039
|
+
${UI_COMPONENTS.map((c) => ` ${str(c.tag)}: ${camel(c.tag)}Element;`).join("\n")}
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
/** Los componentes en JSX de Preact (la plantilla de create-surnie-plugin). */
|
|
1043
|
+
declare namespace preact.JSX {
|
|
1044
|
+
interface IntrinsicElements {
|
|
1045
|
+
${jsx.join("\n")}
|
|
1046
|
+
}
|
|
1047
|
+
}`;
|
|
1048
|
+
}
|
|
1049
|
+
function pluginTypes(m) {
|
|
1050
|
+
const all = [...m.permissions.required, ...m.permissions.optional];
|
|
1051
|
+
const settings = m.settings.filter((s2) => s2.type !== "secret");
|
|
1052
|
+
const secrets = m.settings.filter((s2) => s2.type === "secret");
|
|
1053
|
+
const hasContent = all.some((p) => p.kind === "content") || m.model.collections.length + m.model.singleTypes.length > 0;
|
|
1054
|
+
const userFields = [...new Set(all.flatMap((p) => p.kind === "users" ? p.fields : []))];
|
|
1055
|
+
const api = [];
|
|
1056
|
+
if (hasContent) {
|
|
1057
|
+
api.push(` content: {
|
|
1058
|
+
find(query: SurnieQuery): Promise<SurnieList>;
|
|
1059
|
+
/** Una entrada por id (en un global, sin id). null si no existe. */
|
|
1060
|
+
get(query: { collection: string; id?: string; locale?: string; status?: "draft" | "published"; fields?: string | string[] }): Promise<SurnieEntry | null>;
|
|
1061
|
+
create(input: { collection: string; data: Record<string, unknown>; locale?: string }): Promise<SurnieEntry>;
|
|
1062
|
+
/** rev: el _rev le\xEDdo; si el documento cambi\xF3 entretanto, falla (concurrencia optimista). */
|
|
1063
|
+
update(input: { collection: string; id?: string; data: Record<string, unknown>; locale?: string; rev?: number }): Promise<SurnieEntry>;
|
|
1064
|
+
delete(input: { collection: string; id: string }): Promise<{ ok: true }>;
|
|
1065
|
+
publish(input: { collection: string; id: string; locale: string; publish?: boolean }): Promise<{ ok: true }>;
|
|
1066
|
+
};`);
|
|
1067
|
+
}
|
|
1068
|
+
if (userFields.length) {
|
|
1069
|
+
const user = `{ id: string; ${userFields.map((f) => `${f}?: ${f === "createdAt" ? "string" : "string | null"}`).join("; ")} }`;
|
|
1070
|
+
api.push(` /** Solo los campos de cuenta concedidos. */
|
|
1071
|
+
users: {
|
|
1072
|
+
get(input: { id: string }): Promise<${user} | null>;
|
|
1073
|
+
/** Hasta 100 ids. */
|
|
1074
|
+
find(input: { ids: string[] }): Promise<${user}[]>;
|
|
1075
|
+
};`);
|
|
1076
|
+
}
|
|
1077
|
+
api.push(` settings: {
|
|
1078
|
+
get<K extends keyof SurnieSettings>(key: K): Promise<SurnieSettings[K]>;
|
|
1079
|
+
};`);
|
|
1080
|
+
api.push(` /** Lo que el admin te ha concedido de cada permiso del manifiesto (uno opcional que no te dio no est\xE1). */
|
|
1081
|
+
permissions: {
|
|
1082
|
+
get(): Promise<SurniePermissions>;
|
|
1083
|
+
};`);
|
|
1084
|
+
if (secrets.length) {
|
|
1085
|
+
api.push(` /** Los secretos que rellena el admin; null si no est\xE1 puesto. Nunca salen del servidor. */
|
|
1086
|
+
secrets: {
|
|
1087
|
+
get(key: ${union(secrets.map((s2) => s2.key))}): Promise<string | null>;
|
|
1088
|
+
};`);
|
|
1089
|
+
}
|
|
1090
|
+
const hooks = m.hooks.map((h) => {
|
|
1091
|
+
const event = isBeforeEvent(h.event) ? `(event: SurnieBeforeEvent<${str(h.event)}>, surnie: Surnie) => SurnieAwaitable<SurnieBeforeAnswer>` : `(event: SurnieAfterEvent<${str(h.event)}>, surnie: Surnie) => SurnieAwaitable<void>`;
|
|
1092
|
+
return `${doc(`${h.event} sobre ${"permission" in h.on ? `el permiso "${h.on.permission}"` : `"${h.on.collection}"`}.`)} ${h.id}: ${event};`;
|
|
1093
|
+
});
|
|
1094
|
+
const routes = m.routes.map(
|
|
1095
|
+
(r) => `${doc(`${r.method} /api/plugins/${m.namespace}${r.path === "/" ? "" : r.path} (${r.access === "public" ? "p\xFAblica" : "con API token"}).`)} ${r.id}: (request: Request, surnie: Surnie, context: { params: ${routeParams(r.path)}; caller: SurnieCaller }) => SurnieAwaitable<Response>;`
|
|
1096
|
+
);
|
|
1097
|
+
const tasks = m.tasks.map(
|
|
1098
|
+
(t) => `${doc(`Cada "${t.schedule}" (cron, UTC).`)} ${t.id}: (input: { scheduledAt: string }, surnie: Surnie) => SurnieAwaitable<unknown>;`
|
|
1099
|
+
);
|
|
1100
|
+
const actions = m.panel.actions.map(
|
|
1101
|
+
(a) => `${doc(`${a.scope === "record" ? "En la ficha de" : "Sobre lo marcado en el listado de"} ${"collection" in a.on ? `"${a.on.collection}"` : `las colecciones del permiso "${a.on.permission}"`}.`)} ${a.id}: (target: { collection: string; ids: string[] }, surnie: Surnie, ctx: SurniePanelContext) => SurnieAwaitable<SurnieActionAnswer>;`
|
|
1102
|
+
);
|
|
1103
|
+
const group = (name, entries) => entries.length ? ` ${name}: {
|
|
1104
|
+
${entries.map((e) => e.replace(/^/gm, " ")).join("\n")}
|
|
1105
|
+
};` : null;
|
|
1106
|
+
return `// GENERADO por surnie-plugin desde manifest.json (${m.namespace} ${m.version}): no editar a mano.
|
|
1107
|
+
// Se vuelve a generar con \`surnie-plugin types\`, \`pack\` y \`dev\`.
|
|
1108
|
+
|
|
1109
|
+
${COMMON}
|
|
1110
|
+
/** Los ajustes del plugin (settings.get): los que no tienen valor por defecto pueden no estar puestos. */
|
|
1111
|
+
type SurnieSettings = {
|
|
1112
|
+
${settings.map((s2) => `${doc(s2.label)} ${s2.key}: ${settingType(s2)};`).join("\n")}
|
|
1113
|
+
};
|
|
1114
|
+
|
|
1115
|
+
/** Lo concedido, por id de permiso (permissions.get). */
|
|
1116
|
+
type SurniePermissions = {
|
|
1117
|
+
${all.map((p) => `${doc(p.purpose)} ${p.id}${m.permissions.required.includes(p) ? "" : "?"}: ${grantedType(p)};`).join("\n")}
|
|
1118
|
+
};
|
|
1119
|
+
|
|
1120
|
+
/** Lo que el plugin puede pedir al motor (la recepci\xF3n): el segundo argumento de hooks, rutas y tareas. */
|
|
1121
|
+
type Surnie = {
|
|
1122
|
+
${api.join("\n")}
|
|
1123
|
+
};
|
|
1124
|
+
|
|
1125
|
+
/** Lo que exporta src/server.ts: \`export default { \u2026 } satisfies SurniePlugin\`. */
|
|
1126
|
+
type SurniePlugin = {
|
|
1127
|
+
${[group("hooks", hooks), group("routes", routes), group("tasks", tasks), group("actions", actions)].filter(Boolean).join("\n")}
|
|
1128
|
+
/** Las funciones que pide la interfaz (ctx.call), con los permisos de quien mira. */
|
|
1129
|
+
functions?: Record<string, (input: unknown, surnie: Surnie, ctx: SurniePanelContext) => SurnieAwaitable<unknown>>;
|
|
1130
|
+
};
|
|
1131
|
+
|
|
1132
|
+
`;
|
|
1133
|
+
}
|
|
1134
|
+
function pluginUiTypes(m) {
|
|
1135
|
+
const screens = m.panel.screens.map((sc) => `${doc(`La pantalla /admin/plugins/${m.namespace}/${sc.id}.`)} ${sc.id}: SurnieRender;`);
|
|
1136
|
+
const widgets = m.panel.widgets.map((w) => `${doc(`Un widget del dashboard (tama\xF1o ${w.size}).`)} ${w.id}: SurnieRender;`);
|
|
1137
|
+
const group = (name, entries) => entries.length ? ` ${name}: {
|
|
1138
|
+
${entries.map((e) => e.replace(/^/gm, " ")).join("\n")}
|
|
1139
|
+
};` : null;
|
|
1140
|
+
return `// GENERADO por surnie-plugin desde manifest.json (${m.namespace} ${m.version}): no editar a mano.
|
|
1141
|
+
// Los tipos de la interfaz (src/ui.ts o src/ui.tsx), con el DOM: los comunes est\xE1n en types.d.ts.
|
|
1142
|
+
|
|
1143
|
+
${UI_COMMON}
|
|
1144
|
+
/** Lo que exporta src/ui.ts(x): \`export default { \u2026 } satisfies SurnieUi\`. */
|
|
1145
|
+
type SurnieUi = {
|
|
1146
|
+
${[group("screens", screens), group("widgets", widgets)].filter(Boolean).join("\n")}
|
|
1147
|
+
};
|
|
1148
|
+
|
|
1149
|
+
${uiComponentTypes()}
|
|
1150
|
+
`;
|
|
1151
|
+
}
|
|
1152
|
+
function writePluginTypes(dir) {
|
|
1153
|
+
const file = join(dir, "manifest.json");
|
|
1154
|
+
if (!existsSync(file)) throw new Error("Falta manifest.json en esta carpeta.");
|
|
1155
|
+
const manifest = parseManifestBytes(readFileSync(file));
|
|
1156
|
+
for (const [name, text2] of [
|
|
1157
|
+
[TYPES_FILE, pluginTypes(manifest)],
|
|
1158
|
+
[UI_TYPES_FILE, pluginUiTypes(manifest)]
|
|
1159
|
+
]) {
|
|
1160
|
+
const out = join(dir, name);
|
|
1161
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
1162
|
+
if (!existsSync(out) || readFileSync(out, "utf8") !== text2) writeFileSync(out, text2);
|
|
1163
|
+
}
|
|
1164
|
+
return join(dir, TYPES_FILE);
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
// src/build.ts
|
|
1168
|
+
import { tmpdir } from "node:os";
|
|
1169
|
+
import { dirname as dirname2, join as join3, posix, relative, resolve, sep } from "node:path";
|
|
1170
|
+
import { build as esbuild, version as ESBUILD_VERSION } from "esbuild";
|
|
1171
|
+
|
|
1172
|
+
// src/locales.ts
|
|
1173
|
+
import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2 } from "node:fs";
|
|
1174
|
+
import { join as join2 } from "node:path";
|
|
1175
|
+
var LOCALES_DIR = "locales";
|
|
1176
|
+
var bad = (message) => {
|
|
1177
|
+
throw new Error(message);
|
|
1178
|
+
};
|
|
1179
|
+
function bundleLocales(dir) {
|
|
1180
|
+
const folder = join2(dir, LOCALES_DIR);
|
|
1181
|
+
if (!existsSync2(folder)) return null;
|
|
1182
|
+
const out = {};
|
|
1183
|
+
const inputs = [];
|
|
1184
|
+
for (const file of readdirSync(folder).sort()) {
|
|
1185
|
+
const locale = file.replace(/\.json$/, "");
|
|
1186
|
+
if (!file.endsWith(".json") || !LOCALE_PATTERN.test(locale)) {
|
|
1187
|
+
bad(`${LOCALES_DIR}/${file}: solo van ficheros <idioma>.json (es.json, en.json, pt-BR.json\u2026).`);
|
|
1188
|
+
}
|
|
1189
|
+
let json2;
|
|
1190
|
+
try {
|
|
1191
|
+
json2 = JSON.parse(readFileSync2(join2(folder, file), "utf8"));
|
|
1192
|
+
} catch {
|
|
1193
|
+
return bad(`${LOCALES_DIR}/${file} no es JSON v\xE1lido.`);
|
|
1194
|
+
}
|
|
1195
|
+
let messages;
|
|
1196
|
+
try {
|
|
1197
|
+
messages = parseMessages(json2, `${LOCALES_DIR}/${file}`);
|
|
1198
|
+
} catch (e) {
|
|
1199
|
+
return bad(e.message);
|
|
1200
|
+
}
|
|
1201
|
+
out[locale] = Object.fromEntries(Object.keys(messages).sort().map((k) => [k, messages[k]]));
|
|
1202
|
+
inputs.push(`${LOCALES_DIR}/${file}`);
|
|
1203
|
+
}
|
|
1204
|
+
if (!inputs.length) return null;
|
|
1205
|
+
return { data: Buffer.from(`${JSON.stringify(out, null, 2)}
|
|
1206
|
+
`), inputs };
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
// src/release.ts
|
|
1210
|
+
import { createHash as createHash3, createPrivateKey as createPrivateKey3, createPublicKey as createPublicKey2, generateKeyPairSync as generateKeyPairSync2 } from "node:crypto";
|
|
1211
|
+
import { z as z2 } from "zod";
|
|
1212
|
+
|
|
1213
|
+
// ../../scripts/release-lib.mjs
|
|
1214
|
+
import { createHash as createHash2, createPrivateKey as createPrivateKey2, createPublicKey, sign, verify } from "node:crypto";
|
|
1215
|
+
var ReleaseError = class extends Error {
|
|
1216
|
+
};
|
|
1217
|
+
function toPublicKey(key) {
|
|
1218
|
+
return typeof key === "object" && key.type === "public" ? key : createPublicKey(key);
|
|
1219
|
+
}
|
|
1220
|
+
function keyIdOf(publicKey) {
|
|
1221
|
+
const der = toPublicKey(publicKey).export({ type: "spki", format: "der" });
|
|
1222
|
+
return `ed25519-${createHash2("sha256").update(der).digest("hex").slice(0, 16)}`;
|
|
1223
|
+
}
|
|
1224
|
+
var PAYLOAD_TYPES = {
|
|
1225
|
+
engineRelease: "application/vnd.surnie.engine-release.v1+json",
|
|
1226
|
+
updatesResponse: "application/vnd.surnie.updates-response.v1+json",
|
|
1227
|
+
pluginCatalog: "application/vnd.surnie.plugin-catalog.v1+json",
|
|
1228
|
+
pluginRelease: "application/vnd.surnie.plugin-release.v1+json",
|
|
1229
|
+
pluginApproval: "application/vnd.surnie.plugin-approval.v1+json",
|
|
1230
|
+
pluginApprovalKey: "application/vnd.surnie.plugin-approval-key.v1+json",
|
|
1231
|
+
keyRotation: "application/vnd.surnie.key-rotation.v1+json"
|
|
1232
|
+
};
|
|
1233
|
+
function pae(payloadType, body) {
|
|
1234
|
+
const type = Buffer.from(payloadType, "utf8");
|
|
1235
|
+
return Buffer.concat([Buffer.from(`DSSEv1 ${type.length} `), type, Buffer.from(` ${body.length} `), body]);
|
|
1236
|
+
}
|
|
1237
|
+
function base64Strict(text2, what) {
|
|
1238
|
+
const buf = typeof text2 === "string" ? Buffer.from(text2, "base64") : Buffer.alloc(0);
|
|
1239
|
+
if (!text2 || typeof text2 !== "string" || buf.toString("base64") !== text2) throw new ReleaseError(`${what}: base64 no v\xE1lido.`);
|
|
1240
|
+
return buf;
|
|
1241
|
+
}
|
|
1242
|
+
function dsseSign(payloadType, payload, privateKey, keyIdFn = keyIdOf) {
|
|
1243
|
+
const key = typeof privateKey === "string" ? createPrivateKey2(privateKey) : privateKey;
|
|
1244
|
+
if (key.asymmetricKeyType !== "ed25519") throw new ReleaseError("La clave de firma tiene que ser Ed25519.");
|
|
1245
|
+
const body = Buffer.isBuffer(payload) ? payload : Buffer.from(payload, "utf8");
|
|
1246
|
+
return {
|
|
1247
|
+
payloadType,
|
|
1248
|
+
payload: body.toString("base64"),
|
|
1249
|
+
signatures: [{ keyid: keyIdFn(createPublicKey(key)), sig: sign(null, pae(payloadType, body), key).toString("base64") }]
|
|
1250
|
+
};
|
|
1251
|
+
}
|
|
1252
|
+
function dsseOpen(envelope, payloadType, keys, { what, keyIdFn = keyIdOf }) {
|
|
1253
|
+
const env = (
|
|
1254
|
+
/** @type {Record<string, unknown>} */
|
|
1255
|
+
envelope
|
|
1256
|
+
);
|
|
1257
|
+
const sigs = (
|
|
1258
|
+
/** @type {unknown[]} */
|
|
1259
|
+
env?.signatures
|
|
1260
|
+
);
|
|
1261
|
+
if (!env || typeof env !== "object" || Object.keys(env).sort().join(",") !== "payload,payloadType,signatures" || typeof env.payloadType !== "string" || typeof env.payload !== "string" || !Array.isArray(sigs)) {
|
|
1262
|
+
throw new ReleaseError(`${what}: no tiene la forma de un sobre firmado.`);
|
|
1263
|
+
}
|
|
1264
|
+
if (env.payloadType !== payloadType) throw new ReleaseError(`${what}: no es del tipo esperado (${env.payloadType}).`);
|
|
1265
|
+
if (sigs.length !== 1) throw new ReleaseError(`${what}: tiene que llevar exactamente una firma.`);
|
|
1266
|
+
const s2 = (
|
|
1267
|
+
/** @type {Record<string, unknown>} */
|
|
1268
|
+
sigs[0]
|
|
1269
|
+
);
|
|
1270
|
+
if (!s2 || typeof s2.keyid !== "string" || typeof s2.sig !== "string" || Object.keys(s2).sort().join(",") !== "keyid,sig") {
|
|
1271
|
+
throw new ReleaseError(`${what}: firma mal formada.`);
|
|
1272
|
+
}
|
|
1273
|
+
const entry = (keys?.keys ?? []).find((k) => k.keyId === s2.keyid);
|
|
1274
|
+
if (!entry) throw new ReleaseError(`${what}: est\xE1 firmado con una clave en la que no se conf\xEDa (${s2.keyid}).`);
|
|
1275
|
+
let publicKey;
|
|
1276
|
+
try {
|
|
1277
|
+
publicKey = createPublicKey({ key: base64Strict(entry.publicKey, `Clave ${entry.keyId}`), format: "der", type: "spki" });
|
|
1278
|
+
} catch (e) {
|
|
1279
|
+
if (e instanceof ReleaseError) throw e;
|
|
1280
|
+
throw new ReleaseError(`La clave ${entry.keyId} no es v\xE1lida.`);
|
|
1281
|
+
}
|
|
1282
|
+
if (publicKey.asymmetricKeyType !== "ed25519") throw new ReleaseError(`La clave ${entry.keyId} no es Ed25519.`);
|
|
1283
|
+
if (keyIdFn(publicKey) !== entry.keyId) throw new ReleaseError(`La clave ${entry.keyId} no corresponde a su huella.`);
|
|
1284
|
+
const body = base64Strict(env.payload, what);
|
|
1285
|
+
if (!verify(null, pae(payloadType, body), publicKey, base64Strict(s2.sig, `${what} (firma)`))) {
|
|
1286
|
+
throw new ReleaseError(`${what}: la firma no es v\xE1lida.`);
|
|
1287
|
+
}
|
|
1288
|
+
return body;
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
// src/release.ts
|
|
1292
|
+
var PAYLOAD_TYPES2 = {
|
|
1293
|
+
release: PAYLOAD_TYPES.pluginRelease,
|
|
1294
|
+
approval: PAYLOAD_TYPES.pluginApproval,
|
|
1295
|
+
approvalKey: PAYLOAD_TYPES.pluginApprovalKey,
|
|
1296
|
+
rotation: PAYLOAD_TYPES.keyRotation
|
|
1297
|
+
};
|
|
1298
|
+
var APPROVAL_LEVELS = ["surnie", "verified", "community", "private"];
|
|
1299
|
+
var MAX_ROTATIONS = 16;
|
|
1300
|
+
var PluginReleaseError = class extends Error {
|
|
1301
|
+
};
|
|
1302
|
+
var fail3 = (message) => {
|
|
1303
|
+
throw new PluginReleaseError(message);
|
|
1304
|
+
};
|
|
1305
|
+
var KEY_ID = /^ed25519-[0-9a-f]{16}$/;
|
|
1306
|
+
function lib(fn) {
|
|
1307
|
+
try {
|
|
1308
|
+
return fn();
|
|
1309
|
+
} catch (e) {
|
|
1310
|
+
if (e instanceof ReleaseError) fail3(e.message);
|
|
1311
|
+
throw e;
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
var fromBase64 = (text2, what) => lib(() => base64Strict(text2, what));
|
|
1315
|
+
function publicKeyObject(publicKey) {
|
|
1316
|
+
let key;
|
|
1317
|
+
try {
|
|
1318
|
+
key = createPublicKey2({ key: fromBase64(publicKey, "Clave p\xFAblica"), format: "der", type: "spki" });
|
|
1319
|
+
} catch (e) {
|
|
1320
|
+
if (e instanceof PluginReleaseError) throw e;
|
|
1321
|
+
return fail3("Clave p\xFAblica no v\xE1lida.");
|
|
1322
|
+
}
|
|
1323
|
+
if (key.asymmetricKeyType !== "ed25519") fail3("La clave p\xFAblica no es Ed25519.");
|
|
1324
|
+
return key;
|
|
1325
|
+
}
|
|
1326
|
+
function keyIdOf2(publicKey) {
|
|
1327
|
+
publicKeyObject(publicKey);
|
|
1328
|
+
return `ed25519-${createHash3("sha256").update(Buffer.from(publicKey, "base64")).digest("hex").slice(0, 16)}`;
|
|
1329
|
+
}
|
|
1330
|
+
function privateKeyObject(privateKeyPem) {
|
|
1331
|
+
let key;
|
|
1332
|
+
try {
|
|
1333
|
+
key = createPrivateKey3({ key: privateKeyPem });
|
|
1334
|
+
} catch {
|
|
1335
|
+
return fail3("No se puede leer la clave privada (si es el fichero cifrado, hay que abrirla antes con su contrase\xF1a).");
|
|
1336
|
+
}
|
|
1337
|
+
if (key.asymmetricKeyType !== "ed25519") fail3("La clave privada no es Ed25519.");
|
|
1338
|
+
return key;
|
|
1339
|
+
}
|
|
1340
|
+
function publicOf(key) {
|
|
1341
|
+
const publicKey = createPublicKey2(key).export({ type: "spki", format: "der" }).toString("base64");
|
|
1342
|
+
return { keyId: keyIdOf2(publicKey), publicKey };
|
|
1343
|
+
}
|
|
1344
|
+
function publicKeyOf(privateKeyPem) {
|
|
1345
|
+
return publicOf(privateKeyObject(privateKeyPem));
|
|
1346
|
+
}
|
|
1347
|
+
var envelopeSchema = z2.strictObject({
|
|
1348
|
+
payloadType: z2.string(),
|
|
1349
|
+
payload: z2.string(),
|
|
1350
|
+
signatures: z2.array(z2.strictObject({ keyid: z2.string(), sig: z2.string() }))
|
|
1351
|
+
});
|
|
1352
|
+
function seal(payloadType, payload, key) {
|
|
1353
|
+
return lib(() => dsseSign(payloadType, JSON.stringify(payload), key));
|
|
1354
|
+
}
|
|
1355
|
+
function open(envelope, payloadType, signer, what) {
|
|
1356
|
+
return lib(() => dsseOpen(envelope, payloadType, { keys: [signer] }, { what }));
|
|
1357
|
+
}
|
|
1358
|
+
function parseJson(body, schema, what) {
|
|
1359
|
+
let json2;
|
|
1360
|
+
try {
|
|
1361
|
+
json2 = JSON.parse(body.toString("utf8"));
|
|
1362
|
+
} catch {
|
|
1363
|
+
return fail3(`${what}: no es JSON.`);
|
|
1364
|
+
}
|
|
1365
|
+
const r = schema.safeParse(json2);
|
|
1366
|
+
if (!r.success) fail3(`${what}: ${r.error.issues.map((i) => `${i.path.join(".") || "(ra\xEDz)"}: ${i.message}`).join("; ")}`);
|
|
1367
|
+
return r.data;
|
|
1368
|
+
}
|
|
1369
|
+
var sha256 = (data) => createHash3("sha256").update(data).digest("hex");
|
|
1370
|
+
var SHA256 = /^[0-9a-f]{64}$/;
|
|
1371
|
+
var digestSchema = z2.strictObject({ sha256: z2.string().regex(SHA256), size: z2.number().int().nonnegative() });
|
|
1372
|
+
var SEMVER2 = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
|
|
1373
|
+
var TOOL_VERSION = /^[0-9A-Za-z.+-]{1,40}$/;
|
|
1374
|
+
var recordSchema = z2.strictObject({
|
|
1375
|
+
namespace: z2.string(),
|
|
1376
|
+
version: z2.string().regex(SEMVER2),
|
|
1377
|
+
contract: z2.number().int(),
|
|
1378
|
+
/** sha256 y tamaño de cada fichero del paquete (salvo release.json): tienen que ser EXACTAMENTE estos. */
|
|
1379
|
+
files: z2.strictObject({
|
|
1380
|
+
"manifest.json": digestSchema,
|
|
1381
|
+
"server.js": digestSchema.optional(),
|
|
1382
|
+
"ui.js": digestSchema.optional(),
|
|
1383
|
+
"locales.json": digestSchema.optional()
|
|
1384
|
+
}),
|
|
1385
|
+
/** La fuente, que va aparte a la plataforma (§2.1). */
|
|
1386
|
+
source: digestSchema,
|
|
1387
|
+
/** Con qué se compiló: la plataforma recompila con lo mismo (§2.1, punto 5). */
|
|
1388
|
+
build: z2.strictObject({
|
|
1389
|
+
kit: z2.string().regex(TOOL_VERSION),
|
|
1390
|
+
esbuild: z2.string().regex(TOOL_VERSION),
|
|
1391
|
+
node: z2.string().regex(TOOL_VERSION),
|
|
1392
|
+
/** El gestor y su versión exacta (`pnpm@10.30.3`): con él se instala para recompilar (§2.3, punto 4). */
|
|
1393
|
+
packageManager: z2.string().regex(/^(npm|pnpm|yarn|bun)@\d+\.\d+\.\d+$/)
|
|
1394
|
+
})
|
|
1395
|
+
});
|
|
1396
|
+
function buildRecord(input) {
|
|
1397
|
+
const record = {
|
|
1398
|
+
namespace: input.manifest.namespace,
|
|
1399
|
+
version: input.manifest.version,
|
|
1400
|
+
contract: input.manifest.contract,
|
|
1401
|
+
files: input.digests,
|
|
1402
|
+
source: input.source,
|
|
1403
|
+
build: input.build
|
|
1404
|
+
};
|
|
1405
|
+
const r = recordSchema.safeParse(record);
|
|
1406
|
+
if (!r.success) fail3(`Registro no v\xE1lido: ${r.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
|
|
1407
|
+
return r.data;
|
|
1408
|
+
}
|
|
1409
|
+
function signAsAuthor(record, privateKeyPem) {
|
|
1410
|
+
const key = privateKeyObject(privateKeyPem);
|
|
1411
|
+
return { publicKey: publicOf(key).publicKey, envelope: seal(PAYLOAD_TYPES2.release, recordSchema.parse(record), key) };
|
|
1412
|
+
}
|
|
1413
|
+
var rotationSchema = z2.strictObject({
|
|
1414
|
+
from: z2.string().regex(KEY_ID),
|
|
1415
|
+
to: z2.strictObject({ keyId: z2.string().regex(KEY_ID), publicKey: z2.string() }),
|
|
1416
|
+
at: z2.iso.datetime()
|
|
1417
|
+
});
|
|
1418
|
+
var approvalSchema = z2.strictObject({
|
|
1419
|
+
/** sha256 de los bytes del registro que firmó el autor. */
|
|
1420
|
+
release: z2.string().regex(SHA256),
|
|
1421
|
+
/** La firma del autor, tal cual: la aprobación vale solo para ESTE registro con ESTA firma. */
|
|
1422
|
+
authorSignature: z2.string(),
|
|
1423
|
+
namespace: z2.string(),
|
|
1424
|
+
version: z2.string().regex(SEMVER2),
|
|
1425
|
+
/** Certificación: esta clave es de este autor, y es el dueño de `namespace`. */
|
|
1426
|
+
author: z2.strictObject({ id: z2.string().min(1), name: z2.string().min(1), keyId: z2.string().regex(KEY_ID), publicKey: z2.string() }),
|
|
1427
|
+
level: z2.enum(APPROVAL_LEVELS),
|
|
1428
|
+
/** Solo en `private`: las instancias en las que se puede instalar. */
|
|
1429
|
+
instances: z2.array(z2.string().min(1)).min(1).optional(),
|
|
1430
|
+
/** Traspaso: la plataforma acepta que esta clave sustituya a `from` sin cadena de cambios (clave perdida o nuevo dueño). */
|
|
1431
|
+
transfer: z2.strictObject({ from: z2.string().regex(KEY_ID) }).optional(),
|
|
1432
|
+
reviewedAt: z2.iso.datetime()
|
|
1433
|
+
}).refine((a) => a.level === "private" === (a.instances !== void 0), {
|
|
1434
|
+
error: "instances va solo, y siempre, con el nivel private."
|
|
1435
|
+
});
|
|
1436
|
+
var APPROVAL_KEY_PURPOSE = "plugin-approval";
|
|
1437
|
+
var certificateSchema = z2.strictObject({
|
|
1438
|
+
keyId: z2.string().regex(KEY_ID),
|
|
1439
|
+
publicKey: z2.string(),
|
|
1440
|
+
purpose: z2.literal(APPROVAL_KEY_PURPOSE),
|
|
1441
|
+
/** Plazo: una aprobación vale si se firmó dentro (su `reviewedAt`). */
|
|
1442
|
+
notBefore: z2.iso.datetime(),
|
|
1443
|
+
notAfter: z2.iso.datetime()
|
|
1444
|
+
}).refine((c) => Date.parse(c.notBefore) < Date.parse(c.notAfter), { error: "notBefore tiene que ser anterior a notAfter." });
|
|
1445
|
+
function openApprovalKeyCertificate(envelope, rootKeys) {
|
|
1446
|
+
const keyid = envelope.signatures[0]?.keyid;
|
|
1447
|
+
const root = rootKeys.keys.find((k) => k.keyId === keyid);
|
|
1448
|
+
if (!root) fail3(`La clave de aprobaciones est\xE1 certificada por una ra\xEDz que este motor no conoce (${keyid}).`);
|
|
1449
|
+
if (keyIdOf2(root.publicKey) !== root.keyId) fail3(`La ra\xEDz ${root.keyId} no corresponde a su huella.`);
|
|
1450
|
+
const cert = parseJson(open(envelope, PAYLOAD_TYPES2.approvalKey, root, "Certificado de la clave de aprobaciones"), certificateSchema, "Certificado de la clave de aprobaciones");
|
|
1451
|
+
if (keyIdOf2(cert.publicKey) !== cert.keyId) fail3("El certificado lleva una clave que no corresponde a su huella.");
|
|
1452
|
+
return cert;
|
|
1453
|
+
}
|
|
1454
|
+
var releaseFileSchema = z2.strictObject({
|
|
1455
|
+
author: z2.strictObject({ publicKey: z2.string(), envelope: envelopeSchema }),
|
|
1456
|
+
rotations: z2.array(envelopeSchema).max(MAX_ROTATIONS).default([])
|
|
1457
|
+
});
|
|
1458
|
+
function releaseFile(parts) {
|
|
1459
|
+
return Buffer.from(JSON.stringify({ author: parts.author, rotations: parts.rotations ?? [] }, null, 2) + "\n");
|
|
1460
|
+
}
|
|
1461
|
+
function parseReleaseFile(raw) {
|
|
1462
|
+
return parseJson(raw, releaseFileSchema, "release.json");
|
|
1463
|
+
}
|
|
1464
|
+
var approvalFileSchema = z2.strictObject({ certificate: envelopeSchema, approval: envelopeSchema });
|
|
1465
|
+
var approvalFileName = (m) => `${m.namespace}-${m.version}.approval.json`;
|
|
1466
|
+
function parseApprovalFile(raw) {
|
|
1467
|
+
if (raw.length > 64 * 1024) fail3("La aprobaci\xF3n pasa de 64 KB.");
|
|
1468
|
+
return parseJson(raw, approvalFileSchema, "Aprobaci\xF3n");
|
|
1469
|
+
}
|
|
1470
|
+
function openApprovalFile(file, rootKeys) {
|
|
1471
|
+
const cert = openApprovalKeyCertificate(file.certificate, rootKeys);
|
|
1472
|
+
const approvalKey = { keyId: cert.keyId, publicKey: cert.publicKey };
|
|
1473
|
+
const approval = parseJson(open(file.approval, PAYLOAD_TYPES2.approval, approvalKey, "Aprobaci\xF3n de la plataforma"), approvalSchema, "Aprobaci\xF3n de la plataforma");
|
|
1474
|
+
const reviewed = Date.parse(approval.reviewedAt);
|
|
1475
|
+
if (reviewed < Date.parse(cert.notBefore) || reviewed > Date.parse(cert.notAfter)) {
|
|
1476
|
+
fail3("La aprobaci\xF3n se firm\xF3 fuera del plazo de la clave de aprobaciones.");
|
|
1477
|
+
}
|
|
1478
|
+
return approval;
|
|
1479
|
+
}
|
|
1480
|
+
var sameDigest = (a, b) => a === void 0 && b === void 0 || !!a && !!b && a.sha256 === b.sha256 && a.size === b.size;
|
|
1481
|
+
function verifyPluginRelease(pkg, opts) {
|
|
1482
|
+
const raw = pkg.files["release.json"];
|
|
1483
|
+
if (!raw) fail3("El paquete no lleva release.json: no est\xE1 firmado.");
|
|
1484
|
+
const rel = parseReleaseFile(raw);
|
|
1485
|
+
const authorKey = { keyId: keyIdOf2(rel.author.publicKey), publicKey: rel.author.publicKey };
|
|
1486
|
+
const body = open(rel.author.envelope, PAYLOAD_TYPES2.release, authorKey, "Registro del autor");
|
|
1487
|
+
const record = parseJson(body, recordSchema, "Registro del autor");
|
|
1488
|
+
const m = pkg.manifest;
|
|
1489
|
+
if (record.namespace !== m.namespace || record.version !== m.version || record.contract !== m.contract) {
|
|
1490
|
+
fail3(`El registro es de ${record.namespace} ${record.version} (contrato ${record.contract}); el paquete, de ${m.namespace} ${m.version} (contrato ${m.contract}).`);
|
|
1491
|
+
}
|
|
1492
|
+
for (const name of SIGNED_FILES) {
|
|
1493
|
+
if (!sameDigest(record.files[name], pkg.digests[name])) fail3(`${name} no es el que firm\xF3 el autor.`);
|
|
1494
|
+
}
|
|
1495
|
+
let approval = null;
|
|
1496
|
+
if (opts.approval) {
|
|
1497
|
+
approval = openApprovalFile(opts.approval, opts.rootKeys);
|
|
1498
|
+
if (approval.release !== sha256(body) || approval.authorSignature !== rel.author.envelope.signatures[0].sig) {
|
|
1499
|
+
fail3("La aprobaci\xF3n de la plataforma es de otro registro.");
|
|
1500
|
+
}
|
|
1501
|
+
if (approval.author.keyId !== authorKey.keyId || approval.author.publicKey !== authorKey.publicKey) {
|
|
1502
|
+
fail3("La plataforma no certifica la clave con la que firm\xF3 el autor.");
|
|
1503
|
+
}
|
|
1504
|
+
if (approval.namespace !== record.namespace || approval.version !== record.version) fail3("La aprobaci\xF3n es de otra versi\xF3n.");
|
|
1505
|
+
if (approval.level === "private" && !(opts.instanceId && approval.instances.includes(opts.instanceId))) {
|
|
1506
|
+
fail3("Es un plugin privado de otra instalaci\xF3n.");
|
|
1507
|
+
}
|
|
1508
|
+
} else if (!opts.allowUnreviewed) {
|
|
1509
|
+
fail3("Falta la aprobaci\xF3n de la plataforma.");
|
|
1510
|
+
}
|
|
1511
|
+
return { record, approval, authorKey, trust: trustOf(authorKey, rel.rotations, approval, opts.pinnedAuthorKey ?? null) };
|
|
1512
|
+
}
|
|
1513
|
+
function trustOf(authorKey, rotations, approval, pinned) {
|
|
1514
|
+
if (!pinned) return "new";
|
|
1515
|
+
if (pinned.keyId === authorKey.keyId && pinned.publicKey === authorKey.publicKey) return "same";
|
|
1516
|
+
let current = pinned;
|
|
1517
|
+
const seen = /* @__PURE__ */ new Set([current.keyId]);
|
|
1518
|
+
for (let step = 0; step < rotations.length; step++) {
|
|
1519
|
+
const next = rotations.find((r) => r.signatures[0]?.keyid === current.keyId);
|
|
1520
|
+
if (!next) break;
|
|
1521
|
+
const change = parseJson(open(next, PAYLOAD_TYPES2.rotation, current, "Cambio de clave"), rotationSchema, "Cambio de clave");
|
|
1522
|
+
if (change.from !== current.keyId || keyIdOf2(change.to.publicKey) !== change.to.keyId) fail3("Cambio de clave mal formado.");
|
|
1523
|
+
if (seen.has(change.to.keyId)) fail3("La cadena de cambios de clave da vueltas.");
|
|
1524
|
+
seen.add(change.to.keyId);
|
|
1525
|
+
current = change.to;
|
|
1526
|
+
if (current.keyId === authorKey.keyId && current.publicKey === authorKey.publicKey) return "rotated";
|
|
1527
|
+
}
|
|
1528
|
+
if (approval?.transfer?.from === pinned.keyId) return "transfer";
|
|
1529
|
+
return fail3("Est\xE1 firmado con una clave distinta de la del autor del plugin instalado, sin un cambio de clave autorizado.");
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
// src/source.ts
|
|
1533
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
1534
|
+
import { gunzipSync as gunzipSync2 } from "node:zlib";
|
|
1535
|
+
var MAX_SOURCE_BYTES = 5 * 1024 * 1024;
|
|
1536
|
+
var MAX_SOURCE_UNPACKED_BYTES = 25 * 1024 * 1024;
|
|
1537
|
+
var MAX_SOURCE_FILES = 2e3;
|
|
1538
|
+
var PluginSourceError = class extends Error {
|
|
1539
|
+
};
|
|
1540
|
+
var fail4 = (message) => {
|
|
1541
|
+
throw new PluginSourceError(message);
|
|
1542
|
+
};
|
|
1543
|
+
var SEGMENT = /^[A-Za-z0-9._@+-]+$/;
|
|
1544
|
+
function isSourcePath(path) {
|
|
1545
|
+
if (!path || path.length > 255 || path.startsWith("/")) return false;
|
|
1546
|
+
return path.split("/").every((s2) => SEGMENT.test(s2) && s2 !== "." && s2 !== "..");
|
|
1547
|
+
}
|
|
1548
|
+
function splitPath(path) {
|
|
1549
|
+
if (path.length <= 100) return { prefix: "", name: path };
|
|
1550
|
+
for (let i = path.indexOf("/"); i >= 0; i = path.indexOf("/", i + 1)) {
|
|
1551
|
+
const prefix = path.slice(0, i);
|
|
1552
|
+
const name = path.slice(i + 1);
|
|
1553
|
+
if (prefix.length <= 155 && name.length <= 100) return { prefix, name };
|
|
1554
|
+
}
|
|
1555
|
+
return fail4(`"${path}": la ruta es demasiado larga para la fuente.`);
|
|
1556
|
+
}
|
|
1557
|
+
function packSource(files) {
|
|
1558
|
+
if (files.size > MAX_SOURCE_FILES) fail4(`La fuente lleva ${files.size} ficheros; el m\xE1ximo es ${MAX_SOURCE_FILES}.`);
|
|
1559
|
+
const parts = [];
|
|
1560
|
+
for (const path of [...files.keys()].sort()) {
|
|
1561
|
+
if (!isSourcePath(path)) fail4(`"${path}" no es una ruta v\xE1lida para la fuente.`);
|
|
1562
|
+
const data = files.get(path);
|
|
1563
|
+
const { prefix, name } = splitPath(path);
|
|
1564
|
+
parts.push(header(name, data.length, prefix), padded(data));
|
|
1565
|
+
}
|
|
1566
|
+
parts.push(Buffer.alloc(BLOCK * 2));
|
|
1567
|
+
const tar = Buffer.concat(parts);
|
|
1568
|
+
if (tar.length > MAX_SOURCE_UNPACKED_BYTES) fail4(`La fuente ocupa ${tar.length} bytes sin comprimir; el m\xE1ximo es ${MAX_SOURCE_UNPACKED_BYTES}.`);
|
|
1569
|
+
const gz = gzipReproducible(tar);
|
|
1570
|
+
if (gz.length > MAX_SOURCE_BYTES) fail4(`La fuente ocupa ${gz.length} bytes; el m\xE1ximo es ${MAX_SOURCE_BYTES}.`);
|
|
1571
|
+
return gz;
|
|
1572
|
+
}
|
|
1573
|
+
function readSource(gz) {
|
|
1574
|
+
if (gz.length > MAX_SOURCE_BYTES) fail4(`La fuente ocupa ${gz.length} bytes; el m\xE1ximo es ${MAX_SOURCE_BYTES}.`);
|
|
1575
|
+
let tar = Buffer.alloc(0);
|
|
1576
|
+
try {
|
|
1577
|
+
tar = gunzipSync2(gz, { maxOutputLength: MAX_SOURCE_UNPACKED_BYTES });
|
|
1578
|
+
} catch (e) {
|
|
1579
|
+
fail4(
|
|
1580
|
+
e.code === "ERR_BUFFER_TOO_LARGE" ? `La fuente pasa de ${MAX_SOURCE_UNPACKED_BYTES} bytes sin comprimir.` : "La fuente no es un .tgz v\xE1lido."
|
|
1581
|
+
);
|
|
1582
|
+
}
|
|
1583
|
+
if (tar.length % BLOCK !== 0) fail4("La fuente no es un tar v\xE1lido (tama\xF1o).");
|
|
1584
|
+
const files = /* @__PURE__ */ new Map();
|
|
1585
|
+
let off = 0;
|
|
1586
|
+
for (; ; ) {
|
|
1587
|
+
if (off + BLOCK > tar.length) fail4("La fuente no es un tar v\xE1lido (termina sin cierre).");
|
|
1588
|
+
const h = tar.subarray(off, off + BLOCK);
|
|
1589
|
+
if (isZero(h)) {
|
|
1590
|
+
if (off + 2 * BLOCK > tar.length || !isZero(tar.subarray(off))) fail4("La fuente no es un tar v\xE1lido (datos tras el final).");
|
|
1591
|
+
break;
|
|
1592
|
+
}
|
|
1593
|
+
if (octalField(h, 148, 8, "suma de control", fail4) !== checksum(h)) fail4("La fuente no es un tar v\xE1lido (suma de control).");
|
|
1594
|
+
if (h.toString("latin1", 257, 263) !== "ustar\0" || h.toString("latin1", 263, 265) !== "00") fail4("La fuente no es un tar ustar.");
|
|
1595
|
+
const prefix = field(h, 345, 155);
|
|
1596
|
+
const name = field(h, 0, 100);
|
|
1597
|
+
const path = prefix ? `${prefix}/${name}` : name;
|
|
1598
|
+
const type = String.fromCharCode(h[156]);
|
|
1599
|
+
if (type !== "0") fail4(`"${path}" no es un fichero normal: solo se admiten ficheros.`);
|
|
1600
|
+
if (!isZero(h.subarray(157, 257))) fail4(`"${path}" lleva un destino de enlace.`);
|
|
1601
|
+
if (!isSourcePath(path)) fail4(`"${path}" no es una ruta v\xE1lida para la fuente.`);
|
|
1602
|
+
if (files.has(path)) fail4(`La fuente lleva "${path}" dos veces.`);
|
|
1603
|
+
if (files.size >= MAX_SOURCE_FILES) fail4(`La fuente lleva m\xE1s de ${MAX_SOURCE_FILES} ficheros.`);
|
|
1604
|
+
const size = octalField(h, 124, 12, "tama\xF1o", fail4);
|
|
1605
|
+
const start = off + BLOCK;
|
|
1606
|
+
const end = start + Math.ceil(size / BLOCK) * BLOCK;
|
|
1607
|
+
if (end > tar.length) fail4(`"${path}" est\xE1 cortado.`);
|
|
1608
|
+
if (!isZero(tar.subarray(start + size, end))) fail4(`"${path}" lleva datos tras su final.`);
|
|
1609
|
+
files.set(path, Buffer.from(tar.subarray(start, start + size)));
|
|
1610
|
+
off = end;
|
|
1611
|
+
}
|
|
1612
|
+
return files;
|
|
1613
|
+
}
|
|
1614
|
+
function sourceDigest(gz) {
|
|
1615
|
+
return { sha256: createHash4("sha256").update(gz).digest("hex"), size: gz.length };
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
// src/build.ts
|
|
1619
|
+
var KIT_VERSION = JSON.parse(readFileSync3(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
1620
|
+
var PluginBuildError = class extends Error {
|
|
1621
|
+
};
|
|
1622
|
+
var fail5 = (message) => {
|
|
1623
|
+
throw new PluginBuildError(message);
|
|
1624
|
+
};
|
|
1625
|
+
var ENTRIES = { "server.js": ["src/server.ts"], "ui.js": ["src/ui.ts", "src/ui.tsx"] };
|
|
1626
|
+
var BUILT = [...Object.keys(ENTRIES), "locales.json"];
|
|
1627
|
+
var isUiEntry = (entry) => ENTRIES["ui.js"].includes(entry);
|
|
1628
|
+
function entryOf(dir, out) {
|
|
1629
|
+
const found = ENTRIES[out].filter((e) => existsSync3(join3(dir, e)));
|
|
1630
|
+
if (found.length > 1) fail5(`Sobra una de las dos: ${found.join(" y ")}.`);
|
|
1631
|
+
return found[0] ?? null;
|
|
1632
|
+
}
|
|
1633
|
+
var DIST = "dist";
|
|
1634
|
+
var DIST_BUILD = `${DIST}/build`;
|
|
1635
|
+
var sourceFileName = (m) => `${m.namespace}-${m.version}.source.tgz`;
|
|
1636
|
+
var PACKAGE_MANAGERS = {
|
|
1637
|
+
npm: { lockfile: "package-lock.json", install: () => ["ci", "--ignore-scripts", "--no-audit", "--no-fund"] },
|
|
1638
|
+
pnpm: { lockfile: "pnpm-lock.yaml", install: () => ["install", "--frozen-lockfile", "--ignore-scripts"] },
|
|
1639
|
+
yarn: {
|
|
1640
|
+
lockfile: "yarn.lock",
|
|
1641
|
+
install: (major2) => major2 >= 2 ? ["install", "--immutable", "--mode=skip-build"] : ["install", "--frozen-lockfile", "--ignore-scripts", "--non-interactive"]
|
|
1642
|
+
},
|
|
1643
|
+
bun: { lockfile: "bun.lock", install: () => ["install", "--frozen-lockfile", "--ignore-scripts"] }
|
|
1644
|
+
};
|
|
1645
|
+
function parsePackageManager(value) {
|
|
1646
|
+
const m = typeof value === "string" ? /^(npm|pnpm|yarn|bun)@(\d+\.\d+\.\d+)(\+[A-Za-z0-9.]+)?$/.exec(value) : null;
|
|
1647
|
+
if (!m) {
|
|
1648
|
+
return fail5(
|
|
1649
|
+
'package.json tiene que decir con qu\xE9 gestor y versi\xF3n exacta se instala, p. ej. "packageManager": "pnpm@10.30.3" (npm, pnpm, yarn o bun).'
|
|
1650
|
+
);
|
|
1651
|
+
}
|
|
1652
|
+
return { name: m[1], version: m[2] };
|
|
1653
|
+
}
|
|
1654
|
+
var major = (version) => Number(version.split(".")[0]);
|
|
1655
|
+
function managerPackage(pm) {
|
|
1656
|
+
if (pm.name === "yarn" && major(pm.version) >= 2) return `@yarnpkg/cli-dist@${pm.version}`;
|
|
1657
|
+
return `${pm.name}@${pm.version}`;
|
|
1658
|
+
}
|
|
1659
|
+
function yarnrc(dir, pm) {
|
|
1660
|
+
const file = join3(dir, ".yarnrc.yml");
|
|
1661
|
+
if (pm.name !== "yarn" || !existsSync3(file)) return null;
|
|
1662
|
+
const data = readFileSync3(file);
|
|
1663
|
+
for (const line of data.toString("utf8").split(/\r?\n/)) {
|
|
1664
|
+
const t = line.trim();
|
|
1665
|
+
if (!t || t.startsWith("#")) continue;
|
|
1666
|
+
if (!/^nodeLinker:\s*["']?(node-modules|pnp|pnpm)["']?$/.test(t)) {
|
|
1667
|
+
fail5(`.yarnrc.yml: solo se admite nodeLinker (la plataforma recompila sin tu configuraci\xF3n). Sobra: ${t}`);
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
return data;
|
|
1671
|
+
}
|
|
1672
|
+
function installEnv() {
|
|
1673
|
+
const env = {};
|
|
1674
|
+
for (const [k, v] of Object.entries(process.env)) if (!/^npm_|^NPM_CONFIG_|^YARN_|^BUN_CONFIG_/i.test(k)) env[k] = v;
|
|
1675
|
+
return {
|
|
1676
|
+
...env,
|
|
1677
|
+
CI: "1",
|
|
1678
|
+
TZ: "UTC",
|
|
1679
|
+
LC_ALL: "C",
|
|
1680
|
+
SOURCE_DATE_EPOCH: "0",
|
|
1681
|
+
npm_config_registry: "https://registry.npmjs.org/",
|
|
1682
|
+
npm_config_update_notifier: "false",
|
|
1683
|
+
YARN_NPM_REGISTRY_SERVER: "https://registry.npmjs.org",
|
|
1684
|
+
YARN_ENABLE_SCRIPTS: "0",
|
|
1685
|
+
// Con Plug'n'Play, esbuild escribe la ruta de cada dependencia en un comentario: con la caché
|
|
1686
|
+
// global sería la de la carpeta personal de quien compila. Dentro del proyecto, es la misma siempre.
|
|
1687
|
+
YARN_ENABLE_GLOBAL_CACHE: "0",
|
|
1688
|
+
YARN_ENABLE_TELEMETRY: "0",
|
|
1689
|
+
BUN_CONFIG_REGISTRY: "https://registry.npmjs.org/"
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
var run = (cmd, args, { cwd, env }) => new Promise((done) => {
|
|
1693
|
+
const child = spawn(cmd, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
|
|
1694
|
+
let output = "";
|
|
1695
|
+
child.stdout.on("data", (d) => output += d);
|
|
1696
|
+
child.stderr.on("data", (d) => output += d);
|
|
1697
|
+
child.on("error", (e) => done({ code: -1, output: e.message }));
|
|
1698
|
+
child.on("close", (code) => done({ code: code ?? -1, output }));
|
|
1699
|
+
});
|
|
1700
|
+
async function install(dir, pm, runner) {
|
|
1701
|
+
const env = installEnv();
|
|
1702
|
+
const args = PACKAGE_MANAGERS[pm.name].install(major(pm.version));
|
|
1703
|
+
const installed = await runner(pm.name, ["--version"], { cwd: dir, env });
|
|
1704
|
+
const direct = installed.code === 0 && installed.output.trim() === pm.version;
|
|
1705
|
+
const r = direct ? await runner(pm.name, args, { cwd: dir, env }) : await runner("npm", ["exec", "--yes", `--package=${managerPackage(pm)}`, "--", pm.name, ...args], { cwd: dir, env });
|
|
1706
|
+
if (r.code !== 0) {
|
|
1707
|
+
fail5(`No se han podido instalar las dependencias con ${pm.name}@${pm.version} desde el lockfile:
|
|
1708
|
+
${r.output.trim().split("\n").slice(-15).join("\n")}`);
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
var NODE_BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
|
|
1712
|
+
function nodeModules(required, browser = false) {
|
|
1713
|
+
return {
|
|
1714
|
+
name: "surnie-node",
|
|
1715
|
+
setup(b) {
|
|
1716
|
+
if (browser) {
|
|
1717
|
+
b.onResolve(
|
|
1718
|
+
{ filter: /^[a-z_:/]+$/ },
|
|
1719
|
+
(args) => args.path.startsWith("node:") || NODE_BUILTINS.has(args.path) || NODE_BUILTINS.has(args.path.split("/")[0]) ? {
|
|
1720
|
+
errors: [
|
|
1721
|
+
{
|
|
1722
|
+
text: `"${args.path}" es un m\xF3dulo de Node: la interfaz (src/ui.ts) corre en el navegador. Usa APIs web, o pide los datos a una funci\xF3n del servidor (functions).`
|
|
1723
|
+
}
|
|
1724
|
+
]
|
|
1725
|
+
} : void 0
|
|
1726
|
+
);
|
|
1727
|
+
return;
|
|
1728
|
+
}
|
|
1729
|
+
const error = (path) => ({
|
|
1730
|
+
errors: [
|
|
1731
|
+
{
|
|
1732
|
+
text: `"${path}" es un m\xF3dulo de Node que un plugin no puede usar (docs/plugins.md \xA75.1): solo ${NODE_COMPAT_MODULES.join(", ")}. Usa APIs web (fetch, crypto.subtle\u2026) o un paquete que no dependa de Node.`
|
|
1733
|
+
}
|
|
1734
|
+
]
|
|
1735
|
+
});
|
|
1736
|
+
b.onResolve({ filter: /^[a-z_:/]+$/ }, async (args) => {
|
|
1737
|
+
if (args.pluginData?.surnieProbe) return void 0;
|
|
1738
|
+
const compat = compatModuleOf(args.path);
|
|
1739
|
+
if (compat) {
|
|
1740
|
+
if (args.kind === "require-call") required.add(compat);
|
|
1741
|
+
return { path: `node:${compat}`, external: true, sideEffects: false };
|
|
1742
|
+
}
|
|
1743
|
+
if (args.path.startsWith("node:")) return error(args.path);
|
|
1744
|
+
if (!NODE_BUILTINS.has(args.path) && !NODE_BUILTINS.has(args.path.split("/")[0])) return void 0;
|
|
1745
|
+
const probe = await b.resolve(args.path, { kind: args.kind, resolveDir: args.resolveDir, importer: args.importer, pluginData: { surnieProbe: true } });
|
|
1746
|
+
return probe.errors.length ? error(args.path) : void 0;
|
|
1747
|
+
});
|
|
1748
|
+
b.onResolve({ filter: /^surnie:node-globals$/ }, () => ({ path: "node-globals", namespace: "surnie", sideEffects: false }));
|
|
1749
|
+
b.onLoad({ filter: /.*/, namespace: "surnie" }, () => ({
|
|
1750
|
+
contents: 'export { Buffer } from "node:buffer";\nexport { default as process } from "node:process";\n',
|
|
1751
|
+
loader: "js",
|
|
1752
|
+
resolveDir: "."
|
|
1753
|
+
}));
|
|
1754
|
+
}
|
|
1755
|
+
};
|
|
1756
|
+
}
|
|
1757
|
+
function options(dir, entry, required, banner) {
|
|
1758
|
+
return {
|
|
1759
|
+
absWorkingDir: dir,
|
|
1760
|
+
entryPoints: [entry],
|
|
1761
|
+
outfile: "out.js",
|
|
1762
|
+
bundle: true,
|
|
1763
|
+
write: false,
|
|
1764
|
+
metafile: true,
|
|
1765
|
+
format: "esm",
|
|
1766
|
+
platform: "neutral",
|
|
1767
|
+
target: "es2023",
|
|
1768
|
+
mainFields: ["browser", "module", "main"],
|
|
1769
|
+
conditions: ["worker", "browser"],
|
|
1770
|
+
minify: false,
|
|
1771
|
+
sourcemap: false,
|
|
1772
|
+
legalComments: "inline",
|
|
1773
|
+
charset: "utf8",
|
|
1774
|
+
define: { "process.env.NODE_ENV": '"production"', global: "globalThis" },
|
|
1775
|
+
// `Buffer` y `process` de la capa de Node, solo en el servidor (la interfaz corre en el navegador)
|
|
1776
|
+
...isUiEntry(entry) ? {} : { inject: ["surnie:node-globals"] },
|
|
1777
|
+
...banner ? { banner: { js: banner } } : {},
|
|
1778
|
+
logLevel: "silent",
|
|
1779
|
+
plugins: [nodeModules(required, isUiEntry(entry))]
|
|
1780
|
+
};
|
|
1781
|
+
}
|
|
1782
|
+
function describeErrors(errors) {
|
|
1783
|
+
return errors.map((e) => e.location ? `${e.location.file}:${e.location.line}:${e.location.column}: ${e.text}` : e.text).join("\n");
|
|
1784
|
+
}
|
|
1785
|
+
async function compileEntry(dir, entry) {
|
|
1786
|
+
let result;
|
|
1787
|
+
try {
|
|
1788
|
+
const required = /* @__PURE__ */ new Set();
|
|
1789
|
+
result = await esbuild(options(dir, entry, required));
|
|
1790
|
+
const banner = requireBanner(required);
|
|
1791
|
+
if (banner) result = await esbuild(options(dir, entry, /* @__PURE__ */ new Set(), banner));
|
|
1792
|
+
} catch (e) {
|
|
1793
|
+
const errors = e.errors;
|
|
1794
|
+
return fail5(`No compila ${entry}:
|
|
1795
|
+
${errors ? describeErrors(errors) : e.message}`);
|
|
1796
|
+
}
|
|
1797
|
+
const inputs = Object.keys(result.metafile.inputs).filter((path) => !path.startsWith("surnie:"));
|
|
1798
|
+
return { code: Buffer.from(result.outputFiles[0].contents), inputs };
|
|
1799
|
+
}
|
|
1800
|
+
async function compile(dir) {
|
|
1801
|
+
const outputs = {};
|
|
1802
|
+
const inputs = /* @__PURE__ */ new Set();
|
|
1803
|
+
for (const out of Object.keys(ENTRIES)) {
|
|
1804
|
+
const entry = entryOf(dir, out);
|
|
1805
|
+
if (!entry) continue;
|
|
1806
|
+
const r = await compileEntry(dir, entry);
|
|
1807
|
+
outputs[out] = r.code;
|
|
1808
|
+
for (const path of r.inputs) inputs.add(path);
|
|
1809
|
+
}
|
|
1810
|
+
const locales = bundleLocales2(dir);
|
|
1811
|
+
if (locales) {
|
|
1812
|
+
outputs["locales.json"] = locales.data;
|
|
1813
|
+
for (const path of locales.inputs) inputs.add(path);
|
|
1814
|
+
}
|
|
1815
|
+
return { outputs, inputs };
|
|
1816
|
+
}
|
|
1817
|
+
function bundleLocales2(dir) {
|
|
1818
|
+
try {
|
|
1819
|
+
return bundleLocales(dir);
|
|
1820
|
+
} catch (e) {
|
|
1821
|
+
return fail5(e.message);
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
var isDependency = (path) => path.split("/").some((s2) => s2 === "node_modules" || s2 === ".yarn" || s2 === ".pnp.cjs");
|
|
1825
|
+
function tsconfigChain(dir, file, seen = /* @__PURE__ */ new Set()) {
|
|
1826
|
+
if (!existsSync3(join3(dir, file)) || seen.has(file)) return [];
|
|
1827
|
+
seen.add(file);
|
|
1828
|
+
let ext;
|
|
1829
|
+
try {
|
|
1830
|
+
const text2 = readFileSync3(join3(dir, file), "utf8").replace(/\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm, "").replace(/,(\s*[}\]])/g, "$1");
|
|
1831
|
+
ext = JSON.parse(text2).extends;
|
|
1832
|
+
} catch {
|
|
1833
|
+
return [file];
|
|
1834
|
+
}
|
|
1835
|
+
const next = (Array.isArray(ext) ? ext : [ext]).filter((e) => typeof e === "string" && e.startsWith("."));
|
|
1836
|
+
return [file, ...next.flatMap((e) => tsconfigChain(dir, posix.join(posix.dirname(file), e.endsWith(".json") ? e : `${e}.json`), seen))];
|
|
1837
|
+
}
|
|
1838
|
+
function collectSource(dir, inputs, pm) {
|
|
1839
|
+
const paths = /* @__PURE__ */ new Set(["manifest.json", "package.json", PACKAGE_MANAGERS[pm.name].lockfile, ...tsconfigChain(dir, "tsconfig.json")]);
|
|
1840
|
+
for (const input of inputs) {
|
|
1841
|
+
if (isDependency(input)) continue;
|
|
1842
|
+
const rel = relative(dir, resolve(dir, input)).split(sep).join("/");
|
|
1843
|
+
if (rel.startsWith("../")) fail5(`El c\xF3digo importa "${input}", que est\xE1 fuera del proyecto: la fuente tiene que estar dentro.`);
|
|
1844
|
+
paths.add(rel);
|
|
1845
|
+
}
|
|
1846
|
+
const files = /* @__PURE__ */ new Map();
|
|
1847
|
+
for (const path of paths) {
|
|
1848
|
+
if (!isSourcePath(path)) fail5(`"${path}": nombre no admitido en la fuente (letras, d\xEDgitos y . _ @ + -).`);
|
|
1849
|
+
files.set(path, readFileSync3(join3(dir, path)));
|
|
1850
|
+
}
|
|
1851
|
+
const rc = yarnrc(dir, pm);
|
|
1852
|
+
if (rc) files.set(".yarnrc.yml", rc);
|
|
1853
|
+
return files;
|
|
1854
|
+
}
|
|
1855
|
+
async function cleanBuild(source, dir, pm, runner) {
|
|
1856
|
+
for (const [path, data] of readSource(source)) {
|
|
1857
|
+
const target = join3(dir, ...path.split("/"));
|
|
1858
|
+
mkdirSync2(dirname2(target), { recursive: true });
|
|
1859
|
+
writeFileSync2(target, data);
|
|
1860
|
+
}
|
|
1861
|
+
await install(dir, pm, runner);
|
|
1862
|
+
return compile(dir);
|
|
1863
|
+
}
|
|
1864
|
+
function firstDifference(a, b) {
|
|
1865
|
+
const la = a.toString("utf8").split("\n");
|
|
1866
|
+
const lb = b.toString("utf8").split("\n");
|
|
1867
|
+
for (let i = 0; i < Math.max(la.length, lb.length); i++) {
|
|
1868
|
+
if (la[i] !== lb[i]) return `l\xEDnea ${i + 1}:
|
|
1869
|
+
- ${(la[i] ?? "(nada)").slice(0, 200)}
|
|
1870
|
+
+ ${(lb[i] ?? "(nada)").slice(0, 200)}`;
|
|
1871
|
+
}
|
|
1872
|
+
return "(mismo texto)";
|
|
1873
|
+
}
|
|
1874
|
+
function sameOutputs(a, b) {
|
|
1875
|
+
for (const out of BUILT) {
|
|
1876
|
+
const x = a.outputs[out];
|
|
1877
|
+
const y = b.outputs[out];
|
|
1878
|
+
if (!x && !y) continue;
|
|
1879
|
+
if (!x || !y) return `${out}: solo sale en una de las dos.`;
|
|
1880
|
+
if (!x.equals(y)) return `${out}, ${firstDifference(x, y)}`;
|
|
1881
|
+
}
|
|
1882
|
+
return null;
|
|
1883
|
+
}
|
|
1884
|
+
async function pack(dir, { log = () => {
|
|
1885
|
+
}, runner = run } = {}) {
|
|
1886
|
+
dir = resolve(dir);
|
|
1887
|
+
const read = (path, what) => {
|
|
1888
|
+
if (!existsSync3(join3(dir, path))) fail5(`Falta ${path} (${what}).`);
|
|
1889
|
+
return readFileSync3(join3(dir, path));
|
|
1890
|
+
};
|
|
1891
|
+
const manifestBytes = read("manifest.json", "lo que declara el plugin");
|
|
1892
|
+
const manifest = parseManifestBytes(manifestBytes);
|
|
1893
|
+
writePluginTypes(dir);
|
|
1894
|
+
let pkg;
|
|
1895
|
+
try {
|
|
1896
|
+
pkg = JSON.parse(read("package.json", "las dependencias").toString("utf8"));
|
|
1897
|
+
} catch (e) {
|
|
1898
|
+
if (e instanceof PluginBuildError) throw e;
|
|
1899
|
+
return fail5("package.json no es JSON v\xE1lido.");
|
|
1900
|
+
}
|
|
1901
|
+
const pm = parsePackageManager(pkg.packageManager);
|
|
1902
|
+
read(PACKAGE_MANAGERS[pm.name].lockfile, `el lockfile de ${pm.name}, que fija cada dependencia`);
|
|
1903
|
+
log(`Compilando ${manifest.namespace} ${manifest.version}\u2026`);
|
|
1904
|
+
const here = await compile(dir);
|
|
1905
|
+
const source = packSource(collectSource(dir, here.inputs, pm));
|
|
1906
|
+
const tmp = mkdtempSync(join3(tmpdir(), "surnie-pack-"));
|
|
1907
|
+
let first;
|
|
1908
|
+
try {
|
|
1909
|
+
log(`Recompilando desde la fuente con ${pm.name}@${pm.version} (1 de 2)\u2026`);
|
|
1910
|
+
first = await cleanBuild(source, join3(tmp, "a"), pm, runner);
|
|
1911
|
+
log("Recompilando desde la fuente (2 de 2)\u2026");
|
|
1912
|
+
const second = await cleanBuild(source, join3(tmp, "segunda-compilacion", "en-otra-ruta"), pm, runner);
|
|
1913
|
+
const diff = sameOutputs(first, second);
|
|
1914
|
+
if (diff) {
|
|
1915
|
+
fail5(
|
|
1916
|
+
`Dos compilaciones de la misma fuente no salen iguales, y la plataforma no podr\xEDa comprobar el paquete. Algo depende de la ruta, la fecha o la m\xE1quina. Primera diferencia en ${diff}`
|
|
1917
|
+
);
|
|
1918
|
+
}
|
|
1919
|
+
} finally {
|
|
1920
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
1921
|
+
}
|
|
1922
|
+
const warning = sameOutputs(here, first) ? "Lo compilado en tu carpeta no es id\xE9ntico a lo compilado desde la fuente (p. ej., tus node_modules no coinciden con el lockfile, o yarn lee su cach\xE9 global). El paquete lleva lo compilado desde la fuente." : void 0;
|
|
1923
|
+
const files = { "manifest.json": manifestBytes, ...first.outputs };
|
|
1924
|
+
packPlugin({ manifest: manifestBytes, server: files["server.js"], ui: files["ui.js"], locales: files["locales.json"] });
|
|
1925
|
+
const record = buildRecord({
|
|
1926
|
+
manifest,
|
|
1927
|
+
digests: fileDigests(files),
|
|
1928
|
+
source: sourceDigest(source),
|
|
1929
|
+
build: { kit: KIT_VERSION, esbuild: ESBUILD_VERSION, node: process.versions.node, packageManager: `${pm.name}@${pm.version}` }
|
|
1930
|
+
});
|
|
1931
|
+
rmSync(join3(dir, DIST), { recursive: true, force: true });
|
|
1932
|
+
mkdirSync2(join3(dir, DIST_BUILD), { recursive: true });
|
|
1933
|
+
const written = [];
|
|
1934
|
+
const write = (path, data) => {
|
|
1935
|
+
writeFileSync2(join3(dir, path), data);
|
|
1936
|
+
written.push(path);
|
|
1937
|
+
};
|
|
1938
|
+
for (const [name, data] of Object.entries(files)) write(`${DIST_BUILD}/${name}`, data);
|
|
1939
|
+
write(`${DIST_BUILD}/record.json`, `${JSON.stringify(record, null, 2)}
|
|
1940
|
+
`);
|
|
1941
|
+
write(`${DIST}/${sourceFileName(manifest)}`, source);
|
|
1942
|
+
return { manifest, record, warning, written };
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
// src/dev.ts
|
|
1946
|
+
import { spawn as spawn2, spawnSync } from "node:child_process";
|
|
1947
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync4, watch, writeFileSync as writeFileSync3 } from "node:fs";
|
|
1948
|
+
import { dirname as dirname3, join as join4, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
|
|
1949
|
+
var DEV_CODE = join4(".surnie", "dev", "server.js");
|
|
1950
|
+
var DEV_UI_CODE = join4(".surnie", "dev", "ui.js");
|
|
1951
|
+
var DEV_JSON = "dev.json";
|
|
1952
|
+
var DEV_IMAGE = "surnie/surnie:latest";
|
|
1953
|
+
var DEV_CONTAINER = "surnie-plugin-dev";
|
|
1954
|
+
var DEV_VOLUME = "surnie-plugin-dev";
|
|
1955
|
+
var DEV_PORT = 3e3;
|
|
1956
|
+
var DEV_MOUNT = "/surnie-dev";
|
|
1957
|
+
function starterDevJson(m) {
|
|
1958
|
+
const grants = {};
|
|
1959
|
+
for (const p of [...m.permissions.required, ...m.permissions.optional]) {
|
|
1960
|
+
grants[p.id] = p.kind === "content" ? { collections: {} } : p.kind === "fields" ? { collections: [] } : {};
|
|
1961
|
+
}
|
|
1962
|
+
const settings = Object.fromEntries(m.settings.map((s2) => [s2.key, s2.default ?? null]));
|
|
1963
|
+
return `${JSON.stringify({ grants, settings }, null, 2)}
|
|
1964
|
+
`;
|
|
1965
|
+
}
|
|
1966
|
+
async function devBuild(dir) {
|
|
1967
|
+
const targets = [
|
|
1968
|
+
{ entry: entryOf(dir, "server.js"), out: DEV_CODE },
|
|
1969
|
+
{ entry: entryOf(dir, "ui.js"), out: DEV_UI_CODE }
|
|
1970
|
+
];
|
|
1971
|
+
if (!targets.some((t) => t.entry)) throw new PluginBuildError(`Falta ${ENTRIES["server.js"][0]} o ${ENTRIES["ui.js"][0]}.`);
|
|
1972
|
+
const changed = [];
|
|
1973
|
+
const inputs = [];
|
|
1974
|
+
for (const { entry, out } of targets) {
|
|
1975
|
+
if (!entry) continue;
|
|
1976
|
+
const r = await compileEntry(dir, entry);
|
|
1977
|
+
inputs.push(...r.inputs);
|
|
1978
|
+
const file = join4(dir, out);
|
|
1979
|
+
mkdirSync3(dirname3(file), { recursive: true });
|
|
1980
|
+
if (!existsSync4(file) || !readFileSync4(file).equals(r.code)) {
|
|
1981
|
+
writeFileSync3(file, r.code);
|
|
1982
|
+
changed.push(out);
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
return { changed, inputs };
|
|
1986
|
+
}
|
|
1987
|
+
function dockerRunArgs(o) {
|
|
1988
|
+
if (/[,"]/.test(o.dir)) throw new PluginBuildError(`La ruta del plugin no puede llevar comas ni comillas: ${o.dir}`);
|
|
1989
|
+
const target = `${DEV_MOUNT}/${o.namespace}`;
|
|
1990
|
+
return [
|
|
1991
|
+
"run",
|
|
1992
|
+
"--detach",
|
|
1993
|
+
"--rm",
|
|
1994
|
+
"--name",
|
|
1995
|
+
DEV_CONTAINER,
|
|
1996
|
+
"--publish",
|
|
1997
|
+
`127.0.0.1:${o.port}:3000`,
|
|
1998
|
+
"--volume",
|
|
1999
|
+
`${DEV_VOLUME}:/surnie`,
|
|
2000
|
+
"--mount",
|
|
2001
|
+
`type=bind,src=${o.dir},dst=${target},readonly`,
|
|
2002
|
+
"--env",
|
|
2003
|
+
`APP_URL=http://localhost:${o.port}`,
|
|
2004
|
+
"--env",
|
|
2005
|
+
"SURNIE_DATABASE=pglite",
|
|
2006
|
+
"--env",
|
|
2007
|
+
`SURNIE_DEV_PLUGINS=${target}`,
|
|
2008
|
+
...o.token ? ["--env", "SURNIE_UPDATES_TOKEN"] : [],
|
|
2009
|
+
// Lo mismo que el compose de la imagen única: root solo con lo que usa el lanzador
|
|
2010
|
+
"--cap-drop",
|
|
2011
|
+
"ALL",
|
|
2012
|
+
...["CHOWN", "DAC_OVERRIDE", "FOWNER", "SETUID", "SETGID", "KILL"].flatMap((c) => ["--cap-add", c]),
|
|
2013
|
+
"--security-opt",
|
|
2014
|
+
"no-new-privileges:true",
|
|
2015
|
+
o.image
|
|
2016
|
+
];
|
|
2017
|
+
}
|
|
2018
|
+
var IGNORED = /* @__PURE__ */ new Set(["node_modules", ".surnie", "dist", ".git"]);
|
|
2019
|
+
var docker = (args) => spawnSync("docker", args, { encoding: "utf8" });
|
|
2020
|
+
function ensureDocker() {
|
|
2021
|
+
const r = docker(["version", "--format", "{{.Server.Version}}"]);
|
|
2022
|
+
if (r.error || r.status !== 0) {
|
|
2023
|
+
throw new PluginBuildError(
|
|
2024
|
+
"surnie-plugin dev necesita Docker en marcha (arranca un Surnie de verdad en un contenedor). Inst\xE1lalo o \xE1brelo y vuelve a probar; o usa --no-docker con un Surnie propio."
|
|
2025
|
+
);
|
|
2026
|
+
}
|
|
2027
|
+
if (docker(["container", "inspect", DEV_CONTAINER]).status === 0) {
|
|
2028
|
+
throw new PluginBuildError(`Ya hay un Surnie de desarrollo en marcha (contenedor ${DEV_CONTAINER}): p\xE1ralo con \`docker stop ${DEV_CONTAINER}\`.`);
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
function gitignoreWarning(dir) {
|
|
2032
|
+
const file = join4(dir, ".gitignore");
|
|
2033
|
+
const lines = existsSync4(file) ? readFileSync4(file, "utf8").split(/\r?\n/).map((l) => l.trim()) : [];
|
|
2034
|
+
const missing = [DEV_JSON, ".surnie/"].filter((p) => !lines.includes(p) && !lines.includes(p.replace(/\/$/, "")) && !lines.includes(`/${p}`));
|
|
2035
|
+
return missing.length ? `A\xF1ade a .gitignore: ${missing.join(", ")} (dev.json lleva tus secretos de prueba).` : null;
|
|
2036
|
+
}
|
|
2037
|
+
async function runDev(dir, opts = {}) {
|
|
2038
|
+
dir = resolve2(dir);
|
|
2039
|
+
const log = opts.log ?? ((m) => console.log(m));
|
|
2040
|
+
const port = opts.port ?? DEV_PORT;
|
|
2041
|
+
const image = opts.image ?? DEV_IMAGE;
|
|
2042
|
+
const manifestFile = join4(dir, "manifest.json");
|
|
2043
|
+
if (!existsSync4(manifestFile)) throw new PluginBuildError("Falta manifest.json: ejecuta surnie-plugin dev en la carpeta del plugin.");
|
|
2044
|
+
const manifest = parseManifestBytes(readFileSync4(manifestFile));
|
|
2045
|
+
writePluginTypes(dir);
|
|
2046
|
+
if (!existsSync4(join4(dir, DEV_JSON))) {
|
|
2047
|
+
writeFileSync3(join4(dir, DEV_JSON), starterDevJson(manifest));
|
|
2048
|
+
log(`\u2714 ${DEV_JSON} creado: concede ah\xED los permisos (las colecciones de tu Surnie de desarrollo) y los ajustes.`);
|
|
2049
|
+
}
|
|
2050
|
+
const warning = gitignoreWarning(dir);
|
|
2051
|
+
if (warning) log(`\u26A0 ${warning}`);
|
|
2052
|
+
const build = async () => {
|
|
2053
|
+
try {
|
|
2054
|
+
const r = await devBuild(dir);
|
|
2055
|
+
for (const out of r.changed) log(`\u2714 compilado ${out}`);
|
|
2056
|
+
} catch (e) {
|
|
2057
|
+
log(`\u2718 ${e.message}`);
|
|
2058
|
+
}
|
|
2059
|
+
};
|
|
2060
|
+
await build();
|
|
2061
|
+
let timer = null;
|
|
2062
|
+
let manifestChanged = false;
|
|
2063
|
+
const onChange = (file) => {
|
|
2064
|
+
const rel = relative2(dir, file);
|
|
2065
|
+
if (rel.split(sep2).some((s2) => IGNORED.has(s2))) return;
|
|
2066
|
+
if (rel === "manifest.json") manifestChanged = true;
|
|
2067
|
+
else if (rel === DEV_JSON) return;
|
|
2068
|
+
if (timer) clearTimeout(timer);
|
|
2069
|
+
timer = setTimeout(async () => {
|
|
2070
|
+
if (manifestChanged) {
|
|
2071
|
+
manifestChanged = false;
|
|
2072
|
+
try {
|
|
2073
|
+
writePluginTypes(dir);
|
|
2074
|
+
log(`\u2714 tipos al d\xEDa (${TYPES_FILE})`);
|
|
2075
|
+
} catch (e) {
|
|
2076
|
+
log(`\u2718 manifest.json: ${e.message}`);
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
await build();
|
|
2080
|
+
}, 150);
|
|
2081
|
+
};
|
|
2082
|
+
const watchers = [
|
|
2083
|
+
watch(dir, { recursive: true }, (_e, name) => {
|
|
2084
|
+
if (name) onChange(join4(dir, name.toString()));
|
|
2085
|
+
})
|
|
2086
|
+
];
|
|
2087
|
+
let logs = null;
|
|
2088
|
+
const stop = () => {
|
|
2089
|
+
for (const w of watchers) w.close();
|
|
2090
|
+
logs?.kill();
|
|
2091
|
+
if (opts.docker !== false) docker(["stop", "--time", "20", DEV_CONTAINER]);
|
|
2092
|
+
};
|
|
2093
|
+
if (opts.docker !== false) {
|
|
2094
|
+
ensureDocker();
|
|
2095
|
+
if (opts.reset) {
|
|
2096
|
+
docker(["volume", "rm", DEV_VOLUME]);
|
|
2097
|
+
log("\u2714 volumen de desarrollo borrado: instalaci\xF3n nueva.");
|
|
2098
|
+
}
|
|
2099
|
+
const token = !!process.env.SURNIE_UPDATES_TOKEN?.trim();
|
|
2100
|
+
const r = docker(dockerRunArgs({ dir, namespace: manifest.namespace, port, image, token }));
|
|
2101
|
+
if (r.status !== 0) {
|
|
2102
|
+
stop();
|
|
2103
|
+
throw new PluginBuildError(`No arranca el contenedor de Surnie:
|
|
2104
|
+
${(r.stderr || r.stdout).trim()}`);
|
|
2105
|
+
}
|
|
2106
|
+
log(`
|
|
2107
|
+
\u25B6 Surnie en http://localhost:${port}/admin, con ${manifest.name} (${manifest.namespace}) sin firmar.`);
|
|
2108
|
+
log(" La primera vez descarga el motor (un minuto) y te pide crear la cuenta de administrador.");
|
|
2109
|
+
log(` Guardar recompila; ${DEV_JSON} y manifest.json se recargan solos. Ctrl+C para parar.
|
|
2110
|
+
`);
|
|
2111
|
+
logs = spawn2("docker", ["logs", "--follow", "--since", "0s", DEV_CONTAINER], { stdio: "inherit" });
|
|
2112
|
+
} else {
|
|
2113
|
+
log(`
|
|
2114
|
+
\u25B6 Compilando al guardar en ${dirname3(DEV_CODE)}. Arranca tu Surnie con SURNIE_DEV_PLUGINS=${dir}. Ctrl+C para parar.
|
|
2115
|
+
`);
|
|
2116
|
+
}
|
|
2117
|
+
await new Promise((done) => {
|
|
2118
|
+
const quit = () => {
|
|
2119
|
+
log("\nParando\u2026");
|
|
2120
|
+
stop();
|
|
2121
|
+
done();
|
|
2122
|
+
};
|
|
2123
|
+
process.once("SIGINT", quit);
|
|
2124
|
+
process.once("SIGTERM", quit);
|
|
2125
|
+
});
|
|
2126
|
+
}
|
|
2127
|
+
|
|
2128
|
+
// src/publish.ts
|
|
2129
|
+
import { existsSync as existsSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "node:fs";
|
|
2130
|
+
import { join as join5, resolve as resolve3 } from "node:path";
|
|
2131
|
+
var PluginPublishError = class extends Error {
|
|
2132
|
+
};
|
|
2133
|
+
var fail6 = (message) => {
|
|
2134
|
+
throw new PluginPublishError(message);
|
|
2135
|
+
};
|
|
2136
|
+
var PUBLISH_TOKEN_ENV = "SURNIE_PUBLISH_TOKEN";
|
|
2137
|
+
var PLATFORM_URL_ENV = "SURNIE_PLATFORM_URL";
|
|
2138
|
+
var DEFAULT_PLATFORM_URL = "https://api.surnie.app";
|
|
2139
|
+
var DEFAULT_TIMEOUT_MS = 30 * 6e4;
|
|
2140
|
+
function platformUrl(env = process.env) {
|
|
2141
|
+
const raw = env[PLATFORM_URL_ENV] || DEFAULT_PLATFORM_URL;
|
|
2142
|
+
let url;
|
|
2143
|
+
try {
|
|
2144
|
+
url = new URL(raw);
|
|
2145
|
+
} catch {
|
|
2146
|
+
return fail6(`${PLATFORM_URL_ENV} no es una URL: ${raw}`);
|
|
2147
|
+
}
|
|
2148
|
+
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
|
|
2149
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) fail6(`${PLATFORM_URL_ENV} tiene que ser https.`);
|
|
2150
|
+
return url.origin;
|
|
2151
|
+
}
|
|
2152
|
+
function signedBuild(dir) {
|
|
2153
|
+
dir = resolve3(dir);
|
|
2154
|
+
const manifestPath = join5(dir, "manifest.json");
|
|
2155
|
+
if (!existsSync5(manifestPath)) fail6("No hay manifest.json: ejecuta surnie-plugin publish en la carpeta del plugin.");
|
|
2156
|
+
const parsed = manifestSchema.safeParse(JSON.parse(readFileSync5(manifestPath, "utf8")));
|
|
2157
|
+
if (!parsed.success) fail6("manifest.json no es v\xE1lido: ejecuta surnie-plugin pack para ver por qu\xE9.");
|
|
2158
|
+
const manifest = parsed.data;
|
|
2159
|
+
const packagePath = join5(DIST, packageFileName(manifest));
|
|
2160
|
+
if (!existsSync5(join5(dir, packagePath))) fail6(`No est\xE1 ${packagePath}: ejecuta surnie-plugin pack y surnie-plugin sign.`);
|
|
2161
|
+
const pkg = readFileSync5(join5(dir, packagePath));
|
|
2162
|
+
const verified = verifyPluginRelease(readPluginPackage(pkg), { rootKeys: { keys: [] }, allowUnreviewed: true });
|
|
2163
|
+
if (verified.record.namespace !== manifest.namespace || verified.record.version !== manifest.version) {
|
|
2164
|
+
fail6(`${packagePath} es de ${verified.record.namespace} ${verified.record.version}: vuelve a firmar.`);
|
|
2165
|
+
}
|
|
2166
|
+
const sourcePath = join5(dir, DIST, sourceFileName(manifest));
|
|
2167
|
+
if (!existsSync5(sourcePath)) fail6(`Falta la fuente, ${DIST}/${sourceFileName(manifest)}: vuelve a ejecutar pack y sign.`);
|
|
2168
|
+
const source = readFileSync5(sourcePath);
|
|
2169
|
+
const digest = sourceDigest(source);
|
|
2170
|
+
if (digest.sha256 !== verified.record.source.sha256 || digest.size !== verified.record.source.size) {
|
|
2171
|
+
fail6("La fuente de dist/ no es la que firmaste: vuelve a ejecutar pack y sign.");
|
|
2172
|
+
}
|
|
2173
|
+
return { manifest, pkg, source, packagePath, kit: verified.record.build.kit };
|
|
2174
|
+
}
|
|
2175
|
+
async function call(opts, method, path, init = {}) {
|
|
2176
|
+
const base = opts.platformUrl ?? platformUrl();
|
|
2177
|
+
let response;
|
|
2178
|
+
try {
|
|
2179
|
+
response = await (opts.fetch ?? fetch)(`${base}${path}`, {
|
|
2180
|
+
method,
|
|
2181
|
+
body: init.body,
|
|
2182
|
+
headers: { Authorization: `Bearer ${opts.token}`, "User-Agent": `surnie-plugin/${KIT_VERSION}`, ...init.headers }
|
|
2183
|
+
});
|
|
2184
|
+
} catch {
|
|
2185
|
+
return fail6(`No se ha podido conectar con ${base}.`);
|
|
2186
|
+
}
|
|
2187
|
+
if (response.ok) return response;
|
|
2188
|
+
let code = "";
|
|
2189
|
+
let message = "";
|
|
2190
|
+
try {
|
|
2191
|
+
const body = await response.json();
|
|
2192
|
+
code = body.error?.code ?? "";
|
|
2193
|
+
message = body.error?.message ?? "";
|
|
2194
|
+
} catch {
|
|
2195
|
+
}
|
|
2196
|
+
return fail6(explain(response.status, code, message));
|
|
2197
|
+
}
|
|
2198
|
+
function explain(status2, code, message) {
|
|
2199
|
+
switch (code) {
|
|
2200
|
+
case "invalid_token":
|
|
2201
|
+
return `El token de publicador no vale (${PUBLISH_TOKEN_ENV}): pide uno nuevo.`;
|
|
2202
|
+
case "publisher_suspended":
|
|
2203
|
+
return "Tu cuenta de publicador est\xE1 suspendida.";
|
|
2204
|
+
case "namespace_taken":
|
|
2205
|
+
return "Ese namespace es de otro publicador: cambia el de manifest.json.";
|
|
2206
|
+
case "version_exists":
|
|
2207
|
+
return "Esa versi\xF3n ya se envi\xF3: mira en qu\xE9 punto est\xE1 con surnie-plugin status, o sube la versi\xF3n.";
|
|
2208
|
+
case "version_not_newer":
|
|
2209
|
+
return "La versi\xF3n tiene que ser mayor que la \xFAltima aprobada: s\xFAbela en manifest.json.";
|
|
2210
|
+
case "payload_too_large":
|
|
2211
|
+
return "El paquete o la fuente pasan de 5 MB.";
|
|
2212
|
+
case "rate_limited":
|
|
2213
|
+
return "Demasiadas peticiones seguidas: espera un poco y vuelve a intentarlo.";
|
|
2214
|
+
case "not_found":
|
|
2215
|
+
return "Esa versi\xF3n no se ha enviado (o el plugin es de otro publicador).";
|
|
2216
|
+
default:
|
|
2217
|
+
return `La plataforma responde ${status2}${code ? ` (${code})` : ""}${message ? `: ${message}` : "."}`;
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
async function versionState(opts, m) {
|
|
2221
|
+
const response = await call(opts, "GET", `/v1/plugins/${m.namespace}/versions/${m.version}`);
|
|
2222
|
+
return await response.json();
|
|
2223
|
+
}
|
|
2224
|
+
function writeApproval(dir, build, state) {
|
|
2225
|
+
const raw = Buffer.from(JSON.stringify(state.approval, null, 2) + "\n");
|
|
2226
|
+
const approval = parseApprovalFile(raw);
|
|
2227
|
+
const body = JSON.parse(Buffer.from(approval.approval.payload, "base64").toString("utf8"));
|
|
2228
|
+
if (body.namespace !== build.manifest.namespace || body.version !== build.manifest.version) {
|
|
2229
|
+
fail6("La plataforma ha devuelto la aprobaci\xF3n de otra versi\xF3n.");
|
|
2230
|
+
}
|
|
2231
|
+
const file = join5(DIST, approvalFileName(build.manifest));
|
|
2232
|
+
writeFileSync4(join5(resolve3(dir), file), raw);
|
|
2233
|
+
return file;
|
|
2234
|
+
}
|
|
2235
|
+
var DONE = /* @__PURE__ */ new Set(["review", "approved", "rejected"]);
|
|
2236
|
+
async function follow(dir, build, opts, first) {
|
|
2237
|
+
const now = opts.now ?? Date.now;
|
|
2238
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
2239
|
+
const deadline = now() + (opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
2240
|
+
let state = first;
|
|
2241
|
+
let said = "";
|
|
2242
|
+
let wait = 2e3;
|
|
2243
|
+
while (!DONE.has(state.status) && now() < deadline) {
|
|
2244
|
+
if (state.status !== said) opts.log?.(STEP[state.status] ?? state.status);
|
|
2245
|
+
said = state.status;
|
|
2246
|
+
await sleep(wait);
|
|
2247
|
+
wait = Math.min(wait * 2, 15e3);
|
|
2248
|
+
state = await versionState(opts, build.manifest);
|
|
2249
|
+
}
|
|
2250
|
+
return settle(dir, build, state);
|
|
2251
|
+
}
|
|
2252
|
+
var STEP = {
|
|
2253
|
+
received: "Recibido; esperando a que lo recompile la plataforma\u2026",
|
|
2254
|
+
building: "Recompilando la fuente y comprobando que sale lo mismo que firmaste\u2026",
|
|
2255
|
+
checking: "Revisi\xF3n autom\xE1tica\u2026",
|
|
2256
|
+
signing: "Aprobado; esperando la firma de la plataforma\u2026"
|
|
2257
|
+
};
|
|
2258
|
+
function settle(dir, build, state) {
|
|
2259
|
+
if (state.status === "approved") {
|
|
2260
|
+
if (!state.approval) fail6("La plataforma dice que est\xE1 publicada pero no da su aprobaci\xF3n.");
|
|
2261
|
+
return { outcome: "approved", state, approvalFile: writeApproval(dir, build, state) };
|
|
2262
|
+
}
|
|
2263
|
+
if (state.status === "rejected") return { outcome: "rejected", state };
|
|
2264
|
+
if (state.status === "review") return { outcome: "review", state };
|
|
2265
|
+
return { outcome: "pending", state };
|
|
2266
|
+
}
|
|
2267
|
+
async function publish(dir, opts) {
|
|
2268
|
+
const build = signedBuild(dir);
|
|
2269
|
+
const { namespace, version } = build.manifest;
|
|
2270
|
+
const form = new FormData();
|
|
2271
|
+
form.set("package", new Blob([new Uint8Array(build.pkg)], { type: "application/gzip" }), packageFileName(build.manifest));
|
|
2272
|
+
form.set("source", new Blob([new Uint8Array(build.source)], { type: "application/gzip" }), sourceFileName(build.manifest));
|
|
2273
|
+
opts.log?.(`Enviando ${namespace} ${version} (${build.pkg.length} B y la fuente, ${build.source.length} B)\u2026`);
|
|
2274
|
+
const response = await call(opts, "PUT", `/v1/plugins/${namespace}/versions/${version}`, {
|
|
2275
|
+
body: form,
|
|
2276
|
+
headers: { "Surnie-Kit-Version": build.kit }
|
|
2277
|
+
});
|
|
2278
|
+
return follow(dir, build, opts, await response.json());
|
|
2279
|
+
}
|
|
2280
|
+
async function status(dir, opts) {
|
|
2281
|
+
const build = signedBuild(dir);
|
|
2282
|
+
return settle(dir, build, await versionState(opts, build.manifest));
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
// src/sign.ts
|
|
2286
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
2287
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "node:fs";
|
|
2288
|
+
import { homedir } from "node:os";
|
|
2289
|
+
import { dirname as dirname4, join as join6, resolve as resolve4 } from "node:path";
|
|
2290
|
+
var PluginSignError = class extends Error {
|
|
2291
|
+
};
|
|
2292
|
+
var fail7 = (message) => {
|
|
2293
|
+
throw new PluginSignError(message);
|
|
2294
|
+
};
|
|
2295
|
+
var AUTHOR_KEY_ENV = "SURNIE_PLUGIN_KEY";
|
|
2296
|
+
var AUTHOR_KEY_PASSWORD_ENV = "SURNIE_PLUGIN_KEY_PASSWORD";
|
|
2297
|
+
function authorKeyPath(env = process.env) {
|
|
2298
|
+
return resolve4(env[AUTHOR_KEY_ENV] || join6(homedir(), ".surnie", "plugin-author-key.age"));
|
|
2299
|
+
}
|
|
2300
|
+
async function createAuthorKey(path, password, options2) {
|
|
2301
|
+
if (existsSync6(path)) fail7(`Ya hay una clave en ${path}. No se sobrescribe.`);
|
|
2302
|
+
const { file, privateKeyPem } = await generateEncryptedSigningKey(password, options2);
|
|
2303
|
+
mkdirSync4(dirname4(path), { recursive: true, mode: 448 });
|
|
2304
|
+
writeFileSync5(path, file, { mode: 384, flag: "wx" });
|
|
2305
|
+
return publicKeyOf(privateKeyPem);
|
|
2306
|
+
}
|
|
2307
|
+
async function openAuthorKey(path, password) {
|
|
2308
|
+
if (!existsSync6(path)) fail7(`No est\xE1 la clave del autor en ${path} (cr\xE9ala con surnie-plugin keygen, o ${AUTHOR_KEY_ENV}).`);
|
|
2309
|
+
const text2 = readFileSync6(path, "utf8");
|
|
2310
|
+
if (!isEncryptedKeyFile(text2)) fail7(`La clave de ${path} no est\xE1 cifrada: un autor la guarda siempre cifrada (surnie-plugin keygen).`);
|
|
2311
|
+
return decryptSigningKey(text2, password);
|
|
2312
|
+
}
|
|
2313
|
+
function readBuild(dir) {
|
|
2314
|
+
const at = (p) => join6(dir, p);
|
|
2315
|
+
if (!existsSync6(at(`${DIST_BUILD}/record.json`))) fail7(`No hay nada compilado en ${DIST_BUILD}/: ejecuta antes surnie-plugin pack.`);
|
|
2316
|
+
const record = JSON.parse(readFileSync6(at(`${DIST_BUILD}/record.json`), "utf8"));
|
|
2317
|
+
const files = {};
|
|
2318
|
+
for (const name of SIGNED_FILES) {
|
|
2319
|
+
if (existsSync6(at(`${DIST_BUILD}/${name}`))) files[name] = readFileSync6(at(`${DIST_BUILD}/${name}`));
|
|
2320
|
+
}
|
|
2321
|
+
const digests = fileDigests(files);
|
|
2322
|
+
for (const name of SIGNED_FILES) {
|
|
2323
|
+
const a = record.files[name];
|
|
2324
|
+
const b = digests[name];
|
|
2325
|
+
if (!a !== !b || a && b && (a.sha256 !== b.sha256 || a.size !== b.size)) {
|
|
2326
|
+
fail7(`${DIST_BUILD}/${name} no es lo que compil\xF3 pack: vuelve a ejecutar surnie-plugin pack.`);
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
const pkg = readPluginPackage(packPlugin({ manifest: files["manifest.json"], server: files["server.js"], ui: files["ui.js"], locales: files["locales.json"] }));
|
|
2330
|
+
const sourcePath = at(`${DIST}/${sourceFileName(pkg.manifest)}`);
|
|
2331
|
+
if (!existsSync6(sourcePath)) fail7(`Falta la fuente, ${DIST}/${sourceFileName(pkg.manifest)}: vuelve a ejecutar surnie-plugin pack.`);
|
|
2332
|
+
const source = readFileSync6(sourcePath);
|
|
2333
|
+
const sd = sourceDigest(source);
|
|
2334
|
+
if (sd.sha256 !== record.source.sha256 || sd.size !== record.source.size) fail7("La fuente no es la que reuni\xF3 pack: vuelve a ejecutar surnie-plugin pack.");
|
|
2335
|
+
return { files, record, manifest: pkg.manifest, source };
|
|
2336
|
+
}
|
|
2337
|
+
function signBuild(dir, privateKeyPem) {
|
|
2338
|
+
dir = resolve4(dir);
|
|
2339
|
+
const { files, record, manifest } = readBuild(dir);
|
|
2340
|
+
const author = signAsAuthor(record, privateKeyPem);
|
|
2341
|
+
const tgz = packPlugin({ manifest: files["manifest.json"], server: files["server.js"], ui: files["ui.js"], locales: files["locales.json"], release: releaseFile({ author }) });
|
|
2342
|
+
const verified = verifyPluginRelease(readPluginPackage(tgz), { rootKeys: { keys: [] }, allowUnreviewed: true });
|
|
2343
|
+
const file = `${DIST}/${packageFileName(manifest)}`;
|
|
2344
|
+
writeFileSync5(join6(dir, file), tgz);
|
|
2345
|
+
return { file, manifest, record, authorKey: verified.authorKey };
|
|
2346
|
+
}
|
|
2347
|
+
function inspectPackage(gz, approvalRaw) {
|
|
2348
|
+
const pkg = readPluginPackage(gz);
|
|
2349
|
+
const files = [...SIGNED_FILES, "release.json"].filter((name) => pkg.files[name]).map((name) => ({ name, size: pkg.files[name].length, sha256: createHash5("sha256").update(pkg.files[name]).digest("hex") }));
|
|
2350
|
+
if (!pkg.files["release.json"]) return { manifest: pkg.manifest, files, author: null, record: null, platform: null };
|
|
2351
|
+
const verified = verifyPluginRelease(pkg, { rootKeys: { keys: [] }, allowUnreviewed: true });
|
|
2352
|
+
let platform = null;
|
|
2353
|
+
if (approvalRaw) {
|
|
2354
|
+
const part = parseApprovalFile(approvalRaw);
|
|
2355
|
+
let approval = null;
|
|
2356
|
+
try {
|
|
2357
|
+
const body = JSON.parse(Buffer.from(part.approval.payload, "base64").toString("utf8"));
|
|
2358
|
+
approval = { level: body.level, reviewedAt: body.reviewedAt };
|
|
2359
|
+
} catch {
|
|
2360
|
+
approval = null;
|
|
2361
|
+
}
|
|
2362
|
+
platform = { keyId: part.approval.signatures[0]?.keyid ?? "?", rootKeyId: part.certificate.signatures[0]?.keyid ?? "?", approval };
|
|
2363
|
+
}
|
|
2364
|
+
return { manifest: pkg.manifest, files, author: verified.authorKey, record: verified.record, platform };
|
|
2365
|
+
}
|
|
2366
|
+
|
|
2367
|
+
// src/cli.ts
|
|
2368
|
+
var USAGE = `Uso: surnie-plugin keygen | dev | types | pack | sign | inspect <paquete.tgz> | publish | status
|
|
2369
|
+
|
|
2370
|
+
dev [--port <n>] [--image <imagen>] [--reset] [--no-docker]
|
|
2371
|
+
--port puerto del panel en esta m\xE1quina (${DEV_PORT})
|
|
2372
|
+
--image imagen de Surnie (${DEV_IMAGE})
|
|
2373
|
+
--reset empieza con una instalaci\xF3n nueva (borra el volumen de desarrollo)
|
|
2374
|
+
--no-docker solo compila al guardar, para un Surnie propio (SURNIE_DEV_PLUGINS)`;
|
|
2375
|
+
function devOptions(args) {
|
|
2376
|
+
const opts = {};
|
|
2377
|
+
for (let i = 0; i < args.length; i++) {
|
|
2378
|
+
const a = args[i];
|
|
2379
|
+
if (a === "--reset") opts.reset = true;
|
|
2380
|
+
else if (a === "--no-docker") opts.docker = false;
|
|
2381
|
+
else if (a === "--port" || a === "--image") {
|
|
2382
|
+
const v = args[++i];
|
|
2383
|
+
if (!v) throw new PluginBuildError(`Falta el valor de ${a}.`);
|
|
2384
|
+
if (a === "--port") {
|
|
2385
|
+
const port = Number(v);
|
|
2386
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new PluginBuildError(`--port: un n\xFAmero de 1 a 65535.`);
|
|
2387
|
+
opts.port = port;
|
|
2388
|
+
} else opts.image = v;
|
|
2389
|
+
} else throw new PluginBuildError(`Opci\xF3n desconocida: ${a}
|
|
2390
|
+
|
|
2391
|
+
${USAGE}`);
|
|
2392
|
+
}
|
|
2393
|
+
return opts;
|
|
2394
|
+
}
|
|
2395
|
+
async function publishToken() {
|
|
2396
|
+
const fromEnv = process.env[PUBLISH_TOKEN_ENV];
|
|
2397
|
+
if (fromEnv) return fromEnv;
|
|
2398
|
+
if (!process.stdin.isTTY) throw new PluginPublishError(`Falta el token de publicador: def\xEDnelo en ${PUBLISH_TOKEN_ENV}.`);
|
|
2399
|
+
const token = (await promptHidden("Token de publicador (srnp_\u2026): ")).trim();
|
|
2400
|
+
if (!token) throw new PluginPublishError("Sin token no se puede publicar.");
|
|
2401
|
+
return token;
|
|
2402
|
+
}
|
|
2403
|
+
function report(r) {
|
|
2404
|
+
const { namespace, version, reason } = r.state;
|
|
2405
|
+
if (r.outcome === "approved") {
|
|
2406
|
+
console.log(`
|
|
2407
|
+
\u2714 ${namespace} ${version} publicado. Su aprobaci\xF3n: ${r.approvalFile}`);
|
|
2408
|
+
console.log(" Para instalarlo a mano, sube el paquete y ese fichero en Ajustes \u2192 Plugins.\n");
|
|
2409
|
+
return 0;
|
|
2410
|
+
}
|
|
2411
|
+
if (r.outcome === "review") {
|
|
2412
|
+
console.log(`
|
|
2413
|
+
\u2026 ${namespace} ${version} espera a una persona: ${reason ?? ""}`);
|
|
2414
|
+
console.log(" Cuando se apruebe, surnie-plugin status trae su aprobaci\xF3n.\n");
|
|
2415
|
+
return 0;
|
|
2416
|
+
}
|
|
2417
|
+
if (r.outcome === "pending") {
|
|
2418
|
+
console.log(`
|
|
2419
|
+
\u2026 ${namespace} ${version} sigue en marcha (${r.state.status}). M\xEDralo luego con surnie-plugin status.
|
|
2420
|
+
`);
|
|
2421
|
+
return 0;
|
|
2422
|
+
}
|
|
2423
|
+
console.error(`
|
|
2424
|
+
\u2718 ${namespace} ${version} rechazado: ${reason ?? "sin motivo"}
|
|
2425
|
+
`);
|
|
2426
|
+
return 1;
|
|
2427
|
+
}
|
|
2428
|
+
async function main(argv) {
|
|
2429
|
+
const [cmd, arg] = argv;
|
|
2430
|
+
if (cmd === "dev") {
|
|
2431
|
+
await runDev(process.cwd(), devOptions(argv.slice(1)));
|
|
2432
|
+
return 0;
|
|
2433
|
+
}
|
|
2434
|
+
if (cmd === "types") {
|
|
2435
|
+
console.log(`\u2714 ${writePluginTypes(process.cwd())}`);
|
|
2436
|
+
return 0;
|
|
2437
|
+
}
|
|
2438
|
+
if (cmd === "keygen") {
|
|
2439
|
+
const path = authorKeyPath();
|
|
2440
|
+
const password = await readPassword({ envVar: AUTHOR_KEY_PASSWORD_ENV, prompt: "Contrase\xF1a para tu clave de autor: ", confirm: true });
|
|
2441
|
+
const key = await createAuthorKey(path, password);
|
|
2442
|
+
console.log(`
|
|
2443
|
+
\u2714 Clave de autor ${key.keyId}, cifrada en ${path}.`);
|
|
2444
|
+
console.log(" Guarda una copia del fichero y la contrase\xF1a fuera de esta m\xE1quina: sin las dos no podr\xE1s");
|
|
2445
|
+
console.log(" publicar versiones nuevas de tus plugins (perderla obliga a un traspaso que confirma cada admin).");
|
|
2446
|
+
console.log(` Clave p\xFAblica (la que registras en la plataforma): ${key.publicKey}
|
|
2447
|
+
`);
|
|
2448
|
+
return 0;
|
|
2449
|
+
}
|
|
2450
|
+
if (cmd === "pack") {
|
|
2451
|
+
const r = await pack(process.cwd(), { log: (m) => console.log(m) });
|
|
2452
|
+
if (r.warning) console.warn(`
|
|
2453
|
+
\u26A0 ${r.warning}`);
|
|
2454
|
+
console.log(`
|
|
2455
|
+
\u2714 ${r.manifest.namespace} ${r.manifest.version}: dos compilaciones id\xE9nticas.`);
|
|
2456
|
+
for (const path of r.written) console.log(` ${path}`);
|
|
2457
|
+
console.log("\n Siguiente paso: surnie-plugin sign\n");
|
|
2458
|
+
return 0;
|
|
2459
|
+
}
|
|
2460
|
+
if (cmd === "sign") {
|
|
2461
|
+
const path = authorKeyPath();
|
|
2462
|
+
const password = await readPassword({ envVar: AUTHOR_KEY_PASSWORD_ENV, prompt: `Contrase\xF1a de tu clave de autor (${path}): ` });
|
|
2463
|
+
const r = signBuild(process.cwd(), await openAuthorKey(path, password));
|
|
2464
|
+
console.log(`
|
|
2465
|
+
\u2714 ${r.file}: ${r.manifest.namespace} ${r.manifest.version}, firmado con ${r.authorKey.keyId}.
|
|
2466
|
+
`);
|
|
2467
|
+
return 0;
|
|
2468
|
+
}
|
|
2469
|
+
if (cmd === "publish" || cmd === "status") {
|
|
2470
|
+
const url = platformUrl();
|
|
2471
|
+
const token = await publishToken();
|
|
2472
|
+
const opts = { token, platformUrl: url };
|
|
2473
|
+
if (cmd === "status") return report(await status(process.cwd(), opts));
|
|
2474
|
+
return report(await publish(process.cwd(), { ...opts, log: (line) => console.log(line) }));
|
|
2475
|
+
}
|
|
2476
|
+
if (cmd === "inspect" && arg) {
|
|
2477
|
+
const approvalPath = arg.replace(/\.tgz$/, ".approval.json");
|
|
2478
|
+
const i = inspectPackage(readFileSync7(arg), approvalPath !== arg && existsSync7(approvalPath) ? readFileSync7(approvalPath) : null);
|
|
2479
|
+
const m = i.manifest;
|
|
2480
|
+
console.log(`
|
|
2481
|
+
${m.name} (${m.namespace}) ${m.version} \u2014 contrato ${m.contract}
|
|
2482
|
+
${m.description}
|
|
2483
|
+
`);
|
|
2484
|
+
console.log("Ficheros:");
|
|
2485
|
+
for (const f of i.files) console.log(` ${f.name.padEnd(14)} ${String(f.size).padStart(9)} B sha256 ${f.sha256}`);
|
|
2486
|
+
const perms = [...m.permissions.required.map((p) => ({ ...p, req: true })), ...m.permissions.optional.map((p) => ({ ...p, req: false }))];
|
|
2487
|
+
console.log(`
|
|
2488
|
+
Permisos${perms.length ? "" : ": ninguno"}`);
|
|
2489
|
+
for (const p of perms) console.log(` ${p.req ? "imprescindible" : "opcional "} ${p.kind} (${p.id}): ${p.purpose}`);
|
|
2490
|
+
const own = [...m.model.collections, ...m.model.singleTypes, ...m.model.components].map((x) => x.apiId);
|
|
2491
|
+
if (own.length) console.log(`
|
|
2492
|
+
Modelo propio: ${own.join(", ")}`);
|
|
2493
|
+
if (!i.author) {
|
|
2494
|
+
console.log("\nSin firmar (no lleva release.json).\n");
|
|
2495
|
+
return 0;
|
|
2496
|
+
}
|
|
2497
|
+
const b = i.record.build;
|
|
2498
|
+
console.log(`
|
|
2499
|
+
Firmado por el autor con ${i.author.keyId}: la firma es v\xE1lida y cubre exactamente estos ficheros.`);
|
|
2500
|
+
console.log(`Compilado con el kit ${b.kit}, esbuild ${b.esbuild}, Node ${b.node} y ${b.packageManager}.`);
|
|
2501
|
+
console.log(`Fuente: sha256 ${i.record.source.sha256} (${i.record.source.size} B).`);
|
|
2502
|
+
console.log(
|
|
2503
|
+
i.platform ? `Aprobado por la plataforma (clave ${i.platform.keyId}${i.platform.approval ? `, nivel ${i.platform.approval.level}, revisado ${i.platform.approval.reviewedAt}` : ""}); el motor lo comprueba al instalar.
|
|
2504
|
+
` : "Sin la aprobaci\xF3n de la plataforma: solo se instala en un motor en modo desarrollo.\n"
|
|
2505
|
+
);
|
|
2506
|
+
return 0;
|
|
2507
|
+
}
|
|
2508
|
+
console.error(USAGE);
|
|
2509
|
+
return 1;
|
|
2510
|
+
}
|
|
2511
|
+
main(process.argv.slice(2)).then(
|
|
2512
|
+
(code) => process.exit(code),
|
|
2513
|
+
(e) => {
|
|
2514
|
+
const known = [PluginBuildError, PluginPackageError, PluginSourceError, PluginReleaseError, PluginSignError, PluginPublishError, SigningKeyError];
|
|
2515
|
+
if (known.some((k) => e instanceof k)) {
|
|
2516
|
+
console.error(`\u2718 ${e.message}`);
|
|
2517
|
+
process.exit(1);
|
|
2518
|
+
}
|
|
2519
|
+
throw e;
|
|
2520
|
+
}
|
|
2521
|
+
);
|