@owear/core 0.1.3 → 0.1.4

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/dist/app.d.ts CHANGED
@@ -8,6 +8,12 @@ export declare const app: {
8
8
  /** Conecta con el kernel. Resuelve cuando el canal de control está listo. */
9
9
  whenReady(): Promise<void>;
10
10
  quit(exitCode?: number): Promise<void>;
11
+ /**
12
+ * Define el icono por defecto de la app (ruta a PNG/JPEG). Se aplica a las
13
+ * ventanas creadas a partir de entonces y a `new BrowserWindow()` sin `icon`.
14
+ * (Equivale a `BrowserWindow({ icon })` global.)
15
+ */
16
+ setIcon(path: string): void;
11
17
  info(): Promise<{
12
18
  pid: number;
13
19
  version: string;
package/dist/app.js CHANGED
@@ -9,6 +9,7 @@ import * as fs from 'node:fs';
9
9
  import { channel, socketPathFromEnv } from './channel.js';
10
10
  import { forkWorker } from './node/worker.js';
11
11
  import { nodeHandlers, nodeContextHandlers } from './ipc/node.js';
12
+ import { setWindowIcon } from './appicon.js';
12
13
  import { portRecords, makeMainPort, allocPortId } from './port.js';
13
14
  import { protocolHandlers } from './protocol.js';
14
15
  /** Resuelto por app.whenReady(). Compartido con BrowserWindow. */
@@ -106,6 +107,14 @@ export const app = {
106
107
  quit(exitCode = 0) {
107
108
  return channel.call('app.quit', { exitCode }).catch(() => undefined);
108
109
  },
110
+ /**
111
+ * Define el icono por defecto de la app (ruta a PNG/JPEG). Se aplica a las
112
+ * ventanas creadas a partir de entonces y a `new BrowserWindow()` sin `icon`.
113
+ * (Equivale a `BrowserWindow({ icon })` global.)
114
+ */
115
+ setIcon(path) {
116
+ setWindowIcon(path);
117
+ },
109
118
  info() {
110
119
  return channel.call('app.info');
111
120
  },
@@ -0,0 +1,4 @@
1
+ /** Fija el icono por defecto (ruta a PNG/JPEG). */
2
+ export declare function setWindowIcon(path?: string): void;
3
+ /** Icono por defecto actual (o undefined). */
4
+ export declare function windowIcon(): string | undefined;
@@ -0,0 +1,16 @@
1
+ // Copyright 2026 Owear Contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ //
4
+ // @owear/core/src/appicon.ts — icono por defecto de la app (compartido).
5
+ //
6
+ // Módulo sin dependencias para evitar ciclos: `app.setIcon(path)` lo fija y
7
+ // `BrowserWindow` lo aplica a cada ventana creada a partir de entonces.
8
+ let iconPath;
9
+ /** Fija el icono por defecto (ruta a PNG/JPEG). */
10
+ export function setWindowIcon(path) {
11
+ iconPath = path;
12
+ }
13
+ /** Icono por defecto actual (o undefined). */
14
+ export function windowIcon() {
15
+ return iconPath;
16
+ }
@@ -11,6 +11,8 @@ export declare class BrowserWindow extends EventEmitter {
11
11
  private _onDisconnected;
12
12
  constructor(options?: WindowOptions);
13
13
  private _create;
14
+ /** Fija el icono de ESTA ventana (ruta a PNG/JPEG). */
15
+ setIcon(path: string): Promise<void>;
14
16
  private _wireEvents;
15
17
  private _unwireEvents;
16
18
  get id(): number | null;
@@ -3,7 +3,8 @@
3
3
  //
4
4
  // @owear/core/src/browserwindow.ts — BrowserWindow (C9).
5
5
  import { EventEmitter } from 'node:events';
6
- import { channel } from './channel.js';
6
+ import { channel, invokeNative } from './channel.js';
7
+ import { windowIcon } from './appicon.js';
7
8
  import { readyPromise } from './app.js';
8
9
  import { WebContents, WIN_EVENT_NAMES, WC_EVENT_NAMES } from './webcontents.js';
9
10
  // ── BrowserWindow ───────────────────────────────────────────────────────────
@@ -45,14 +46,24 @@ export class BrowserWindow extends EventEmitter {
45
46
  readyPromise.then(() => this._create()).catch((e) => this.emit('error', e));
46
47
  }
47
48
  async _create() {
48
- const params = { ...this._options };
49
- const res = await channel.call('window.create', params);
49
+ const { icon, ...rest } = this._options;
50
+ const res = await channel.call('window.create', { ...rest });
50
51
  this._id = res.windowId;
51
52
  this._wc._setWindowId(res.windowId);
52
53
  windowsById.set(res.windowId, this);
53
54
  this._wireEvents();
55
+ // Icono: el de la opción o el global (app.setIcon). PNG/JPEG.
56
+ const ic = icon ?? windowIcon();
57
+ if (ic)
58
+ await this.setIcon(ic).catch(() => undefined);
54
59
  this.emit('ready-to-show', this._id);
55
60
  }
61
+ /** Fija el icono de ESTA ventana (ruta a PNG/JPEG). */
62
+ async setIcon(path) {
63
+ const { readFileSync } = await import('node:fs');
64
+ const pngB64 = readFileSync(path).toString('base64');
65
+ await invokeNative('window', 'setIcon', this.requireId(), pngB64);
66
+ }
56
67
  _wireEvents() {
57
68
  channel.on('window.event', this._onWindowEvent);
58
69
  channel.on('disconnected', this._onDisconnected);
package/dist/index.d.ts CHANGED
@@ -42,6 +42,11 @@ export interface WindowOptions {
42
42
  * Crea la partición con `session.fromPartition(name)`.
43
43
  */
44
44
  session?: string;
45
+ /**
46
+ * Icono de la ventana (ruta a un PNG/JPEG). Para un icono por defecto de toda
47
+ * la app usa `app.setIcon(path)`.
48
+ */
49
+ icon?: string;
45
50
  }
46
51
  export interface Bounds {
47
52
  x: number;
@@ -105,6 +110,8 @@ export { app } from './app.js';
105
110
  export { readyPromise } from './app.js';
106
111
  export { installer } from './installer.js';
107
112
  export type { InstallerMode, PayloadEntry, InstallerInfo, PlanOptions, InstallOptions, InstallResult, UninstallResult, VerifyResult, StateResult, ShortcutOptions, LaunchOptions, } from './installer.js';
113
+ export { autoUpdater } from './updater.js';
114
+ export type { FeedOptions, UpdateInfo, UpdateFile, ProgressInfo, UpdateCheckResult, } from './updater.js';
108
115
  export { defineBridge } from './bridge.js';
109
116
  export type { OwearBridge, BridgeApp, BridgeTarget, BridgePlatform, BridgeFormat, BridgeLayout, BridgePreset, BridgeGroup, BridgeProtect, BridgeNode, BridgeHooks, } from './bridge.js';
110
117
  export { forkWorker, resolveWorkerEntry } from './node/worker.js';
package/dist/index.js CHANGED
@@ -35,6 +35,8 @@ export { app } from './app.js';
35
35
  export { readyPromise } from './app.js';
36
36
  // ── instalador (D1): bridge + API del modo instalador/desinstalador ──────────
37
37
  export { installer } from './installer.js';
38
+ // ── auto-update ─────────────────────────────────────────────────────────────
39
+ export { autoUpdater } from './updater.js';
38
40
  export { defineBridge } from './bridge.js';
39
41
  // ── workers Node (utilityProcess.fork) ──────────────────────────────────────
40
42
  export { forkWorker, resolveWorkerEntry } from './node/worker.js';
@@ -53,10 +53,15 @@ export interface StateResult {
53
53
  version?: string;
54
54
  mode?: string;
55
55
  app?: string;
56
+ /** Directorio de instalación (si se conoce / está registrado). */
57
+ dir?: string;
56
58
  }
57
59
  export interface ShortcutOptions {
58
60
  execPath: string;
59
61
  iconPath?: string;
62
+ /** Anulan los del manifiesto (por defecto: appId/appName del installer.json). */
63
+ appId?: string;
64
+ appName?: string;
60
65
  desktop?: boolean;
61
66
  menu?: boolean;
62
67
  startup?: boolean;
@@ -76,6 +81,13 @@ export declare const installer: {
76
81
  info(): Promise<InstallerInfo>;
77
82
  /** Bridge embebido (contrato app ↔ installer). */
78
83
  bridge<T = unknown>(): Promise<T | null>;
84
+ /** Directorio de instalación por defecto (absoluto, por usuario). */
85
+ defaultDir(): Promise<string>;
86
+ /** Selector NATIVO de carpeta (no depende de módulos .owm). null si cancela. */
87
+ chooseDir(opts?: {
88
+ title?: string;
89
+ defaultPath?: string;
90
+ }): Promise<string | null>;
79
91
  /** Lista los ficheros del payload embebido. */
80
92
  payloadList(): Promise<PayloadEntry[]>;
81
93
  /** Lee un fichero del payload (base64). */
@@ -97,10 +109,12 @@ export declare const installer: {
97
109
  verify(opts: {
98
110
  dir: string;
99
111
  }): Promise<VerifyResult>;
100
- /** Estado de instalación en `dir`. */
101
- state(opts: {
102
- dir: string;
112
+ /** Estado de instalación en `dir` (o el registrado si se omite). */
113
+ state(opts?: {
114
+ dir?: string;
103
115
  }): Promise<StateResult>;
116
+ /** Lista las apps instaladas (registro de Owear). */
117
+ list(): Promise<Array<Record<string, unknown>>>;
104
118
  /** Crea accesos directos / integración de escritorio. */
105
119
  shortcuts(opts: ShortcutOptions): Promise<boolean>;
106
120
  /** Lanza un ejecutable en segundo plano (p. ej. la app instalada). */
package/dist/installer.js CHANGED
@@ -29,6 +29,14 @@ export const installer = {
29
29
  bridge() {
30
30
  return invokeNative('installer', 'bridge');
31
31
  },
32
+ /** Directorio de instalación por defecto (absoluto, por usuario). */
33
+ defaultDir() {
34
+ return invokeNative('installer', 'defaultDir');
35
+ },
36
+ /** Selector NATIVO de carpeta (no depende de módulos .owm). null si cancela. */
37
+ chooseDir(opts = {}) {
38
+ return invokeNative('installer', 'chooseDir', opts);
39
+ },
32
40
  /** Lista los ficheros del payload embebido. */
33
41
  payloadList() {
34
42
  return invokeNative('installer', 'payloadList');
@@ -53,10 +61,14 @@ export const installer = {
53
61
  verify(opts) {
54
62
  return invokeNative('installer', 'verify', opts);
55
63
  },
56
- /** Estado de instalación en `dir`. */
57
- state(opts) {
64
+ /** Estado de instalación en `dir` (o el registrado si se omite). */
65
+ state(opts = {}) {
58
66
  return invokeNative('installer', 'state', opts);
59
67
  },
68
+ /** Lista las apps instaladas (registro de Owear). */
69
+ list() {
70
+ return invokeNative('installer', 'list');
71
+ },
60
72
  /** Crea accesos directos / integración de escritorio. */
61
73
  shortcuts(opts) {
62
74
  return invokeNative('installer', 'shortcuts', opts);
@@ -0,0 +1,20 @@
1
+ export interface BootRecord {
2
+ version: string;
3
+ attempts: number;
4
+ updatedAt: string;
5
+ }
6
+ /** Ruta del registro de arranque dentro de `<userData>`. */
7
+ export declare function bootRecordPath(userDataDir: string): string;
8
+ /** Lee el registro; null si no existe o está corrupto. */
9
+ export declare function readBoot(file: string): BootRecord | null;
10
+ /** Escribe el registro (crea el directorio si hace falta). */
11
+ export declare function writeBoot(file: string, rec: BootRecord): void;
12
+ /**
13
+ * Calcula el estado del siguiente arranque:
14
+ * - misma versión que la anterior → `attempts + 1`; si llega al umbral, rollback.
15
+ * - versión distinta (o primer arranque) → `attempts = 1`, sin rollback.
16
+ */
17
+ export declare function nextBoot(prev: BootRecord | null, version: string, threshold: number, now?: () => Date): {
18
+ record: BootRecord;
19
+ shouldRollback: boolean;
20
+ };
@@ -0,0 +1,49 @@
1
+ // Copyright 2026 Owear Contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ //
4
+ // @owear/core/src/updater/boot.ts — registro de arranque para el **rollback**.
5
+ //
6
+ // Tras aplicar un update el binario nuevo arranca con una copia de seguridad
7
+ // (`<exe>.owprev`). Si el arranque se repite sin que la app marque "sano"
8
+ // (crash loop), el updater revierte al binario anterior.
9
+ //
10
+ // El contador vive en `<userData>/update-boot.json`:
11
+ // { "version": "1.4.0", "attempts": 2, "updatedAt": "…" }
12
+ // Cada arranque incrementa `attempts`; cuando la app confirma salud
13
+ // (`commit`), se pone a 0. Si `attempts` alcanza el umbral → rollback.
14
+ import * as fs from 'node:fs';
15
+ import * as path from 'node:path';
16
+ /** Ruta del registro de arranque dentro de `<userData>`. */
17
+ export function bootRecordPath(userDataDir) {
18
+ return path.join(userDataDir, 'update-boot.json');
19
+ }
20
+ /** Lee el registro; null si no existe o está corrupto. */
21
+ export function readBoot(file) {
22
+ try {
23
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
24
+ if (typeof raw?.version !== 'string' || typeof raw?.attempts !== 'number')
25
+ return null;
26
+ return { version: raw.version, attempts: raw.attempts, updatedAt: String(raw.updatedAt ?? '') };
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ /** Escribe el registro (crea el directorio si hace falta). */
33
+ export function writeBoot(file, rec) {
34
+ fs.mkdirSync(path.dirname(file), { recursive: true });
35
+ fs.writeFileSync(file, JSON.stringify(rec) + '\n');
36
+ }
37
+ /**
38
+ * Calcula el estado del siguiente arranque:
39
+ * - misma versión que la anterior → `attempts + 1`; si llega al umbral, rollback.
40
+ * - versión distinta (o primer arranque) → `attempts = 1`, sin rollback.
41
+ */
42
+ export function nextBoot(prev, version, threshold, now = () => new Date()) {
43
+ const sameVersion = !!prev && prev.version === version;
44
+ const attempts = sameVersion ? prev.attempts + 1 : 1;
45
+ return {
46
+ record: { version, attempts, updatedAt: now().toISOString() },
47
+ shouldRollback: sameVersion && attempts >= threshold,
48
+ };
49
+ }
@@ -0,0 +1,30 @@
1
+ /** sha256 (hex) de cada bloque de `data` (tamaño `blockSize`). */
2
+ export declare function blockHashes(data: Buffer, blockSize: number): string[];
3
+ /** Bloque de bytes [start, end] (end INCLUSIVE), como un HTTP Range. */
4
+ export interface ByteRange {
5
+ start: number;
6
+ end: number;
7
+ }
8
+ export interface DeltaPlan {
9
+ blockSize: number;
10
+ total: number;
11
+ reused: number;
12
+ changed: number;
13
+ ranges: ByteRange[];
14
+ /** Bytes a descargar si se aplica el delta. */
15
+ downloadBytes: number;
16
+ /** Bytes del artefacto completo. */
17
+ totalBytes: number;
18
+ /** Ratio de cambio (0..1). */
19
+ ratio: number;
20
+ }
21
+ /**
22
+ * Plan de delta: compara los hashes locales con los remotos y agrupa los
23
+ * bloques cambiados en rangos contiguos. `remoteSize` acota el último bloque.
24
+ */
25
+ export declare function planDelta(localHashes: string[], remoteHashes: string[], blockSize: number, remoteSize: number): DeltaPlan;
26
+ /**
27
+ * Ensambla el artefacto nuevo reutilizando los bloques locales y pidiendo los
28
+ * cambiados con `fetchRange` (que debe devolver exactamente ese rango).
29
+ */
30
+ export declare function assemble(local: Buffer, remoteHashes: string[], plan: DeltaPlan, remoteSize: number, fetchRange: (r: ByteRange) => Promise<Buffer>): Promise<Buffer>;
@@ -0,0 +1,96 @@
1
+ // Copyright 2026 Owear Contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ //
4
+ // @owear/core/src/updater/delta.ts — delta por bloques (estilo blockmap).
5
+ //
6
+ // El artefacto (p. ej. el binario único) se parte en bloques de tamaño fijo y
7
+ // se publica un blockmap con el sha256 de cada bloque. En el cliente se
8
+ // comparan los bloques locales con los remotos y **solo se descargan los que
9
+ // cambian** (HTTP Range), reutilizando el resto del fichero actual.
10
+ import { createHash } from 'node:crypto';
11
+ /** sha256 (hex) de cada bloque de `data` (tamaño `blockSize`). */
12
+ export function blockHashes(data, blockSize) {
13
+ const out = [];
14
+ if (data.length === 0) {
15
+ out.push(createHash('sha256').update(Buffer.alloc(0)).digest('hex'));
16
+ return out;
17
+ }
18
+ for (let off = 0; off < data.length; off += blockSize) {
19
+ out.push(createHash('sha256')
20
+ .update(data.subarray(off, Math.min(off + blockSize, data.length)))
21
+ .digest('hex'));
22
+ }
23
+ return out;
24
+ }
25
+ /**
26
+ * Plan de delta: compara los hashes locales con los remotos y agrupa los
27
+ * bloques cambiados en rangos contiguos. `remoteSize` acota el último bloque.
28
+ */
29
+ export function planDelta(localHashes, remoteHashes, blockSize, remoteSize) {
30
+ const total = remoteHashes.length;
31
+ const ranges = [];
32
+ let cur = null;
33
+ let changed = 0;
34
+ const blockEnd = (i) => Math.min((i + 1) * blockSize, remoteSize) - 1;
35
+ for (let i = 0; i < total; i++) {
36
+ const same = i < localHashes.length && localHashes[i] === remoteHashes[i];
37
+ if (same) {
38
+ if (cur) {
39
+ ranges.push(cur);
40
+ cur = null;
41
+ }
42
+ continue;
43
+ }
44
+ changed++;
45
+ const start = i * blockSize;
46
+ if (cur && start === cur.end + 1)
47
+ cur.end = blockEnd(i);
48
+ else {
49
+ if (cur)
50
+ ranges.push(cur);
51
+ cur = { start, end: blockEnd(i) };
52
+ }
53
+ }
54
+ if (cur)
55
+ ranges.push(cur);
56
+ const downloadBytes = ranges.reduce((n, r) => n + (r.end - r.start + 1), 0);
57
+ return {
58
+ blockSize,
59
+ total,
60
+ reused: total - changed,
61
+ changed,
62
+ ranges,
63
+ downloadBytes,
64
+ totalBytes: remoteSize,
65
+ ratio: total ? changed / total : 1,
66
+ };
67
+ }
68
+ /**
69
+ * Ensambla el artefacto nuevo reutilizando los bloques locales y pidiendo los
70
+ * cambiados con `fetchRange` (que debe devolver exactamente ese rango).
71
+ */
72
+ export async function assemble(local, remoteHashes, plan, remoteSize, fetchRange) {
73
+ const out = Buffer.alloc(remoteSize);
74
+ // bloque = reutilizado salvo que caiga dentro de un rango de descarga
75
+ let ri = 0;
76
+ for (let i = 0; i < remoteHashes.length; i++) {
77
+ const start = i * plan.blockSize;
78
+ const end = Math.min(start + plan.blockSize, remoteSize);
79
+ while (ri < plan.ranges.length && plan.ranges[ri].end < start)
80
+ ri++;
81
+ const inRange = ri < plan.ranges.length && plan.ranges[ri].start <= start;
82
+ if (!inRange) {
83
+ // reutiliza del local (si existe y coincide); si no, se pedirá abajo
84
+ if (start < local.length)
85
+ local.copy(out, start, start, Math.min(end, local.length));
86
+ }
87
+ }
88
+ // descarga de los rangos cambiados
89
+ for (const r of plan.ranges) {
90
+ const buf = await fetchRange(r);
91
+ if (buf.length !== r.end - r.start + 1)
92
+ throw new Error(`rango ${r.start}-${r.end}: recibidos ${buf.length} bytes`);
93
+ buf.copy(out, r.start);
94
+ }
95
+ return out;
96
+ }
@@ -0,0 +1,6 @@
1
+ export type YamlValue = string | number | boolean | null | YamlMap | YamlValue[];
2
+ export interface YamlMap {
3
+ [k: string]: YamlValue;
4
+ }
5
+ /** Parsea un manifiesto YAML a un objeto JS. */
6
+ export declare function parseYaml(text: string): YamlValue;
@@ -0,0 +1,160 @@
1
+ // Copyright 2026 Owear Contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ //
4
+ // @owear/core/src/updater/yaml.ts — parser YAML mínimo (subconjunto) para los
5
+ // manifiestos de auto-update. Soporta:
6
+ // - mapas (`key: value`), anidados por indentación
7
+ // - listas (`- item`) de escalares o mapas
8
+ // - escalares (texto, comillas simples/dobles, números, true/false/null)
9
+ // - bloque literal (`key: |` y `key: >`) con líneas indentadas
10
+ // No soporta: anchors/aliases, flow style, multi-documento, tags. Suficiente
11
+ // para `latest.yml` / `<channel>.yml` (estilo electron-builder).
12
+ function stripComment(s) {
13
+ // Solo elimina comentarios fuera de comillas.
14
+ let inS = false;
15
+ let inD = false;
16
+ for (let i = 0; i < s.length; i++) {
17
+ const c = s[i];
18
+ if (c === "'" && !inD)
19
+ inS = !inS;
20
+ else if (c === '"' && !inS)
21
+ inD = !inD;
22
+ else if (c === '#' && !inS && !inD && (i === 0 || s[i - 1] === ' '))
23
+ return s.slice(0, i);
24
+ }
25
+ return s;
26
+ }
27
+ function tokenize(text) {
28
+ const out = [];
29
+ for (const raw of text.replace(/\r\n?/g, '\n').split('\n')) {
30
+ const noComment = stripComment(raw);
31
+ if (noComment.trim() === '' || /^---\s*$/.test(noComment.trim()) || /^\.\.\.\s*$/.test(noComment.trim()))
32
+ continue;
33
+ const indent = noComment.match(/^ */)[0].length;
34
+ out.push({ indent, text: noComment.slice(indent) });
35
+ }
36
+ return out;
37
+ }
38
+ function parseScalar(s) {
39
+ const t = s.trim();
40
+ if (t === '' || t === '~' || t === 'null')
41
+ return null;
42
+ if (t === 'true')
43
+ return true;
44
+ if (t === 'false')
45
+ return false;
46
+ if (/^'.*'$/.test(t))
47
+ return t.slice(1, -1).replace(/''/g, "'");
48
+ if (/^".*"$/.test(t)) {
49
+ try {
50
+ return JSON.parse(t);
51
+ }
52
+ catch {
53
+ return t.slice(1, -1);
54
+ }
55
+ }
56
+ if (/^-?\d+$/.test(t))
57
+ return parseInt(t, 10);
58
+ if (/^-?\d*\.\d+$/.test(t))
59
+ return parseFloat(t);
60
+ return t;
61
+ }
62
+ /** Divide "key: value" por el primer ':' seguido de espacio o fin. */
63
+ function splitKey(text) {
64
+ let inS = false;
65
+ let inD = false;
66
+ for (let i = 0; i < text.length; i++) {
67
+ const c = text[i];
68
+ if (c === "'" && !inD)
69
+ inS = !inS;
70
+ else if (c === '"' && !inS)
71
+ inD = !inD;
72
+ else if (c === ':' && !inS && !inD && (i + 1 === text.length || text[i + 1] === ' '))
73
+ return { key: text.slice(0, i).trim(), rest: text.slice(i + 1).trim() };
74
+ }
75
+ return null;
76
+ }
77
+ function parseBlock(lines, start, indent) {
78
+ if (start >= lines.length)
79
+ return { value: null, next: start };
80
+ const first = lines[start];
81
+ // Lista
82
+ if (first.text.startsWith('- ') || first.text === '-') {
83
+ const arr = [];
84
+ let i = start;
85
+ while (i < lines.length && lines[i].indent === indent && (lines[i].text.startsWith('- ') || lines[i].text === '-')) {
86
+ const item = lines[i].text === '-' ? '' : lines[i].text.slice(2);
87
+ if (item === '') {
88
+ const sub = parseBlock(lines, i + 1, lines[i + 1]?.indent ?? indent + 2);
89
+ arr.push(sub.value);
90
+ i = sub.next;
91
+ }
92
+ else {
93
+ const kv = splitKey(item);
94
+ if (kv) {
95
+ // mapa en línea (primer campo) + campos siguientes más indentados
96
+ const obj = {};
97
+ obj[kv.key] = kv.rest === '' ? null : parseScalar(kv.rest);
98
+ const sub = parseBlock(lines, i + 1, lines[i + 1]?.indent ?? indent + 2);
99
+ if (sub.value && typeof sub.value === 'object' && !Array.isArray(sub.value)) {
100
+ Object.assign(obj, sub.value);
101
+ i = sub.next;
102
+ }
103
+ else {
104
+ i++;
105
+ }
106
+ arr.push(obj);
107
+ }
108
+ else {
109
+ arr.push(parseScalar(item));
110
+ i++;
111
+ }
112
+ }
113
+ }
114
+ return { value: arr, next: i };
115
+ }
116
+ // Mapa
117
+ const obj = {};
118
+ let i = start;
119
+ while (i < lines.length && lines[i].indent === indent) {
120
+ const kv = splitKey(lines[i].text);
121
+ if (!kv)
122
+ break;
123
+ if (kv.rest === '|' || kv.rest === '>') {
124
+ const blockIndent = lines[i + 1]?.indent ?? indent + 2;
125
+ const parts = [];
126
+ i++;
127
+ while (i < lines.length && lines[i].indent >= blockIndent) {
128
+ parts.push(lines[i].text);
129
+ i++;
130
+ }
131
+ obj[kv.key] = kv.rest === '>' ? parts.join(' ') : parts.join('\n');
132
+ continue;
133
+ }
134
+ if (kv.rest === '') {
135
+ // valor anidado (mapa/lista) o null
136
+ const nextLine = lines[i + 1];
137
+ if (nextLine && nextLine.indent > indent) {
138
+ const sub = parseBlock(lines, i + 1, nextLine.indent);
139
+ obj[kv.key] = sub.value;
140
+ i = sub.next;
141
+ }
142
+ else {
143
+ obj[kv.key] = null;
144
+ i++;
145
+ }
146
+ }
147
+ else {
148
+ obj[kv.key] = parseScalar(kv.rest);
149
+ i++;
150
+ }
151
+ }
152
+ return { value: obj, next: i };
153
+ }
154
+ /** Parsea un manifiesto YAML a un objeto JS. */
155
+ export function parseYaml(text) {
156
+ const lines = tokenize(text);
157
+ if (!lines.length)
158
+ return null;
159
+ return parseBlock(lines, 0, lines[0].indent).value;
160
+ }