Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

proto-expand

Package Overview
Dependencies
Maintainers
0
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

proto-expand - npm Package Compare versions

Comparing version 1.2.3 to 1.2.4

84

dist/index.d.ts

@@ -63,6 +63,11 @@ type Value = number | string | null | boolean;

type ObjectType = {
[key: string]: any;
};
interface InstructionImplementation {
type: string;
toKnot(): any;
toKnot(): ObjectType;
expand(dimensions: Dimensions): InstructionImplementation;
toObject(): ObjectType;
}

@@ -88,15 +93,24 @@

readonly implementation?: InstructionImplementation;
constructor(id: string, description: string, image: string, attachments: string[], implementation: any, key?: string, type?: string, goal?: string[], subject?: string[], values?: Map<string, string>);
static fromKnotArray(strings: string[], activityId: string): Instruction;
constructor(id: string, description: string, image: string, attachments: string[], implementation: InstructionImplementation, key?: string, type?: string, goal?: string[], subject?: string[], values?: Map<string, string>);
static fromKnotArray(strings: string[], idGenerator: IdGenerator): Instruction;
toArray(activity: Activity, activitySeq: number, step: number): Array<string>;
generateValues(activityId: string): string[];
expand(activityId: string, dimensions: Dimensions): Instruction[];
expandValues(activityId: string, regexp: RegExp, i: number, name: string): Instruction;
expand(idGenerator: IdGenerator, dimensions: Dimensions): Instruction[];
expandValues(idGenerator: IdGenerator, regexp: RegExp, i: number, name: string): Instruction;
expandImplementation(dimensions: Dimensions): Instruction[];
toObject(): ObjectType;
/**
* Create an Activity Definition from an untyped equivalent object
* @param id The instruction id
* @param obj
*/
static fromObject(obj: any): Instruction;
static fromObject(id: string, obj: ObjectType): Instruction;
}
declare class IdGenerator {
readonly activityId: string;
private idSet;
private counter;
constructor(activityId: string);
getId(id: string): string;
}

@@ -117,7 +131,9 @@ /**

expand(dimensions: Dimensions): Array<Activity>;
toObject(): [string, ObjectType];
/**
* Create an Activity Definition from an untyped equivalent object
* @param id
* @param obj
*/
static fromObject(obj: any): Activity;
static fromObject(id: string, obj: ObjectType): Activity;
}

@@ -138,23 +154,14 @@

/**
* Another contrived function
* Get a `knot` entry and parse it to get the JSON object inside
* To do that:
* 1. double quotes replace quotes not preceded by backslash
* 2. a single quote replaces quotes preceded by backslash
* @param str
*/
declare const parseKnotEntry: (str: string) => any;
/**
* Get an object, create a JSON and then entangle it to a `knot` entry
* @param obj
*/
declare const knotEntry: (obj: any) => string;
declare function knotEntry(obj: ObjectType): string;
/**
* Untangle the text of a 'knot' to a valid JSON format
*/
declare const untangle: (str: string) => any[][];
declare function untangle(str: string): any[][];
/**
* Entangle a JSON to the text of a 'knot' entry
*/
declare const entangle: (obj: any) => any;
declare function entangle(obj: any[][]): string;
/**

@@ -164,3 +171,3 @@ * Parse a `knot` array of instructions creating an array of activities.

*/
declare const parseKnotArray: (knot: string[][]) => Array<Activity>;
declare const parseKnotArray: (knot: string[][]) => Activity[];

@@ -178,9 +185,5 @@ /**

readonly primaryKey?: string[];
readonly options?: {
[key: string]: any;
};
readonly options?: ObjectType;
readonly activities: Activity[];
constructor(name: string, title: string, description: string, roles: string[], primaryKey: string[], options: {
[key: string]: any;
}, activities: Activity[]);
constructor(name: string, title: string, description: string, roles: string[], primaryKey: string[], options: ObjectType, activities: Activity[]);
/**

@@ -198,6 +201,2 @@ * Contrived method that gets the activities from the process and returns a `string` in the "knot" format

/**
* Generate a YAML string for the current process
*/
toYaml(): string;
/**
* Creates a ProcessDefinition from a given `knot` array.

@@ -217,6 +216,19 @@ *

/**
* Create a Process Definition from a string in YAML format
* @param content
*/
static fromYaml(content: string): ProcessDefinition;
/**
* Create a Process Definition from an untyped equivalent object
* @param obj
*/
static fromObject(obj: any): ProcessDefinition;
static fromObject(obj: ObjectType): ProcessDefinition;
/**
* Create a Generic Object tp be serialized from the current Process Definition
*/
toObject(): ObjectType;
/**
* Generate a YAML string for the current process
*/
toYaml(): string;
}

@@ -252,2 +264,12 @@ /**

/**
* Another contrived function
* Get a `knot` entry and parse it to get the JSON object inside
* To do that:
* 1. double quotes replace quotes not preceded by backslash
* 2. a single quote replaces quotes preceded by backslash
* @param str
*/
declare function parseKnotEntry(str: string): ObjectType;
export { type Dimensions, type FlatPayload, type Payload, ProcessDefinition, type Value, createAssignment, entangle, expandString, extractDimensions, findFirst, findVariable, flattenPayload, knotEntry, parseKnotArray, parseKnotEntry, parseKnotStringToArray, signature, toKnotRow, untangle };

@@ -30,4 +30,4 @@ var __create = Object.create;

// src/index.ts
var src_exports = {};
__export(src_exports, {
var index_exports = {};
__export(index_exports, {
ProcessDefinition: () => ProcessDefinition,

@@ -49,8 +49,19 @@ createAssignment: () => createAssignment,

});
module.exports = __toCommonJS(src_exports);
module.exports = __toCommonJS(index_exports);
// src/parse.ts
// src/ProcessDefinition.ts
var import_yaml2 = __toESM(require("yaml"));
// src/parseKnotEntry.ts
var import_json5 = __toESM(require("json5"));
function parseKnotEntry(str) {
let cleanText = str.replace(/(?<!\\)"/g, "\\'").replace(/(?<!\\)'/g, '"').replace(/\\'/g, "'").replace(/"(.*?)"/gs, (match) => match.replace(/\n/g, "\\n"));
try {
return import_json5.default.parse(cleanText);
} catch (err) {
throw err;
}
}
// src/generateYaml.ts
// src/YamlGenerate.ts
var import_yaml = __toESM(require("yaml"));

@@ -132,14 +143,2 @@ function generateYaml(object, header, width, indentation) {

/**
* Generate a YAML string for the current process
*/
toYaml() {
const header = `
SWAR Version 1.2 Process definition
yaml-language-server: $schema=${processSchema}
`;
const seqWidth = 50;
const indentation = 4;
return generateYaml(this, header, seqWidth, indentation);
}
/**
* Creates a ProcessDefinition from a given `knot` array.

@@ -171,2 +170,9 @@ *

/**
* Create a Process Definition from a string in YAML format
* @param content
*/
static fromYaml(content) {
return this.fromObject(import_yaml2.default.parse(content));
}
/**
* Create a Process Definition from an untyped equivalent object

@@ -183,5 +189,31 @@ * @param obj

obj.options,
obj.activities.map((activity) => Activity.fromObject(activity))
Object.entries(obj.activities).map(([id, obj2]) => Activity.fromObject(id, obj2))
);
}
/**
* Create a Generic Object tp be serialized from the current Process Definition
*/
toObject() {
return {
name: this.name,
title: this.title,
description: this.description,
roles: this.roles,
primaryKey: this.primaryKey,
options: this.options,
activities: Object.fromEntries(this.activities.map((activity) => activity.toObject()))
};
}
/**
* Generate a YAML string for the current process
*/
toYaml() {
const header = `
SWAR Version 1.2 Process definition
yaml-language-server: $schema=${processSchema}
`;
const seqWidth = 50;
const indentation = 4;
return generateYaml(this.toObject(), header, seqWidth, indentation);
}
};

@@ -250,2 +282,5 @@ var findFirst = (counts, strings, prefix = "@") => {

}
toObject() {
return this;
}
static fromObject(obj) {

@@ -268,2 +303,5 @@ return new _Questions(obj.message, obj.questions.map((q) => new Question(q.id, q.text, q.answers, q.default, q.height)));

}
toObject() {
return this;
}
static parse(obj) {

@@ -286,16 +324,16 @@ return new _Photos(obj.inputs.reduce((acc, { id, dsc }) => {

var Form2 = class _Form2 {
constructor(title, fields, expressions, order) {
constructor(title, fields, expressions) {
this.type = "form2";
this.title = title;
this.expressions = expressions;
this.fields = fields;
this.expressions = expressions;
this.order = order;
}
toKnot() {
const expressions = messUpExpressions(this.fields, this.expressions);
return {
type: "FORM2",
CALCULOS: this.expressions ? {
CALCULOS: expressions ? {
proc: {
c_clean: this.expressions,
c_orden: this.order
c_clean: expressions,
c_orden: Object.keys(expressions)
}

@@ -315,34 +353,47 @@ } : void 0,

const fields = [];
const expressions = /* @__PURE__ */ new Map();
const order = [];
const expressions = {};
let rowId = 0;
for (let i = 1; i <= n; i++) {
for (const field of this.fields) {
const newField = {};
if (field.type === "row")
field.id = `row_${rowId++}`;
for (const [k, v2] of Object.entries(field)) {
if (v2 !== void 0)
newField[k] = expandString(regexp, i, name, v2.toString());
if (v2 !== void 0) {
if (Array.isArray(v2))
newField[k] = v2.map((e) => expandString(regexp, i, name, e.toString()));
else
newField[k] = expandString(regexp, i, name, v2.toString());
}
}
fields.push(Form2Field.fromObject(newField));
const { id, ...rest } = newField;
fields.push(Form2Field.fromObject(id, newField));
}
for (const [k, es] of Object.entries(this.expressions))
expressions[expandString(regexp, i, name, k)] = es.map((e) => expandString(regexp, i, name, e));
for (const o of this.order)
order.push(expandString(regexp, i, name, o));
}
return new _Form2(this.title, fields, expressions, order);
return new _Form2(this.title, fields, expressions);
}
static parse(obj) {
var _a, _b;
const title = (_b = (_a = obj.inputs.filter((e) => e.type === "title")[0]) == null ? void 0 : _a.title) != null ? _b : "";
const title = (_b = (_a = obj.inputs.find((e) => e.type === "title")) == null ? void 0 : _a.title) != null ? _b : "";
const inputs = obj.inputs.filter((e) => e.type !== "title");
const fields = inputs.map((field) => Form2Field.parse(field));
const [exp, order] = obj.CALCULOS ? [obj.CALCULOS.proc.c_clean, obj.CALCULOS.proc.c_orden] : [void 0, void 0];
return new _Form2(title, fields, exp, order);
let rowId = 0;
const fs = inputs.map((field) => Form2Field.parse(field.type === "row" ? `row_${rowId++}` : field.id, field));
const [fields, exp] = obj.CALCULOS ? cleanUpExpressions(fs, obj.CALCULOS.proc.c_clean, obj.CALCULOS.proc.c_orden) : [fs, void 0, void 0];
return new _Form2(title, fields, exp);
}
toObject() {
return {
type: this.type,
title: this.title,
fields: Object.fromEntries(this.fields.map((field) => field.toObject())),
expressions: this.expressions
};
}
static fromObject(obj) {
return new _Form2(
obj.title,
obj.fields.map((f) => Form2Field.fromObject(f)),
obj.expressions,
obj.order
Object.entries(obj.fields).map(([id, obj2]) => Form2Field.fromObject(id, obj2)),
obj.expressions
);

@@ -354,3 +405,3 @@ }

this.id = id;
this.type = type;
this.type = type === "input" ? void 0 : type;
this.options = options;

@@ -360,3 +411,3 @@ this.required = required;

this.check = check;
this.placeholder = placeholder;
this.placeholder = type === "choice" ? void 0 : placeholder;
this.origin = origin;

@@ -368,8 +419,9 @@ this.width = width;

toKnot() {
var _a;
return {
id: this.id,
type: this.type,
type: (_a = this.type) != null ? _a : "input",
obligatorio: this.required,
revisar: this.check,
placeholder: this.placeholder,
placeholder: this.type === "choice" ? this.id : this.placeholder,
label: this.label !== void 0 ? this.label : void 0,

@@ -379,7 +431,7 @@ x0: this.origin,

optionWidth: this.optionWidth,
options: this.options,
options: joinOptions(this.options),
defaultValue: this.default
};
}
static parse(field) {
static parse(realId, field) {
const {

@@ -405,5 +457,5 @@ id,

return new _Form2Field(
id,
realId,
type,
options,
splitOptions(options),
obligatorio,

@@ -419,5 +471,19 @@ label ? label : text ? text : void 0,

}
static fromObject(o) {
toObject() {
return [this.id, {
type: this.type,
options: this.options,
required: this.required,
label: this.label,
check: this.check,
placeholder: this.placeholder,
origin: this.origin,
width: this.width,
optionWidth: this.optionWidth,
default: this.default
}];
}
static fromObject(id, o) {
return new _Form2Field(
o.id,
id,
o.type,

@@ -436,11 +502,44 @@ o.options,

};
function splitOptions(input) {
return input ? input.match(/'([^']+)'/g).map((item) => item.replace(/'/g, "")) : void 0;
}
function joinOptions(input) {
return input ? input.map((item) => `'${item}'`).join(",") : void 0;
}
function cleanUpExpressions(fs, expressions, expressionsOrder) {
const cleanExpressions = {};
for (const e of expressionsOrder) {
const es = expressions[e].filter((e2) => !e2.startsWith("isChoice"));
if (es.length > 0) {
cleanExpressions[e] = es;
}
}
return [fs, cleanExpressions];
}
function messUpExpressions(fs, expressions) {
if (!expressions) return void 0;
const result = {};
for (const f of fs) {
let validation = f.id + "_valid";
const es = expressions[validation];
if (es)
result[validation] = es;
else if (f.type === "choice")
result[validation] = [`isChoice(${f.id}, ${f.id}_OPTIONS)`];
}
for (const [key, es] of Object.entries(expressions)) {
if (!key.endsWith("_valid"))
result[key] = es;
}
return result;
}
// src/Form.ts
var Form = class _Form {
constructor(title, fields, format, key) {
constructor(title, format, key, fields) {
this.type = "form";
this.title = title;
this.fields = fields;
this.key = key ? key : void 0;
this.format = format;
this.key = key ? key : void 0;
}

@@ -453,3 +552,3 @@ toKnot() {

if (this.key) obj["key"] = this.key;
if (this.format || this.format === null) obj["EvidenceFormat"] = this.format;
if (this.format || this.format === null) obj["EvidenceFormat"] = this.format === null ? null : { key: this.format };
return obj;

@@ -463,5 +562,7 @@ }

const { inputs, key, EvidenceFormat } = obj;
const title = (_b = (_a = inputs.filter((e) => e.type === "title")[0]) == null ? void 0 : _a.title) != null ? _b : "";
const title = (_b = (_a = inputs.find((e) => e.type === "title")) == null ? void 0 : _a.title) != null ? _b : "";
let rowId = 0;
const fields = inputs.filter((e) => e.type !== "title").map((field) => {
const { id, type, placeholder, revisar, obligatorio, width, x0, defaultValue, ...rest } = field;
const realId = type === "row" ? `row_${rowId++}` : id;
if (Object.keys(rest).length > 0) {

@@ -471,3 +572,3 @@ throw new Error(`Unknown fields ${rest}`);

return new FormField(
id,
realId,
type,

@@ -482,19 +583,26 @@ obligatorio,

});
return new _Form(title, fields, EvidenceFormat, key);
return new _Form(title, EvidenceFormat ? EvidenceFormat.key : EvidenceFormat, key, fields);
}
toObject() {
return {
type: this.type,
title: this.title,
format: this.format,
key: this.key,
fields: Object.fromEntries(this.fields.map((field) => field.toObject()))
};
}
static fromObject(obj) {
return new _Form(
obj.title,
obj.fields.map((f) => FormField.fromObject(f)),
obj.format,
obj.key
);
return new _Form(obj.title, obj.format, obj.key, Object.entries(obj.fields ? obj.fields : []).map(([id, obj2]) => FormField.fromObject(id, obj2)));
}
};
function defaultCheck(id) {
return `validarString('${id}')`;
}
var FormField = class _FormField {
constructor(id, type, required, check, placeholder, origin, width, defaultValue) {
this.id = id;
this.type = type;
this.type = type === "input" ? void 0 : type;
this.required = required;
this.check = check;
this.check = check && check === defaultCheck(id) ? void 0 : check;
this.placeholder = placeholder;

@@ -506,7 +614,9 @@ this.origin = origin;

toKnot() {
var _a;
const type = (_a = this.type) != null ? _a : "input";
return {
id: this.id,
type: this.type,
type,
obligatorio: this.required,
revisar: this.check,
revisar: this.check ? this.check : type === "input" ? defaultCheck(this.id) : void 0,
placeholder: this.placeholder,

@@ -518,5 +628,16 @@ x0: this.origin ? "return " + this.origin : void 0,

}
static fromObject(o) {
toObject() {
return [this.id, {
type: this.type,
required: this.required,
check: this.check,
placeholder: this.placeholder,
origin: this.origin,
width: this.width,
default: this.default
}];
}
static fromObject(id, o) {
return new _FormField(
o.id,
id,
o.type,

@@ -559,2 +680,5 @@ o.required,

}
toObject() {
return this;
}
};

@@ -582,2 +706,5 @@

}
toObject() {
return this;
}
};

@@ -605,2 +732,5 @@

}
toObject() {
return this;
}
toKnot() {

@@ -638,2 +768,5 @@ var _a;

}
toObject() {
return this;
}
};

@@ -654,2 +787,5 @@

}
toObject() {
return this;
}
};

@@ -694,2 +830,5 @@

}
toObject() {
return this;
}
static fromObject(obj) {

@@ -742,3 +881,3 @@ return new _FreeForm(

constructor(id, description, image, attachments, implementation, key, type, goal, subject, values) {
this.id = id;
this.id = id ? id.trim() : void 0;
this.description = description;

@@ -754,3 +893,3 @@ this.image = image;

}
static fromKnotArray(strings, activityId) {
static fromKnotArray(strings, idGenerator) {
const ins = strings[0] ? parseKnotEntry(strings[0]) : void 0;

@@ -767,3 +906,3 @@ const [id, text, image] = ins ? [ins.id, ins.text, ins.instruccionImagen] : ["", "", ""];

return new _Instruction(
id,
idGenerator.getId(id),
text && text !== "" ? text : void 0,

@@ -773,3 +912,3 @@ image && image !== "" ? image : void 0,

implementation ? parseImplementation(implementation) : void 0,
key && key !== activityId ? key : void 0,
key && key !== idGenerator.activityId ? key : void 0,
type && type !== "Status" ? type : void 0,

@@ -790,8 +929,9 @@ goal && goal.length > 0 ? goal : void 0,

var _a, _b, _c, _d, _e, _f, _g, _h;
const id1 = this.id && !this.id.startsWith("_") ? this.id : void 0;
let json = {
id: this.id,
id: id1,
text: this.description,
instruccionImagen: this.image
};
const s = this.id || this.description ? knotEntry(json) : "";
const s = id1 || this.description ? knotEntry(json) : "";
const attachments = (_a = this.attachments) != null ? _a : [];

@@ -814,4 +954,4 @@ return [

}
expand(activityId, dimensions) {
const v = findFirst(dimensions, this.generateValues(activityId));
expand(idGenerator, dimensions) {
const v = findFirst(dimensions, this.generateValues(idGenerator.activityId));
if (!v)

@@ -821,8 +961,8 @@ return this.expandImplementation(dimensions);

const instructions = new Array();
for (let i = 1; i <= n; i++) instructions.push(this.expandValues(activityId, regexp, i, name));
for (let i = 1; i <= n; i++) instructions.push(this.expandValues(idGenerator, regexp, i, name));
return instructions;
}
expandValues(activityId, regexp, i, name) {
const values = this.generateValues(activityId).map((str) => expandString(regexp, i, name, str));
return _Instruction.fromKnotArray(values, activityId);
expandValues(idGenerator, regexp, i, name) {
const strings = this.generateValues(idGenerator.activityId).map((str) => expandString(regexp, i, name, str));
return _Instruction.fromKnotArray(strings, idGenerator);
}

@@ -833,3 +973,3 @@ expandImplementation(dimensions) {

if (!expanded) return [];
if (expanded === this.implementation) [this];
if (expanded === this.implementation) return [this];
return [new _Instruction(

@@ -848,9 +988,25 @@ this.id,

}
toObject() {
var _a;
return {
id: this.id,
description: this.description,
image: this.image,
attachments: this.attachments,
implementation: (_a = this.implementation) == null ? void 0 : _a.toObject(),
key: this.key,
type: this.type,
goal: this.goal,
subject: this.subject,
values: this.values
};
}
/**
* Create an Activity Definition from an untyped equivalent object
* @param id The instruction id
* @param obj
*/
static fromObject(obj) {
static fromObject(id, obj) {
return new _Instruction(
obj.id,
id,
obj.description,

@@ -923,4 +1079,24 @@ obj.image,

}
var IdGenerator = class {
constructor(activityId) {
this.activityId = activityId;
this.idSet = /* @__PURE__ */ new Set();
this.counter = 1;
}
getId(id) {
if (id && id !== "") {
if (this.idSet.has(id)) {
const counter = this.counter++;
const prefix = id.startsWith("_") ? "" : "_";
return this.getId(`${prefix}${id}_${counter}`);
}
this.idSet.add(id);
return id;
}
return this.getId("_" + this.activityId);
}
};
// src/Activity.ts
var console2 = __toESM(require("console"));
var escapeQuotes = (str) => str.replace(/'/g, "\\'");

@@ -937,3 +1113,3 @@ var Activity = class _Activity {

this.description,
this.instructions.flatMap((instruction) => instruction.expand(this.id, dimensions))
this.instructions.flatMap((instruction) => instruction.expand(new IdGenerator(this.id), dimensions))
);

@@ -957,3 +1133,3 @@ }

let description = expandString(regexp, i, name, this.description);
let instructions = this.instructions.map((ins) => ins.expandValues(id, regexp, i, name));
let instructions = this.instructions.map((ins) => ins.expandValues(new IdGenerator(id), regexp, i, name));
let activity = new _Activity(id, description, instructions);

@@ -964,11 +1140,35 @@ activities.push(activity);

}
toObject() {
const instructions = /* @__PURE__ */ new Map();
let rowId = 0;
for (const instruction of this.instructions) {
let { id, ...rest } = instruction.toObject();
if (!id || id === "") {
id = rest.key ? rest.key : this.id;
}
if (instructions.has(id)) {
id = `${id}_${++rowId}`;
}
instructions.set(id, rest);
}
if (instructions.size != this.instructions.length)
console2.log(instructions);
return [
this.id,
{
description: this.description,
instructions
}
];
}
/**
* Create an Activity Definition from an untyped equivalent object
* @param id
* @param obj
*/
static fromObject(obj) {
static fromObject(id, obj) {
return new _Activity(
obj.id,
id,
obj.description,
obj.instructions.map((instruction) => Instruction.fromObject(instruction))
Object.entries(obj.instructions).map(([id2, obj2]) => Instruction.fromObject(id2, obj2))
);

@@ -987,16 +1187,10 @@ }

};
var parseKnotEntry = (str) => {
let cleanText = str.replace(/(?<!\\)"/g, "\\'").replace(/(?<!\\)'/g, '"').replace(/\\'/g, "'").replace(/"(.*?)"/gs, (match) => match.replace(/\n/g, "\\n"));
try {
return import_json5.default.parse(cleanText);
} catch (err) {
throw err;
}
};
var knotEntry = (obj) => !obj ? obj : JSON.stringify(obj).replace(/'/g, "\\'").replace(/"/g, "'").replace(/\\\n/g, "\n").replace(/'/g, "'");
var untangle = (str) => {
function knotEntry(obj) {
return obj === void 0 ? void 0 : obj === null ? null : JSON.stringify(obj).replace(/'/g, "\\'").replace(/"/g, "'").replace(/\\\n/g, "\n").replace(/'/g, "'");
}
function untangle(str) {
const array = parseKnotStringToArray(str);
return array.map((line) => line.map((e) => e.startsWith("{") ? parseKnotEntry(e) : e));
};
var entangle = (obj) => {
}
function entangle(obj) {
return obj.map((line) => {

@@ -1019,3 +1213,3 @@ const activity = knotEntry(line[0]);

}).join("\n") + "\n";
};
}
var parseKnotArray = (knot) => {

@@ -1025,2 +1219,3 @@ const result = [];

let instructions = [];
let idGenerator = null;
const addActivity = () => {

@@ -1032,10 +1227,12 @@ if (current) result.push(new Activity(current.id, current.description, instructions));

const activity = Activity.fromKnotString(row[0]);
if (!current)
if (!current) {
current = activity;
else if (activity.id != current.id) {
idGenerator = new IdGenerator(activity.id);
} else if (activity.id != current.id) {
addActivity();
current = activity;
instructions = [];
idGenerator = new IdGenerator(activity.id);
}
instructions.push(Instruction.fromKnotArray(row.slice(2), current.id));
instructions.push(Instruction.fromKnotArray(row.slice(2), idGenerator));
}

@@ -1042,0 +1239,0 @@ });

@@ -30,4 +30,14 @@ #!/usr/bin/env node

// src/parseKnotEntry.ts
var import_json5 = __toESM(require("json5"));
function parseKnotEntry(str) {
let cleanText = str.replace(/(?<!\\)"/g, "\\'").replace(/(?<!\\)'/g, '"').replace(/\\'/g, "'").replace(/"(.*?)"/gs, (match) => match.replace(/\n/g, "\\n"));
try {
return import_json5.default.parse(cleanText);
} catch (err) {
throw err;
}
}
// src/parse.ts
var import_json5 = __toESM(require("json5"));
var parseKnotStringToArray = (str) => {

@@ -41,16 +51,10 @@ const cleanText = "[" + // Add first bracket

};
var parseKnotEntry = (str) => {
let cleanText = str.replace(/(?<!\\)"/g, "\\'").replace(/(?<!\\)'/g, '"').replace(/\\'/g, "'").replace(/"(.*?)"/gs, (match) => match.replace(/\n/g, "\\n"));
try {
return import_json5.default.parse(cleanText);
} catch (err) {
throw err;
}
};
var knotEntry = (obj) => !obj ? obj : JSON.stringify(obj).replace(/'/g, "\\'").replace(/"/g, "'").replace(/\\\n/g, "\n").replace(/'/g, "'");
var untangle = (str) => {
function knotEntry(obj) {
return obj === void 0 ? void 0 : obj === null ? null : JSON.stringify(obj).replace(/'/g, "\\'").replace(/"/g, "'").replace(/\\\n/g, "\n").replace(/'/g, "'");
}
function untangle(str) {
const array = parseKnotStringToArray(str);
return array.map((line) => line.map((e) => e.startsWith("{") ? parseKnotEntry(e) : e));
};
var entangle = (obj) => {
}
function entangle(obj) {
return obj.map((line) => {

@@ -73,3 +77,3 @@ const activity = knotEntry(line[0]);

}).join("\n") + "\n";
};
}
var parseKnotArray = (knot) => {

@@ -79,2 +83,3 @@ const result = [];

let instructions = [];
let idGenerator = null;
const addActivity = () => {

@@ -86,10 +91,12 @@ if (current) result.push(new Activity(current.id, current.description, instructions));

const activity = Activity.fromKnotString(row[0]);
if (!current)
if (!current) {
current = activity;
else if (activity.id != current.id) {
idGenerator = new IdGenerator(activity.id);
} else if (activity.id != current.id) {
addActivity();
current = activity;
instructions = [];
idGenerator = new IdGenerator(activity.id);
}
instructions.push(Instruction.fromKnotArray(row.slice(2), current.id));
instructions.push(Instruction.fromKnotArray(row.slice(2), idGenerator));
}

@@ -142,2 +149,5 @@ });

}
toObject() {
return this;
}
static fromObject(obj) {

@@ -160,2 +170,5 @@ return new _Questions(obj.message, obj.questions.map((q) => new Question(q.id, q.text, q.answers, q.default, q.height)));

}
toObject() {
return this;
}
static parse(obj) {

@@ -178,16 +191,16 @@ return new _Photos(obj.inputs.reduce((acc, { id, dsc }) => {

var Form2 = class _Form2 {
constructor(title, fields, expressions, order) {
constructor(title, fields, expressions) {
this.type = "form2";
this.title = title;
this.expressions = expressions;
this.fields = fields;
this.expressions = expressions;
this.order = order;
}
toKnot() {
const expressions = messUpExpressions(this.fields, this.expressions);
return {
type: "FORM2",
CALCULOS: this.expressions ? {
CALCULOS: expressions ? {
proc: {
c_clean: this.expressions,
c_orden: this.order
c_clean: expressions,
c_orden: Object.keys(expressions)
}

@@ -207,34 +220,47 @@ } : void 0,

const fields = [];
const expressions = /* @__PURE__ */ new Map();
const order = [];
const expressions = {};
let rowId = 0;
for (let i = 1; i <= n; i++) {
for (const field of this.fields) {
const newField = {};
if (field.type === "row")
field.id = `row_${rowId++}`;
for (const [k, v2] of Object.entries(field)) {
if (v2 !== void 0)
newField[k] = expandString(regexp, i, name, v2.toString());
if (v2 !== void 0) {
if (Array.isArray(v2))
newField[k] = v2.map((e) => expandString(regexp, i, name, e.toString()));
else
newField[k] = expandString(regexp, i, name, v2.toString());
}
}
fields.push(Form2Field.fromObject(newField));
const { id, ...rest } = newField;
fields.push(Form2Field.fromObject(id, newField));
}
for (const [k, es] of Object.entries(this.expressions))
expressions[expandString(regexp, i, name, k)] = es.map((e) => expandString(regexp, i, name, e));
for (const o of this.order)
order.push(expandString(regexp, i, name, o));
}
return new _Form2(this.title, fields, expressions, order);
return new _Form2(this.title, fields, expressions);
}
static parse(obj) {
var _a, _b;
const title = (_b = (_a = obj.inputs.filter((e) => e.type === "title")[0]) == null ? void 0 : _a.title) != null ? _b : "";
const title = (_b = (_a = obj.inputs.find((e) => e.type === "title")) == null ? void 0 : _a.title) != null ? _b : "";
const inputs = obj.inputs.filter((e) => e.type !== "title");
const fields = inputs.map((field) => Form2Field.parse(field));
const [exp, order] = obj.CALCULOS ? [obj.CALCULOS.proc.c_clean, obj.CALCULOS.proc.c_orden] : [void 0, void 0];
return new _Form2(title, fields, exp, order);
let rowId = 0;
const fs2 = inputs.map((field) => Form2Field.parse(field.type === "row" ? `row_${rowId++}` : field.id, field));
const [fields, exp] = obj.CALCULOS ? cleanUpExpressions(fs2, obj.CALCULOS.proc.c_clean, obj.CALCULOS.proc.c_orden) : [fs2, void 0, void 0];
return new _Form2(title, fields, exp);
}
toObject() {
return {
type: this.type,
title: this.title,
fields: Object.fromEntries(this.fields.map((field) => field.toObject())),
expressions: this.expressions
};
}
static fromObject(obj) {
return new _Form2(
obj.title,
obj.fields.map((f) => Form2Field.fromObject(f)),
obj.expressions,
obj.order
Object.entries(obj.fields).map(([id, obj2]) => Form2Field.fromObject(id, obj2)),
obj.expressions
);

@@ -246,3 +272,3 @@ }

this.id = id;
this.type = type;
this.type = type === "input" ? void 0 : type;
this.options = options;

@@ -252,3 +278,3 @@ this.required = required;

this.check = check;
this.placeholder = placeholder;
this.placeholder = type === "choice" ? void 0 : placeholder;
this.origin = origin;

@@ -260,8 +286,9 @@ this.width = width;

toKnot() {
var _a;
return {
id: this.id,
type: this.type,
type: (_a = this.type) != null ? _a : "input",
obligatorio: this.required,
revisar: this.check,
placeholder: this.placeholder,
placeholder: this.type === "choice" ? this.id : this.placeholder,
label: this.label !== void 0 ? this.label : void 0,

@@ -271,7 +298,7 @@ x0: this.origin,

optionWidth: this.optionWidth,
options: this.options,
options: joinOptions(this.options),
defaultValue: this.default
};
}
static parse(field) {
static parse(realId, field) {
const {

@@ -297,5 +324,5 @@ id,

return new _Form2Field(
id,
realId,
type,
options,
splitOptions(options),
obligatorio,

@@ -311,5 +338,19 @@ label ? label : text ? text : void 0,

}
static fromObject(o) {
toObject() {
return [this.id, {
type: this.type,
options: this.options,
required: this.required,
label: this.label,
check: this.check,
placeholder: this.placeholder,
origin: this.origin,
width: this.width,
optionWidth: this.optionWidth,
default: this.default
}];
}
static fromObject(id, o) {
return new _Form2Field(
o.id,
id,
o.type,

@@ -328,11 +369,44 @@ o.options,

};
function splitOptions(input) {
return input ? input.match(/'([^']+)'/g).map((item) => item.replace(/'/g, "")) : void 0;
}
function joinOptions(input) {
return input ? input.map((item) => `'${item}'`).join(",") : void 0;
}
function cleanUpExpressions(fs2, expressions, expressionsOrder) {
const cleanExpressions = {};
for (const e of expressionsOrder) {
const es = expressions[e].filter((e2) => !e2.startsWith("isChoice"));
if (es.length > 0) {
cleanExpressions[e] = es;
}
}
return [fs2, cleanExpressions];
}
function messUpExpressions(fs2, expressions) {
if (!expressions) return void 0;
const result = {};
for (const f of fs2) {
let validation = f.id + "_valid";
const es = expressions[validation];
if (es)
result[validation] = es;
else if (f.type === "choice")
result[validation] = [`isChoice(${f.id}, ${f.id}_OPTIONS)`];
}
for (const [key, es] of Object.entries(expressions)) {
if (!key.endsWith("_valid"))
result[key] = es;
}
return result;
}
// src/Form.ts
var Form = class _Form {
constructor(title, fields, format, key) {
constructor(title, format, key, fields) {
this.type = "form";
this.title = title;
this.fields = fields;
this.key = key ? key : void 0;
this.format = format;
this.key = key ? key : void 0;
}

@@ -345,3 +419,3 @@ toKnot() {

if (this.key) obj["key"] = this.key;
if (this.format || this.format === null) obj["EvidenceFormat"] = this.format;
if (this.format || this.format === null) obj["EvidenceFormat"] = this.format === null ? null : { key: this.format };
return obj;

@@ -355,5 +429,7 @@ }

const { inputs, key, EvidenceFormat } = obj;
const title = (_b = (_a = inputs.filter((e) => e.type === "title")[0]) == null ? void 0 : _a.title) != null ? _b : "";
const title = (_b = (_a = inputs.find((e) => e.type === "title")) == null ? void 0 : _a.title) != null ? _b : "";
let rowId = 0;
const fields = inputs.filter((e) => e.type !== "title").map((field) => {
const { id, type, placeholder, revisar, obligatorio, width, x0, defaultValue, ...rest } = field;
const realId = type === "row" ? `row_${rowId++}` : id;
if (Object.keys(rest).length > 0) {

@@ -363,3 +439,3 @@ throw new Error(`Unknown fields ${rest}`);

return new FormField(
id,
realId,
type,

@@ -374,19 +450,26 @@ obligatorio,

});
return new _Form(title, fields, EvidenceFormat, key);
return new _Form(title, EvidenceFormat ? EvidenceFormat.key : EvidenceFormat, key, fields);
}
toObject() {
return {
type: this.type,
title: this.title,
format: this.format,
key: this.key,
fields: Object.fromEntries(this.fields.map((field) => field.toObject()))
};
}
static fromObject(obj) {
return new _Form(
obj.title,
obj.fields.map((f) => FormField.fromObject(f)),
obj.format,
obj.key
);
return new _Form(obj.title, obj.format, obj.key, Object.entries(obj.fields ? obj.fields : []).map(([id, obj2]) => FormField.fromObject(id, obj2)));
}
};
function defaultCheck(id) {
return `validarString('${id}')`;
}
var FormField = class _FormField {
constructor(id, type, required, check, placeholder, origin, width, defaultValue) {
this.id = id;
this.type = type;
this.type = type === "input" ? void 0 : type;
this.required = required;
this.check = check;
this.check = check && check === defaultCheck(id) ? void 0 : check;
this.placeholder = placeholder;

@@ -398,7 +481,9 @@ this.origin = origin;

toKnot() {
var _a;
const type = (_a = this.type) != null ? _a : "input";
return {
id: this.id,
type: this.type,
type,
obligatorio: this.required,
revisar: this.check,
revisar: this.check ? this.check : type === "input" ? defaultCheck(this.id) : void 0,
placeholder: this.placeholder,

@@ -410,5 +495,16 @@ x0: this.origin ? "return " + this.origin : void 0,

}
static fromObject(o) {
toObject() {
return [this.id, {
type: this.type,
required: this.required,
check: this.check,
placeholder: this.placeholder,
origin: this.origin,
width: this.width,
default: this.default
}];
}
static fromObject(id, o) {
return new _FormField(
o.id,
id,
o.type,

@@ -451,2 +547,5 @@ o.required,

}
toObject() {
return this;
}
};

@@ -474,2 +573,5 @@

}
toObject() {
return this;
}
};

@@ -497,2 +599,5 @@

}
toObject() {
return this;
}
toKnot() {

@@ -530,2 +635,5 @@ var _a;

}
toObject() {
return this;
}
};

@@ -546,2 +654,5 @@

}
toObject() {
return this;
}
};

@@ -586,2 +697,5 @@

}
toObject() {
return this;
}
static fromObject(obj) {

@@ -634,3 +748,3 @@ return new _FreeForm(

constructor(id, description, image, attachments, implementation, key, type, goal, subject, values) {
this.id = id;
this.id = id ? id.trim() : void 0;
this.description = description;

@@ -646,3 +760,3 @@ this.image = image;

}
static fromKnotArray(strings, activityId) {
static fromKnotArray(strings, idGenerator) {
const ins = strings[0] ? parseKnotEntry(strings[0]) : void 0;

@@ -659,3 +773,3 @@ const [id, text, image] = ins ? [ins.id, ins.text, ins.instruccionImagen] : ["", "", ""];

return new _Instruction(
id,
idGenerator.getId(id),
text && text !== "" ? text : void 0,

@@ -665,3 +779,3 @@ image && image !== "" ? image : void 0,

implementation ? parseImplementation(implementation) : void 0,
key && key !== activityId ? key : void 0,
key && key !== idGenerator.activityId ? key : void 0,
type && type !== "Status" ? type : void 0,

@@ -682,8 +796,9 @@ goal && goal.length > 0 ? goal : void 0,

var _a, _b, _c, _d, _e, _f, _g, _h;
const id1 = this.id && !this.id.startsWith("_") ? this.id : void 0;
let json = {
id: this.id,
id: id1,
text: this.description,
instruccionImagen: this.image
};
const s = this.id || this.description ? knotEntry(json) : "";
const s = id1 || this.description ? knotEntry(json) : "";
const attachments = (_a = this.attachments) != null ? _a : [];

@@ -706,4 +821,4 @@ return [

}
expand(activityId, dimensions) {
const v = findFirst(dimensions, this.generateValues(activityId));
expand(idGenerator, dimensions) {
const v = findFirst(dimensions, this.generateValues(idGenerator.activityId));
if (!v)

@@ -713,8 +828,8 @@ return this.expandImplementation(dimensions);

const instructions = new Array();
for (let i = 1; i <= n; i++) instructions.push(this.expandValues(activityId, regexp, i, name));
for (let i = 1; i <= n; i++) instructions.push(this.expandValues(idGenerator, regexp, i, name));
return instructions;
}
expandValues(activityId, regexp, i, name) {
const values = this.generateValues(activityId).map((str) => expandString(regexp, i, name, str));
return _Instruction.fromKnotArray(values, activityId);
expandValues(idGenerator, regexp, i, name) {
const strings = this.generateValues(idGenerator.activityId).map((str) => expandString(regexp, i, name, str));
return _Instruction.fromKnotArray(strings, idGenerator);
}

@@ -725,3 +840,3 @@ expandImplementation(dimensions) {

if (!expanded) return [];
if (expanded === this.implementation) [this];
if (expanded === this.implementation) return [this];
return [new _Instruction(

@@ -740,9 +855,25 @@ this.id,

}
toObject() {
var _a;
return {
id: this.id,
description: this.description,
image: this.image,
attachments: this.attachments,
implementation: (_a = this.implementation) == null ? void 0 : _a.toObject(),
key: this.key,
type: this.type,
goal: this.goal,
subject: this.subject,
values: this.values
};
}
/**
* Create an Activity Definition from an untyped equivalent object
* @param id The instruction id
* @param obj
*/
static fromObject(obj) {
static fromObject(id, obj) {
return new _Instruction(
obj.id,
id,
obj.description,

@@ -815,4 +946,24 @@ obj.image,

}
var IdGenerator = class {
constructor(activityId) {
this.activityId = activityId;
this.idSet = /* @__PURE__ */ new Set();
this.counter = 1;
}
getId(id) {
if (id && id !== "") {
if (this.idSet.has(id)) {
const counter = this.counter++;
const prefix = id.startsWith("_") ? "" : "_";
return this.getId(`${prefix}${id}_${counter}`);
}
this.idSet.add(id);
return id;
}
return this.getId("_" + this.activityId);
}
};
// src/Activity.ts
var console2 = __toESM(require("console"));
var escapeQuotes = (str) => str.replace(/'/g, "\\'");

@@ -829,3 +980,3 @@ var Activity = class _Activity {

this.description,
this.instructions.flatMap((instruction) => instruction.expand(this.id, dimensions))
this.instructions.flatMap((instruction) => instruction.expand(new IdGenerator(this.id), dimensions))
);

@@ -849,3 +1000,3 @@ }

let description = expandString(regexp, i, name, this.description);
let instructions = this.instructions.map((ins) => ins.expandValues(id, regexp, i, name));
let instructions = this.instructions.map((ins) => ins.expandValues(new IdGenerator(id), regexp, i, name));
let activity = new _Activity(id, description, instructions);

@@ -856,11 +1007,35 @@ activities.push(activity);

}
toObject() {
const instructions = /* @__PURE__ */ new Map();
let rowId = 0;
for (const instruction of this.instructions) {
let { id, ...rest } = instruction.toObject();
if (!id || id === "") {
id = rest.key ? rest.key : this.id;
}
if (instructions.has(id)) {
id = `${id}_${++rowId}`;
}
instructions.set(id, rest);
}
if (instructions.size != this.instructions.length)
console2.log(instructions);
return [
this.id,
{
description: this.description,
instructions
}
];
}
/**
* Create an Activity Definition from an untyped equivalent object
* @param id
* @param obj
*/
static fromObject(obj) {
static fromObject(id, obj) {
return new _Activity(
obj.id,
id,
obj.description,
obj.instructions.map((instruction) => Instruction.fromObject(instruction))
Object.entries(obj.instructions).map(([id2, obj2]) => Instruction.fromObject(id2, obj2))
);

@@ -870,3 +1045,6 @@ }

// src/generateYaml.ts
// src/ProcessDefinition.ts
var import_yaml2 = __toESM(require("yaml"));
// src/YamlGenerate.ts
var import_yaml = __toESM(require("yaml"));

@@ -948,14 +1126,2 @@ function generateYaml(object, header, width, indentation) {

/**
* Generate a YAML string for the current process
*/
toYaml() {
const header = `
SWAR Version 1.2 Process definition
yaml-language-server: $schema=${processSchema}
`;
const seqWidth = 50;
const indentation = 4;
return generateYaml(this, header, seqWidth, indentation);
}
/**
* Creates a ProcessDefinition from a given `knot` array.

@@ -987,2 +1153,9 @@ *

/**
* Create a Process Definition from a string in YAML format
* @param content
*/
static fromYaml(content) {
return this.fromObject(import_yaml2.default.parse(content));
}
/**
* Create a Process Definition from an untyped equivalent object

@@ -999,5 +1172,31 @@ * @param obj

obj.options,
obj.activities.map((activity) => Activity.fromObject(activity))
Object.entries(obj.activities).map(([id, obj2]) => Activity.fromObject(id, obj2))
);
}
/**
* Create a Generic Object tp be serialized from the current Process Definition
*/
toObject() {
return {
name: this.name,
title: this.title,
description: this.description,
roles: this.roles,
primaryKey: this.primaryKey,
options: this.options,
activities: Object.fromEntries(this.activities.map((activity) => activity.toObject()))
};
}
/**
* Generate a YAML string for the current process
*/
toYaml() {
const header = `
SWAR Version 1.2 Process definition
yaml-language-server: $schema=${processSchema}
`;
const seqWidth = 50;
const indentation = 4;
return generateYaml(this.toObject(), header, seqWidth, indentation);
}
};

@@ -1027,3 +1226,2 @@ var findFirst = (counts, strings, prefix = "@") => {

var import_json52 = __toESM(require("json5"));
var import_yaml2 = __toESM(require("yaml"));
var process = __toESM(require("process"));

@@ -1042,10 +1240,7 @@

// src/process-parse.ts
var console2 = __toESM(require("console"));
var console3 = __toESM(require("console"));
var program = new import_commander.Command();
function getOutputExtension(options) {
return options.yaml ? ".yaml" : options.json ? ".json" : options.knot || options.entangle || options.expand ? ".txt" : ".json5";
}
function readFile(file) {
if (!fs.existsSync(file)) {
console2.error(`Error: File "${file}" does not exist.`);
console3.error(`Error: File "${file}" does not exist.`);
process.exit(1);

@@ -1055,71 +1250,90 @@ }

}
function parseInput(content, inputExtension) {
switch (inputExtension) {
case ".json":
return JSON.parse(content);
case ".json5":
return import_json52.default.parse(content);
case ".yaml":
return import_yaml2.default.parse(content);
default:
console2.error(`Error: Illegal extension "${inputExtension}".`);
process.exit(1);
function getInputExtension(file, options) {
if (file.endsWith(".swar12.yaml" /* SWAR12 */)) {
return [".swar12.yaml" /* SWAR12 */, import_path.default.basename(file, ".swar12.yaml" /* SWAR12 */)];
}
const ext = import_path.default.extname(file);
if (!options.inputKnot && ext !== ".json5" /* JSON5 */ && ext !== ".txt" /* KNOT */)
console3.log(`Invalid extension ${ext}`);
return [ext === ".json5" /* JSON5 */ ? ".json5" /* JSON5 */ : ".txt" /* KNOT */, import_path.default.basename(file, ext)];
}
function formatOutput(output, outputExtension) {
switch (outputExtension) {
case ".json":
return JSON.stringify(output, null, 2);
case ".yaml":
return import_yaml2.default.stringify(output, { lineWidth: 0 });
default:
return import_json52.default.stringify(output, null, 2);
function loadProcessDefinition(content, extension) {
switch (extension) {
case ".txt" /* KNOT */:
return ProcessDefinition.parseKnotString(content);
case ".swar12.yaml" /* SWAR12 */:
return ProcessDefinition.fromYaml(content);
case ".json5" /* JSON5 */:
return ProcessDefinition.fromKnotArray(import_json52.default.parse(content));
}
}
function expand(pd, payloadFile) {
return pd.expand(extractDimensions(JSON.parse(readFile(payloadFile))));
function outputProcessDefinition(processDefinition, extension) {
switch (extension) {
case ".txt" /* KNOT */:
return processDefinition.exportToKnot();
case ".swar12.yaml" /* SWAR12 */:
return processDefinition.toYaml();
case ".json5" /* JSON5 */:
return import_json52.default.stringify(untangle(processDefinition.exportToKnot()), null, 2);
}
}
function generateOutput(content, inputExtension, outputExtension, options, inputKnot) {
if (options.entangle)
return entangle(parseInput(content, inputExtension));
if (options.untangle)
return formatOutput(untangle(content), outputExtension);
if (options.expandUntangled) {
const inputProcess = ProcessDefinition.parseKnotString(entangle(parseInput(content, inputExtension)));
const pd2 = expand(inputProcess, options.expandUntangled);
return formatOutput(untangle(pd2.exportToKnot()), outputExtension);
}
function processInput(inputFile, options, inputExtension) {
const content = readFile(inputFile);
if (options.expand) {
const inputProcess = ProcessDefinition.parseKnotString(content);
const pd2 = expand(inputProcess, options.expand);
return pd2.exportToKnot();
console3.log(`Expanding macros in file: '${inputFile}' using payload '${options.expand}'`);
const inputProcess = loadProcessDefinition(content, inputExtension);
const payload = JSON.parse(readFile(options.expand));
const pd = inputProcess.expand(extractDimensions(payload));
const output = outputProcessDefinition(pd, inputExtension);
return [output, inputExtension];
}
const pd = inputKnot ? ProcessDefinition.parseKnotString(content) : parseInput(content, inputExtension);
return options.knot ? pd.exportToKnot() : formatOutput(pd, outputExtension);
}
program.name("process-parse").description("Parse process files with optional output formats and expansion.").usage("[options] <files ...>").argument("<files...>", "Files to parse. Format is recognized by extension (.yaml, .txt, .json, .json5)").option("-u, --untangle", "Format a 'knot' file as a valid JSON file, retaining the internal structure").option("-e, --entangle", "Convert a JSON file into a 'knot' file, retaining the internal structure").option("-o, --overwrite", "Overwrite output files").option("-j, --json", "Output as JSON files").option("-5, --json5", "Output as JSON5 files (default)").option("-y, --yaml", "Output as YAML files").option("-k, --knot", "Output as 'knot' files (uses '.txt' extension").option("-x, --expand <payload-file>", "Expand content before output using the specified payload file").option("-X, --expand-untangled <payload-file>", 'Equivalent to "entangle -> expand -> untangle"').option("-i, --input-knot", "Interpret input as a 'knot' file regardless of file extension").option("-d, --dir <dir-name>", "Save generated files to the specified directory").showHelpAfterError().action((files, options) => {
if (options.dir && !fs.existsSync(options.dir)) fs.mkdirSync(options.dir, { recursive: true });
files.forEach((file) => {
var _a;
const inputExtension = import_path.default.extname(file);
const outputExtension = getOutputExtension(options);
const inputKnot = options.inputKnot || inputExtension === ".txt";
if (inputKnot && (options.entangle || options.expandUntangled)) {
console2.log("Can not entangle a `KNOT`");
if (options.untangle) {
if (inputExtension != ".txt" /* KNOT */) {
console3.log("Only a 'KNOT' can be untangled");
process.exit(1);
}
if (options.untangle && !inputKnot) {
console2.log("Only a 'KNOT' can be untangled");
console3.log(`Untangling KNOT file: '${inputFile}'`);
const output = import_json52.default.stringify(untangle(content), null, 2);
return [output, ".json5" /* JSON5 */];
}
if (options.entangle) {
if (inputExtension !== ".json5" /* JSON5 */) {
console3.log("Please specify a 'JSON5' file");
process.exit(1);
}
const content = readFile(file);
console2.log(`Processing file: ${file}`);
const output = generateOutput(content, inputExtension, outputExtension, options, inputKnot);
const fileName = import_path.default.basename(file, inputExtension);
const outputFileName = import_path.default.join((_a = options.dir) != null ? _a : "", `${fileName}${outputExtension}`);
console3.log(`Entangling file: '${inputFile}'`);
const output = entangle(import_json52.default.parse(content));
return [output, ".txt" /* KNOT */];
}
if (inputExtension === ".swar12.yaml" /* SWAR12 */) {
console3.log(`Converting SWAR version 1.2 file: '${inputFile}' to a KNOT file`);
const output = ProcessDefinition.fromYaml(content).exportToKnot();
return [output, ".txt" /* KNOT */];
}
if (inputExtension === ".txt" /* KNOT */) {
console3.log(`Converting KNOT file '${inputFile}' to SWAR version 1.2`);
const output = ProcessDefinition.parseKnotString(content).toYaml();
return [output, ".swar12.yaml" /* SWAR12 */];
}
if (inputExtension === ".json5" /* JSON5 */) {
console3.log(`Converting version 1.0 JSON file '${inputFile}' to SWAR version 1.2`);
const output = ProcessDefinition.fromKnotArray(import_json52.default.parse(content)).toYaml();
return [output, ".swar12.yaml" /* SWAR12 */];
}
console3.log(`Illegal input file ${inputFile}`);
process.exit(1);
}
program.name("process-parse").description("Parse process files with optional output formats and expansion.").usage("[options] <files ...>").argument("<files...>", "Files to parse. Either a KNOT, a JSON5 (a KNOT as a JSON) or a swar 1.2 YAML file").option("-u, --untangle", "KNOT to JSON5, retaining the internal structure").option("-e, --entangle", "JSON5 to KNOT file, retaining the internal structure").option("-o, --overwrite", "Overwrite output files").option("-x, --expand <payload-file>", "Expand content before output, using the specified payload file").option("-i, --input-knot", "Interpret input as a KNOT file regardless of file extension").option("-d, --dir <dir-name>", "Save generated files to the specified directory").showHelpAfterError().action((files, options) => {
files.forEach((file) => {
var _a;
const [ext, basename] = getInputExtension(file, options);
const [output, outputExtension] = processInput(file, options, ext);
if (options.dir && !fs.existsSync(options.dir))
fs.mkdirSync(options.dir, { recursive: true });
const outputFileName = import_path.default.join((_a = options.dir) != null ? _a : "", `${basename}${outputExtension}`);
if (!options.overwrite && fs.existsSync(outputFileName))
console2.log(`Refusing to override ${outputFileName} without '--overwrite' flag`);
console3.log(`Refusing to override ${outputFileName} without '--overwrite' flag`);
else {
fs.writeFileSync(outputFileName, output);
console2.log(`Output written to ${outputFileName}`);
console3.log(`Output written to '${outputFileName}'`);
}

@@ -1126,0 +1340,0 @@ });

{
"name": "proto-expand",
"version": "1.2.3",
"version": "1.2.4",
"description": "",

@@ -12,3 +12,3 @@ "main": "./dist/index.js",

"bin": {
"process-parse": "./dist/process-parse.js"
"process-parse": "dist/process-parse.js"
},

@@ -15,0 +15,0 @@ "keywords": [],

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc