@hilvana/recipes 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/engine.d.ts CHANGED
@@ -36,6 +36,8 @@ export interface Plan {
36
36
  destructiveSteps: number[];
37
37
  /** Page count predicted after each step (when it could be computed). */
38
38
  predictedPages?: number[];
39
+ /** How many files the recipe will produce (more than one when it ends with `split`). */
40
+ outputCount?: number;
39
41
  /** Simplifications made while converting Word files, in plain language. */
40
42
  warnings: string[];
41
43
  }
@@ -46,7 +48,16 @@ export interface GoalResult {
46
48
  met: boolean;
47
49
  message: string;
48
50
  }
51
+ export interface RunOutput {
52
+ bytes: Uint8Array;
53
+ filename: string;
54
+ pageCount: number;
55
+ byteLength: number;
56
+ }
49
57
  export interface RunResult {
58
+ /** Every file the recipe produced: one, or one per part when the recipe ends with `split`. */
59
+ outputs: RunOutput[];
60
+ /** The first output (the only one unless the recipe splits); kept for single-output callers. */
50
61
  bytes: Uint8Array;
51
62
  filename: string;
52
63
  pageCount: number;
package/dist/engine.js CHANGED
@@ -81,6 +81,7 @@ export async function plan(raw, files, langOrOpts = 'es') {
81
81
  const steps = withSource(recipe.steps);
82
82
  const offset = steps.length - recipe.steps.length; // 1 when a merge was prepended
83
83
  let pages;
84
+ let outputCount = 1;
84
85
  const predicted = [];
85
86
  steps.forEach((step, i) => {
86
87
  const n = i + 1 - offset; // step number as the user wrote it (0 = implicit merge)
@@ -155,6 +156,17 @@ export async function plan(raw, files, langOrOpts = 'es') {
155
156
  checkRange(step.pages ?? 'last');
156
157
  break;
157
158
  }
159
+ case 'split': {
160
+ if (i !== steps.length - 1)
161
+ issues.push({ code: 'SPLIT_NOT_LAST', message: t(lang, 'SPLIT_NOT_LAST', { index: n }), step: n });
162
+ for (const r of step.ranges ?? []) {
163
+ const sel = checkRange(r);
164
+ if (pages !== undefined && sel.length === 0)
165
+ issues.push({ code: 'INVALID_RANGE', message: t(lang, 'INVALID_RANGE', { expr: r }), step: n });
166
+ }
167
+ outputCount = step.ranges ? step.ranges.length : pages;
168
+ break;
169
+ }
158
170
  case 'rotate':
159
171
  case 'stampText':
160
172
  case 'watermark':
@@ -192,6 +204,7 @@ export async function plan(raw, files, langOrOpts = 'es') {
192
204
  goals: describeGoals(recipe.goals, lang),
193
205
  destructiveSteps,
194
206
  predictedPages: predicted,
207
+ outputCount,
195
208
  };
196
209
  }
197
210
  function describeGoals(goals, lang) {
@@ -261,16 +274,39 @@ export async function run(raw, files, opts = {}) {
261
274
  throw new RecipeError([issueFromError(err, lang, i + 1)]);
262
275
  }
263
276
  }
264
- const result = doc;
265
- const info = await core.inspect(result);
266
- const goals = verify(recipe.goals, result, info, lang);
267
277
  const firstName = (files[0]?.name ?? 'documento').replace(/\.[^.]+$/, '');
268
- const filename = safeFilename((recipe.output?.filename ?? '{name}-hilvana.pdf').replace('{date}', today()).replace('{name}', firstName));
278
+ const named = safeFilename((recipe.output?.filename ?? '{name}-hilvana.pdf').replace('{date}', today()).replace('{name}', firstName));
279
+ const base = named.replace(/\.pdf$/i, '');
280
+ // A final split turns the document into parts; every other recipe has exactly one output.
281
+ const last = steps[steps.length - 1];
282
+ const parts = [];
283
+ if (last.op === 'split') {
284
+ try {
285
+ const pieces = last.ranges ? await core.split(doc, last.ranges) : await core.burst(doc);
286
+ pieces.forEach((bytes, i) => parts.push({ bytes, label: last.ranges ? last.ranges[i] : String(i + 1) }));
287
+ }
288
+ catch (err) {
289
+ throw new RecipeError([issueFromError(err, lang, steps.length - (steps.length - recipe.steps.length))]);
290
+ }
291
+ }
292
+ else {
293
+ parts.push({ bytes: doc });
294
+ }
295
+ const outputs = [];
296
+ const goals = [];
297
+ for (const part of parts) {
298
+ const info = await core.inspect(part.bytes);
299
+ const filename = safeFilename(part.label ? `${base}-${part.label.replace(/[^\w-]+/g, '_')}` : base) + '.pdf';
300
+ outputs.push({ bytes: part.bytes, filename, pageCount: info.pageCount, byteLength: part.bytes.byteLength });
301
+ for (const g of verify(recipe.goals, part.bytes, info, lang))
302
+ goals.push(parts.length > 1 ? { ...g, message: `${filename}: ${g.message}` } : g);
303
+ }
269
304
  return {
270
- bytes: result,
271
- filename: filename.toLowerCase().endsWith('.pdf') ? filename : `${filename}.pdf`,
272
- pageCount: info.pageCount,
273
- byteLength: result.byteLength,
305
+ outputs,
306
+ bytes: outputs[0].bytes,
307
+ filename: outputs[0].filename,
308
+ pageCount: outputs[0].pageCount,
309
+ byteLength: outputs[0].byteLength,
274
310
  goals,
275
311
  allGoalsMet: goals.every((g) => g.met),
276
312
  steps: p.steps,
@@ -293,6 +329,7 @@ async function apply(step, doc, ctx) {
293
329
  case 'stripMetadata': return core.stripMetadata(need());
294
330
  case 'setMetadata': return core.setMetadata(need(), step);
295
331
  case 'optimize': return core.optimize(need());
332
+ case 'split': return need(); // applied after every other step, see run()
296
333
  case 'compress': {
297
334
  // With no explicit level, aim for the recipe's size goal if there is one.
298
335
  const target = step.targetBytes ?? (step.level ? undefined : ctx.goals?.maxBytes);
package/dist/i18n.js CHANGED
@@ -34,6 +34,7 @@ const messages = {
34
34
  'word.COLUMNS_IGNORED': 'el texto en varias columnas se puso en una sola',
35
35
  NO_PDF_INPUTS: 'La receta necesita al menos un PDF de entrada.',
36
36
  SOURCE_NOT_FIRST: 'El paso {index} crea un documento nuevo; solo puede ir de primero.',
37
+ SPLIT_NOT_LAST: 'El paso {index} divide el documento en varios archivos; solo puede ir de último.',
37
38
  CONFIRMATION_REQUIRED: 'La receta tiene pasos que eliminan contenido o información ({steps}). Confírmala para ejecutarla.',
38
39
  // describe
39
40
  'step.merge': 'Unir {files}',
@@ -52,6 +53,8 @@ const messages = {
52
53
  'step.optimize': 'Optimizar la estructura del archivo',
53
54
  'step.compress': 'Comprimir (nivel {level})',
54
55
  'step.compressTarget': 'Comprimir hasta {target} como máximo',
56
+ 'step.splitEach': 'Dividir en un archivo por página',
57
+ 'step.splitRanges': 'Dividir en {count} archivos: {ranges}',
55
58
  'level.lossless': 'sin pérdida',
56
59
  'level.balanced': 'equilibrado',
57
60
  'level.strong': 'fuerte',
@@ -103,6 +106,7 @@ const messages = {
103
106
  'word.COLUMNS_IGNORED': 'multi-column text was set in a single column',
104
107
  NO_PDF_INPUTS: 'The recipe needs at least one PDF input.',
105
108
  SOURCE_NOT_FIRST: 'Step {index} creates a new document; it can only come first.',
109
+ SPLIT_NOT_LAST: 'Step {index} splits the document into several files; it can only come last.',
106
110
  CONFIRMATION_REQUIRED: 'The recipe has steps that remove content or information ({steps}). Confirm it to run it.',
107
111
  'step.merge': 'Merge {files}',
108
112
  'step.mergeAll': 'Merge every PDF in the order received',
@@ -120,6 +124,8 @@ const messages = {
120
124
  'step.optimize': 'Optimize the file structure',
121
125
  'step.compress': 'Compress ({level} level)',
122
126
  'step.compressTarget': 'Compress to at most {target}',
127
+ 'step.splitEach': 'Split into one file per page',
128
+ 'step.splitRanges': 'Split into {count} files: {ranges}',
123
129
  'level.lossless': 'lossless',
124
130
  'level.balanced': 'balanced',
125
131
  'level.strong': 'strong',
@@ -176,6 +182,8 @@ export function describeStep(step, lang) {
176
182
  return step.targetBytes !== undefined
177
183
  ? t(lang, 'step.compressTarget', { target: formatBytes(step.targetBytes) })
178
184
  : t(lang, 'step.compress', { level: t(lang, `level.${step.level ?? 'balanced'}`) });
185
+ case 'split':
186
+ return step.ranges ? t(lang, 'step.splitRanges', { count: step.ranges.length, ranges: step.ranges.join('; ') }) : t(lang, 'step.splitEach');
179
187
  }
180
188
  }
181
189
  /** Today's date as YYYY-MM-DD in the user's local time zone. */
package/dist/schema.d.ts CHANGED
@@ -100,6 +100,10 @@ export declare const CompressStep: z.ZodObject<{
100
100
  }>>;
101
101
  targetBytes: z.ZodOptional<z.ZodNumber>;
102
102
  }, z.core.$strict>;
103
+ export declare const SplitStep: z.ZodObject<{
104
+ op: z.ZodLiteral<"split">;
105
+ ranges: z.ZodOptional<z.ZodArray<z.ZodString>>;
106
+ }, z.core.$strict>;
103
107
  export declare const Step: z.ZodDiscriminatedUnion<[z.ZodObject<{
104
108
  op: z.ZodLiteral<"merge">;
105
109
  files: z.ZodOptional<z.ZodArray<z.ZodString>>;
@@ -187,6 +191,9 @@ export declare const Step: z.ZodDiscriminatedUnion<[z.ZodObject<{
187
191
  max: "max";
188
192
  }>>;
189
193
  targetBytes: z.ZodOptional<z.ZodNumber>;
194
+ }, z.core.$strict>, z.ZodObject<{
195
+ op: z.ZodLiteral<"split">;
196
+ ranges: z.ZodOptional<z.ZodArray<z.ZodString>>;
190
197
  }, z.core.$strict>], "op">;
191
198
  export type Step = z.infer<typeof Step>;
192
199
  export declare const Goals: z.ZodObject<{
@@ -287,6 +294,9 @@ export declare const Recipe: z.ZodObject<{
287
294
  max: "max";
288
295
  }>>;
289
296
  targetBytes: z.ZodOptional<z.ZodNumber>;
297
+ }, z.core.$strict>, z.ZodObject<{
298
+ op: z.ZodLiteral<"split">;
299
+ ranges: z.ZodOptional<z.ZodArray<z.ZodString>>;
290
300
  }, z.core.$strict>], "op">>;
291
301
  output: z.ZodOptional<z.ZodObject<{
292
302
  filename: z.ZodOptional<z.ZodString>;
@@ -391,6 +401,9 @@ export declare const recipeJsonSchema: () => z.core.ZodStandardJSONSchemaPayload
391
401
  max: "max";
392
402
  }>>;
393
403
  targetBytes: z.ZodOptional<z.ZodNumber>;
404
+ }, z.core.$strict>, z.ZodObject<{
405
+ op: z.ZodLiteral<"split">;
406
+ ranges: z.ZodOptional<z.ZodArray<z.ZodString>>;
394
407
  }, z.core.$strict>], "op">>;
395
408
  output: z.ZodOptional<z.ZodObject<{
396
409
  filename: z.ZodOptional<z.ZodString>;
@@ -403,5 +416,5 @@ export declare const recipeJsonSchema: () => z.core.ZodStandardJSONSchemaPayload
403
416
  }, z.core.$strict>>;
404
417
  }, z.core.$strict>>;
405
418
  /** Steps that drop content or overwrite information; running them requires explicit confirmation. */
406
- export declare const DESTRUCTIVE_OPS: Set<"merge" | "fromImages" | "select" | "remove" | "rotate" | "stampText" | "sign" | "watermark" | "numberPages" | "stripMetadata" | "setMetadata" | "optimize" | "compress">;
419
+ export declare const DESTRUCTIVE_OPS: Set<"merge" | "fromImages" | "select" | "remove" | "rotate" | "stampText" | "sign" | "watermark" | "numberPages" | "stripMetadata" | "setMetadata" | "optimize" | "compress" | "split">;
407
420
  //# sourceMappingURL=schema.d.ts.map
package/dist/schema.js CHANGED
@@ -65,6 +65,11 @@ export const CompressStep = z.object({
65
65
  targetBytes: z.number().int().positive().optional()
66
66
  .describe('Try stronger levels until the file is at most this size. Defaults to goals.maxBytes when no level is given.'),
67
67
  }).strict();
68
+ export const SplitStep = z.object({
69
+ op: z.literal('split'),
70
+ ranges: z.array(pages).min(1).max(500).optional()
71
+ .describe('One output file per range, in order (e.g. ["1-3", "4-last"]). Omit for one file per page.'),
72
+ }).strict().describe('Last step only: splits the document into several output files.');
68
73
  export const Step = z.discriminatedUnion('op', [
69
74
  MergeStep,
70
75
  FromImagesStep,
@@ -79,6 +84,7 @@ export const Step = z.discriminatedUnion('op', [
79
84
  SetMetadataStep,
80
85
  OptimizeStep,
81
86
  CompressStep,
87
+ SplitStep,
82
88
  ]);
83
89
  export const Goals = z.object({
84
90
  maxBytes: z.number().int().positive().optional().describe('The result must be at most this many bytes.'),
@@ -92,7 +98,7 @@ export const Recipe = z.object({
92
98
  description: z.string().max(1000).optional(),
93
99
  steps: z.array(Step).min(1).max(50),
94
100
  output: z.object({
95
- filename: z.string().max(200).optional().describe('Supports {date} and {name} (first input without extension).'),
101
+ filename: z.string().max(200).optional().describe('Supports {date} and {name} (first input without extension). With a final split step, each part adds "-<range>" (or "-<page>") before .pdf.'),
96
102
  }).strict().optional(),
97
103
  goals: Goals.optional(),
98
104
  }).strict();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hilvana/recipes",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Hilvana recipes: a versioned JSON format for chained PDF and Word operations, with validation, execution and goal verification.",
5
5
  "keywords": [
6
6
  "pdf",
@@ -43,8 +43,8 @@
43
43
  "provenance": true
44
44
  },
45
45
  "dependencies": {
46
- "@hilvana/core": "0.1.1",
46
+ "@hilvana/core": "0.2.0",
47
47
  "zod": "^4.1.0",
48
- "@hilvana/office": "0.1.1"
48
+ "@hilvana/office": "0.2.0"
49
49
  }
50
50
  }