@bpmnkit/core 0.2.0 → 0.4.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/bpmn/bpmn-builder.d.ts +71 -0
- package/dist/bpmn/bpmn-builder.js +240 -106
- package/dist/bpmn/bpmn-serializer.js +70 -0
- package/dist/bpmn/builder-coverage.d.ts +59 -0
- package/dist/bpmn/builder-coverage.js +62 -0
- package/dist/bpmn/compact.d.ts +6 -0
- package/dist/bpmn/compact.js +37 -2
- package/dist/bpmn/diagram-diff.d.ts +71 -0
- package/dist/bpmn/diagram-diff.js +124 -0
- package/dist/bpmn/element-catalog.d.ts +31 -0
- package/dist/bpmn/element-catalog.js +50 -0
- package/dist/bpmn/element-shape.d.ts +49 -0
- package/dist/bpmn/element-shape.js +182 -0
- package/dist/bpmn/lint.d.ts +97 -0
- package/dist/bpmn/lint.js +135 -0
- package/dist/bpmn/preserving-writer.d.ts +64 -0
- package/dist/bpmn/preserving-writer.js +70 -0
- package/dist/bpmn/stable-ids.d.ts +30 -0
- package/dist/bpmn/stable-ids.js +134 -0
- package/dist/dmn/dmn-serializer.js +7 -2
- package/dist/dmn/preserving-writer.d.ts +31 -0
- package/dist/dmn/preserving-writer.js +36 -0
- package/dist/form/preserving-writer.d.ts +47 -0
- package/dist/form/preserving-writer.js +50 -0
- package/dist/index.d.ts +15 -1
- package/dist/index.js +9 -1
- package/dist/json/index.d.ts +5 -0
- package/dist/json/index.js +3 -0
- package/dist/json/json-patch.d.ts +65 -0
- package/dist/json/json-patch.js +416 -0
- package/dist/json/json-spans.d.ts +48 -0
- package/dist/json/json-spans.js +153 -0
- package/dist/layout/types.js +4 -0
- package/dist/xml/index.d.ts +5 -1
- package/dist/xml/index.js +2 -0
- package/dist/xml/xml-parser.d.ts +39 -0
- package/dist/xml/xml-parser.js +43 -2
- package/dist/xml/xml-patch.d.ts +109 -0
- package/dist/xml/xml-patch.js +459 -0
- package/dist/xml/xml-spans.d.ts +45 -0
- package/dist/xml/xml-spans.js +74 -0
- package/package.json +2 -1
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writing a form back over the file it came from, changing as little as
|
|
3
|
+
* possible.
|
|
4
|
+
*
|
|
5
|
+
* The BPMN and DMN writers' counterpart, and the simpler of the two because a
|
|
6
|
+
* form is JSON. There is no schema question to get wrong: object key order is
|
|
7
|
+
* not information and array order always is, both by RFC 8259, so
|
|
8
|
+
* {@link preserveJsonFormatting} checks itself and this needs to supply
|
|
9
|
+
* nothing.
|
|
10
|
+
*
|
|
11
|
+
* What it buys is larger than it sounds. `exportForm` writes
|
|
12
|
+
* `JSON.stringify(…, null, 2)` in its own key order, so a form indented with
|
|
13
|
+
* tabs — or with four spaces, or minified — came back with **every line
|
|
14
|
+
* rewritten** the first time anyone touched it. Now it comes back with the line
|
|
15
|
+
* they touched.
|
|
16
|
+
*
|
|
17
|
+
* @packageDocumentation
|
|
18
|
+
*/
|
|
19
|
+
import { preserveJsonFormatting } from "../json/json-patch.js";
|
|
20
|
+
import { exportForm } from "./form-serializer.js";
|
|
21
|
+
/**
|
|
22
|
+
* Rewrites a form document to say what a freshly serialized one says, keeping
|
|
23
|
+
* the original's formatting wherever JSON cannot tell the difference.
|
|
24
|
+
*
|
|
25
|
+
* Takes both sides as text, for a caller holding a serialized document rather
|
|
26
|
+
* than a model — an editor's schema, say.
|
|
27
|
+
*
|
|
28
|
+
* @param original - The file's current contents.
|
|
29
|
+
* @param updated - The form as the serializer would write it now.
|
|
30
|
+
*/
|
|
31
|
+
export function preserveFormFormatting(original, updated) {
|
|
32
|
+
return preserveJsonFormatting(original, updated);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Serializes a form over the document it came from.
|
|
36
|
+
*
|
|
37
|
+
* @param original - The file's current contents.
|
|
38
|
+
* @param form - The form to write.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```typescript
|
|
42
|
+
* const onDisk = await readFile("approval.form", "utf8");
|
|
43
|
+
* await writeFile("approval.form", exportFormPreserving(onDisk, edited));
|
|
44
|
+
* // Renaming one label changes one line, whatever indentation the file uses.
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export function exportFormPreserving(original, form) {
|
|
48
|
+
return preserveFormFormatting(original, exportForm(form)).json;
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=preserving-writer.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,13 @@ export { Bpmn, SAMPLE_BPMN_XML } from "./bpmn/index.js";
|
|
|
6
6
|
export { applyAutoLayout } from "./bpmn/auto-layout.js";
|
|
7
7
|
export { diffSemantics, projectSemantics, semanticHash } from "./bpmn/semantic-hash.js";
|
|
8
8
|
export type { JsonValue, SemanticDiff, SemanticProjection } from "./bpmn/semantic-hash.js";
|
|
9
|
+
export { detectExecutionPlatform, lintCategories, lintDiagram } from "./bpmn/lint.js";
|
|
10
|
+
export type { DetectedPlatform, ExecutionPlatform, LintDiagnostic, LintOptions, LintReport, } from "./bpmn/lint.js";
|
|
11
|
+
export { diffDiagram } from "./bpmn/diagram-diff.js";
|
|
12
|
+
export { exportPreserving, exportPreservingResult, preserveBpmnFormatting, } from "./bpmn/preserving-writer.js";
|
|
13
|
+
export type { PreservingWriteResult } from "./bpmn/preserving-writer.js";
|
|
14
|
+
export { exportDmnPreserving, preserveDmnFormatting } from "./dmn/preserving-writer.js";
|
|
15
|
+
export type { BpmnDiffCategory, BpmnDiffPlaneSummary, BpmnDiffResult, } from "./bpmn/diagram-diff.js";
|
|
9
16
|
export { sha256Hex } from "./bpmn/sha256.js";
|
|
10
17
|
export { checkDiCompleteness } from "./bpmn/di-check.js";
|
|
11
18
|
export type { DiCompleteness } from "./bpmn/di-check.js";
|
|
@@ -30,7 +37,11 @@ export type { DecisionTableBuilder, InputOptions, OutputOptions, RuleOptions, }
|
|
|
30
37
|
export type { DmnDefinitions, DmnDecision, DmnDecisionTable, DmnInput, DmnOutput, DmnRule, DmnInputEntry, DmnOutputEntry, DmnDiagram, DmnDiagramShape, DmnDiagramEdge, DmnWaypoint, DmnTypeRef, DmnAggregation, HitPolicy, DmnInformationRequirement, DmnKnowledgeRequirement, DmnAuthorityRequirement, DmnInputData, DmnKnowledgeSource, DmnBusinessKnowledgeModel, DmnTextAnnotation, DmnAssociation, } from "./dmn/dmn-model.js";
|
|
31
38
|
export type { XmlElement } from "./types/xml-element.js";
|
|
32
39
|
export { generateId, resetIdCounter } from "./types/id-generator.js";
|
|
33
|
-
export { parseXml, serializeXml } from "./xml/index.js";
|
|
40
|
+
export { parseXml, parseXmlSpans, preserveFormatting, preserveFormattingVerified, serializeXml, } from "./xml/index.js";
|
|
41
|
+
export type { PreserveOptions, SiblingOrder, SpannedAttribute, SpannedElement, VerifiedPreserve, } from "./xml/index.js";
|
|
42
|
+
export { parseJsonSpans, preserveJsonFormatting } from "./json/index.js";
|
|
43
|
+
export { exportFormPreserving, preserveFormFormatting } from "./form/preserving-writer.js";
|
|
44
|
+
export type { JsonKind, JsonMember, JsonNode, PreservedJson } from "./json/index.js";
|
|
34
45
|
export { readDiColor, writeDiColor, BIOC_NS, COLOR_NS } from "./bpmn/di-color.js";
|
|
35
46
|
export type { DiColor } from "./bpmn/di-color.js";
|
|
36
47
|
export { optimize } from "./bpmn/optimize/index.js";
|
|
@@ -45,6 +56,9 @@ export type { BenchmarkResult, BoundingBox, ElementComparison, ElementPosition,
|
|
|
45
56
|
export type { Bounds, LayoutEdge, LayoutNode, LayoutResult, Waypoint } from "./layout/index.js";
|
|
46
57
|
export { ELEMENT_SIZES, GRID_CELL_HEIGHT, GRID_CELL_WIDTH } from "./layout/index.js";
|
|
47
58
|
export { compactify, expand } from "./bpmn/compact.js";
|
|
59
|
+
export { ELEMENT_GROUP_ORDER, ELEMENT_TYPE_GROUPS, allElementTypes, elementTypesInGroup, } from "./bpmn/element-catalog.js";
|
|
60
|
+
export type { ElementTypeGroup } from "./bpmn/element-catalog.js";
|
|
61
|
+
export { createFlowElement, retypeElement } from "./bpmn/element-shape.js";
|
|
48
62
|
export { applyOperations } from "./bpmn/operations.js";
|
|
49
63
|
export type { BpmnOperation } from "./bpmn/operations.js";
|
|
50
64
|
export { applyBpmnOperations, reconcileCompact, OperationError } from "./bpmn/full-operations.js";
|
package/dist/index.js
CHANGED
|
@@ -4,6 +4,10 @@ export { findElement, findElementInProcess, findProcess, findSequenceFlow, getAl
|
|
|
4
4
|
export { Bpmn, SAMPLE_BPMN_XML } from "./bpmn/index.js";
|
|
5
5
|
export { applyAutoLayout } from "./bpmn/auto-layout.js";
|
|
6
6
|
export { diffSemantics, projectSemantics, semanticHash } from "./bpmn/semantic-hash.js";
|
|
7
|
+
export { detectExecutionPlatform, lintCategories, lintDiagram } from "./bpmn/lint.js";
|
|
8
|
+
export { diffDiagram } from "./bpmn/diagram-diff.js";
|
|
9
|
+
export { exportPreserving, exportPreservingResult, preserveBpmnFormatting, } from "./bpmn/preserving-writer.js";
|
|
10
|
+
export { exportDmnPreserving, preserveDmnFormatting } from "./dmn/preserving-writer.js";
|
|
7
11
|
export { sha256Hex } from "./bpmn/sha256.js";
|
|
8
12
|
export { checkDiCompleteness } from "./bpmn/di-check.js";
|
|
9
13
|
export { planeForElement, listPlaneElementIds } from "./bpmn/di-planes.js";
|
|
@@ -15,7 +19,9 @@ export { Dmn, layoutDmn, benchmarkDmnLayout, compactifyDmn, expandDmn } from "./
|
|
|
15
19
|
export { Form, compactifyForm, expandForm } from "./form/index.js";
|
|
16
20
|
export { FormBuilder, GroupBuilder } from "./form/form-builder.js";
|
|
17
21
|
export { generateId, resetIdCounter } from "./types/id-generator.js";
|
|
18
|
-
export { parseXml, serializeXml } from "./xml/index.js";
|
|
22
|
+
export { parseXml, parseXmlSpans, preserveFormatting, preserveFormattingVerified, serializeXml, } from "./xml/index.js";
|
|
23
|
+
export { parseJsonSpans, preserveJsonFormatting } from "./json/index.js";
|
|
24
|
+
export { exportFormPreserving, preserveFormFormatting } from "./form/preserving-writer.js";
|
|
19
25
|
export { readDiColor, writeDiColor, BIOC_NS, COLOR_NS } from "./bpmn/di-color.js";
|
|
20
26
|
export { optimize } from "./bpmn/optimize/index.js";
|
|
21
27
|
export { renderStoryHtml } from "./bpmn/story.js";
|
|
@@ -24,6 +30,8 @@ export { layoutProcess, layoutFlowNodes } from "./layout/index.js";
|
|
|
24
30
|
export { benchmarkLayout, compareLayouts, formatBenchmarkResult, generateAutoLayout, parseReferenceLayout, } from "./layout/index.js";
|
|
25
31
|
export { ELEMENT_SIZES, GRID_CELL_HEIGHT, GRID_CELL_WIDTH } from "./layout/index.js";
|
|
26
32
|
export { compactify, expand } from "./bpmn/compact.js";
|
|
33
|
+
export { ELEMENT_GROUP_ORDER, ELEMENT_TYPE_GROUPS, allElementTypes, elementTypesInGroup, } from "./bpmn/element-catalog.js";
|
|
34
|
+
export { createFlowElement, retypeElement } from "./bpmn/element-shape.js";
|
|
27
35
|
export { applyOperations } from "./bpmn/operations.js";
|
|
28
36
|
export { applyBpmnOperations, reconcileCompact, OperationError } from "./bpmn/full-operations.js";
|
|
29
37
|
export { buildValidationDmn, findValidationStructure, getValidationInputNames, insertValidationStructure, removeValidationStructure, validationDecisionId, } from "./bpmn/input-validation.js";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { parseJsonSpans } from "./json-spans.js";
|
|
2
|
+
export type { JsonKind, JsonMember, JsonNode } from "./json-spans.js";
|
|
3
|
+
export { preserveJsonFormatting } from "./json-patch.js";
|
|
4
|
+
export type { PreservedJson } from "./json-patch.js";
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rewriting a JSON document in place, so an edit reads as an edit.
|
|
3
|
+
*
|
|
4
|
+
* The same problem [`xml-patch.ts`](../xml/xml-patch.ts) solves for XML, and
|
|
5
|
+
* mostly the same answer: take the file as it stands and the file as the
|
|
6
|
+
* serializer would write it, and return the second's content carried by the
|
|
7
|
+
* first's bytes. A form saved from a visual editor otherwise comes back with
|
|
8
|
+
* this toolkit's indentation and this toolkit's key order, and one changed
|
|
9
|
+
* label reads as a rewritten file.
|
|
10
|
+
*
|
|
11
|
+
* ## Why this one checks itself
|
|
12
|
+
*
|
|
13
|
+
* The XML version cannot know whether sibling order carries meaning in a
|
|
14
|
+
* particular document, so it offers strategies and makes the caller verify.
|
|
15
|
+
* JSON needs none of that, because JSON has no schema-dependent semantics to
|
|
16
|
+
* be wrong about:
|
|
17
|
+
*
|
|
18
|
+
* - **An object is an unordered collection of members** (RFC 8259 §4), so
|
|
19
|
+
* keeping the file's own key order is not a guess about a schema; it is what
|
|
20
|
+
* the format says. Key order is never information.
|
|
21
|
+
* - **An array is an ordered sequence** (§5), so item order always follows the
|
|
22
|
+
* update. A form's components are its components in order.
|
|
23
|
+
*
|
|
24
|
+
* That makes deep equality — insensitive to key order, sensitive to item order
|
|
25
|
+
* — an exact statement of "this says what the update says", and the patch
|
|
26
|
+
* checks itself against it before returning. No reader has to be supplied and
|
|
27
|
+
* no strategy has to be chosen.
|
|
28
|
+
*
|
|
29
|
+
* @packageDocumentation
|
|
30
|
+
*/
|
|
31
|
+
/** How a preserving write turned out. */
|
|
32
|
+
export interface PreservedJson {
|
|
33
|
+
/** The document to write. */
|
|
34
|
+
readonly json: string;
|
|
35
|
+
/**
|
|
36
|
+
* `preserved` when the file's own formatting was kept; `rewritten` when the
|
|
37
|
+
* update was used as it stands, because nothing better could be checked.
|
|
38
|
+
*/
|
|
39
|
+
readonly outcome: "preserved" | "rewritten";
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Rewrites `original` to say what `updated` says, changing as little as it can.
|
|
43
|
+
*
|
|
44
|
+
* The result is `updated`'s document written with `original`'s formatting: its
|
|
45
|
+
* indentation, its key order, its number and string spellings. A member nobody
|
|
46
|
+
* touched comes back byte for byte.
|
|
47
|
+
*
|
|
48
|
+
* The patch is checked against `updated` before it is returned — object members
|
|
49
|
+
* compared without regard to order, array items with — so a result that would
|
|
50
|
+
* say anything else is discarded in favour of `updated` itself. That is also
|
|
51
|
+
* what happens when either document will not parse. Calling this is never worse
|
|
52
|
+
* than not.
|
|
53
|
+
*
|
|
54
|
+
* @param original - The document as it stands.
|
|
55
|
+
* @param updated - The same document as the serializer would write it now.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```typescript
|
|
59
|
+
* const onDisk = await readFile("approval.form", "utf8");
|
|
60
|
+
* const { json } = preserveJsonFormatting(onDisk, Form.export(edited));
|
|
61
|
+
* // Renaming one label changes one line, whatever indentation the file uses.
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export declare function preserveJsonFormatting(original: string, updated: string): PreservedJson;
|
|
65
|
+
//# sourceMappingURL=json-patch.d.ts.map
|
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rewriting a JSON document in place, so an edit reads as an edit.
|
|
3
|
+
*
|
|
4
|
+
* The same problem [`xml-patch.ts`](../xml/xml-patch.ts) solves for XML, and
|
|
5
|
+
* mostly the same answer: take the file as it stands and the file as the
|
|
6
|
+
* serializer would write it, and return the second's content carried by the
|
|
7
|
+
* first's bytes. A form saved from a visual editor otherwise comes back with
|
|
8
|
+
* this toolkit's indentation and this toolkit's key order, and one changed
|
|
9
|
+
* label reads as a rewritten file.
|
|
10
|
+
*
|
|
11
|
+
* ## Why this one checks itself
|
|
12
|
+
*
|
|
13
|
+
* The XML version cannot know whether sibling order carries meaning in a
|
|
14
|
+
* particular document, so it offers strategies and makes the caller verify.
|
|
15
|
+
* JSON needs none of that, because JSON has no schema-dependent semantics to
|
|
16
|
+
* be wrong about:
|
|
17
|
+
*
|
|
18
|
+
* - **An object is an unordered collection of members** (RFC 8259 §4), so
|
|
19
|
+
* keeping the file's own key order is not a guess about a schema; it is what
|
|
20
|
+
* the format says. Key order is never information.
|
|
21
|
+
* - **An array is an ordered sequence** (§5), so item order always follows the
|
|
22
|
+
* update. A form's components are its components in order.
|
|
23
|
+
*
|
|
24
|
+
* That makes deep equality — insensitive to key order, sensitive to item order
|
|
25
|
+
* — an exact statement of "this says what the update says", and the patch
|
|
26
|
+
* checks itself against it before returning. No reader has to be supplied and
|
|
27
|
+
* no strategy has to be chosen.
|
|
28
|
+
*
|
|
29
|
+
* @packageDocumentation
|
|
30
|
+
*/
|
|
31
|
+
import { parseJsonSpans } from "./json-spans.js";
|
|
32
|
+
const WHITESPACE = new Set([" ", "\t", "\n", "\r"]);
|
|
33
|
+
/** Offset of the first whitespace character in the run before `offset`. */
|
|
34
|
+
function whitespaceStart(source, offset) {
|
|
35
|
+
let start = offset;
|
|
36
|
+
while (start > 0 && WHITESPACE.has(source[start - 1]))
|
|
37
|
+
start -= 1;
|
|
38
|
+
return start;
|
|
39
|
+
}
|
|
40
|
+
/** The indentation of the line `offset` sits on, when it starts that line. */
|
|
41
|
+
function indentAt(source, offset) {
|
|
42
|
+
const start = whitespaceStart(source, offset);
|
|
43
|
+
const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
|
|
44
|
+
return start <= lineStart ? source.slice(lineStart, offset) : "";
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Deep equality with JSON's own rules: members unordered, items ordered.
|
|
48
|
+
*
|
|
49
|
+
* This is the whole correctness argument. A patch that satisfies it says
|
|
50
|
+
* exactly what the update says, and one that does not is thrown away.
|
|
51
|
+
*/
|
|
52
|
+
function sameValue(a, b) {
|
|
53
|
+
if (a === b)
|
|
54
|
+
return true;
|
|
55
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
56
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
|
|
57
|
+
return false;
|
|
58
|
+
return a.every((item, index) => sameValue(item, b[index]));
|
|
59
|
+
}
|
|
60
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
|
|
61
|
+
return false;
|
|
62
|
+
const left = a;
|
|
63
|
+
const right = b;
|
|
64
|
+
const keys = Object.keys(left);
|
|
65
|
+
if (keys.length !== Object.keys(right).length)
|
|
66
|
+
return false;
|
|
67
|
+
return keys.every((key) => Object.hasOwn(right, key) && sameValue(left[key], right[key]));
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* A value written the same way however it was formatted.
|
|
71
|
+
*
|
|
72
|
+
* Used to recognise the same array item in two documents. The source text will
|
|
73
|
+
* not do: the update is indented differently by definition, so comparing what
|
|
74
|
+
* was written would find nothing in common and rewrite every array in the file.
|
|
75
|
+
*/
|
|
76
|
+
function canonical(node) {
|
|
77
|
+
if (node.kind === "object") {
|
|
78
|
+
const members = (node.members ?? [])
|
|
79
|
+
.map((member) => `${JSON.stringify(member.key)}:${canonical(member.value)}`)
|
|
80
|
+
.sort();
|
|
81
|
+
return `{${members.join(",")}}`;
|
|
82
|
+
}
|
|
83
|
+
if (node.kind === "array") {
|
|
84
|
+
return `[${(node.items ?? []).map(canonical).join(",")}]`;
|
|
85
|
+
}
|
|
86
|
+
return JSON.stringify(node.value ?? null);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* An item's identity, for lining up two versions of the same array.
|
|
90
|
+
*
|
|
91
|
+
* An `id` is the answer whenever there is one — a form component always has one
|
|
92
|
+
* — because that is what survives an edit to everything else about it. Without
|
|
93
|
+
* one the item's value stands in, so identical items pair up and a changed one
|
|
94
|
+
* is replaced where it stands.
|
|
95
|
+
*/
|
|
96
|
+
function itemKey(node) {
|
|
97
|
+
if (node.kind === "object") {
|
|
98
|
+
const id = node.members?.find((member) => member.key === "id");
|
|
99
|
+
if (id !== undefined && id.value.kind === "string")
|
|
100
|
+
return `#${String(id.value.value)}`;
|
|
101
|
+
}
|
|
102
|
+
return canonical(node);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Lines up two sequences by longest common subsequence.
|
|
106
|
+
*
|
|
107
|
+
* Returns, for each index in `a`, the index in `b` it pairs with, or -1.
|
|
108
|
+
* Array order is meaning in JSON, so this has to produce the reordering the
|
|
109
|
+
* two sequences differ by rather than patching each item where it stands.
|
|
110
|
+
*/
|
|
111
|
+
function align(a, b) {
|
|
112
|
+
const rows = a.length;
|
|
113
|
+
const columns = b.length;
|
|
114
|
+
const table = Array.from({ length: rows + 1 }, () => new Int32Array(columns + 1));
|
|
115
|
+
for (let i = rows - 1; i >= 0; i -= 1) {
|
|
116
|
+
for (let j = columns - 1; j >= 0; j -= 1) {
|
|
117
|
+
const row = table[i];
|
|
118
|
+
const next = table[i + 1];
|
|
119
|
+
row[j] =
|
|
120
|
+
a[i] === b[j]
|
|
121
|
+
? next[j + 1] + 1
|
|
122
|
+
: Math.max(next[j], row[j + 1]);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const pairing = new Array(rows).fill(-1);
|
|
126
|
+
let i = 0;
|
|
127
|
+
let j = 0;
|
|
128
|
+
while (i < rows && j < columns) {
|
|
129
|
+
if (a[i] === b[j]) {
|
|
130
|
+
pairing[i] = j;
|
|
131
|
+
i += 1;
|
|
132
|
+
j += 1;
|
|
133
|
+
}
|
|
134
|
+
else if (table[i + 1][j] >= table[i][j + 1]) {
|
|
135
|
+
i += 1;
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
j += 1;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return pairing;
|
|
142
|
+
}
|
|
143
|
+
/** How a document indents one level, read from its first indented line. */
|
|
144
|
+
function indentUnit(source) {
|
|
145
|
+
const match = /\n([ \t]+)\S/.exec(source);
|
|
146
|
+
return match?.[1] ?? " ";
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Re-indents a block written at one depth so it sits at another.
|
|
150
|
+
*
|
|
151
|
+
* By depth, not by string replacement: the two documents may not indent with
|
|
152
|
+
* the same characters at all, and a block moved from a two-space update into a
|
|
153
|
+
* tab-indented file has to have its *inner* lines converted too, or it arrives
|
|
154
|
+
* with tabs outside and spaces inside.
|
|
155
|
+
*/
|
|
156
|
+
function reindent(text, from, to, fromUnit, toUnit) {
|
|
157
|
+
if (from === to && fromUnit === toUnit)
|
|
158
|
+
return text;
|
|
159
|
+
const lines = text.split("\n");
|
|
160
|
+
return lines
|
|
161
|
+
.map((line, index) => {
|
|
162
|
+
if (index === 0)
|
|
163
|
+
return line;
|
|
164
|
+
const body = line.trimStart();
|
|
165
|
+
const indent = line.slice(0, line.length - body.length);
|
|
166
|
+
if (!indent.startsWith(from))
|
|
167
|
+
return line;
|
|
168
|
+
const deeper = indent.slice(from.length);
|
|
169
|
+
const depth = fromUnit === "" ? 0 : Math.floor(deeper.length / fromUnit.length);
|
|
170
|
+
return `${to}${toUnit.repeat(depth)}${body}`;
|
|
171
|
+
})
|
|
172
|
+
.join("\n");
|
|
173
|
+
}
|
|
174
|
+
/** The text of a value from the update, re-indented for where it is going. */
|
|
175
|
+
function transplant(updated, node, indent, original) {
|
|
176
|
+
return reindent(updated.slice(node.start, node.end), indentAt(updated, node.start), indent, indentUnit(updated), indentUnit(original));
|
|
177
|
+
}
|
|
178
|
+
function diffValue(context, a, b) {
|
|
179
|
+
if (a.kind !== b.kind) {
|
|
180
|
+
context.edits.push({
|
|
181
|
+
start: a.start,
|
|
182
|
+
end: a.end,
|
|
183
|
+
text: transplant(context.updated, b, indentAt(context.original, a.start), context.original),
|
|
184
|
+
});
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (a.kind === "object") {
|
|
188
|
+
diffObject(context, a, b);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (a.kind === "array") {
|
|
192
|
+
diffArray(context, a, b);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
// A scalar. Compare the *values*: `1.0` and `1` are the same number, and
|
|
196
|
+
// `"é"` and `"é"` are the same string. Rewriting one as the other is a
|
|
197
|
+
// diff that says nothing.
|
|
198
|
+
if (a.value === b.value)
|
|
199
|
+
return;
|
|
200
|
+
context.edits.push({
|
|
201
|
+
start: a.start,
|
|
202
|
+
end: a.end,
|
|
203
|
+
text: context.updated.slice(b.start, b.end),
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
function diffObject(context, a, b) {
|
|
207
|
+
const { original, updated, edits } = context;
|
|
208
|
+
const present = new Map((a.members ?? []).map((member) => [member.key, member]));
|
|
209
|
+
const wanted = new Map((b.members ?? []).map((member) => [member.key, member]));
|
|
210
|
+
for (const member of a.members ?? []) {
|
|
211
|
+
const match = wanted.get(member.key);
|
|
212
|
+
if (match === undefined) {
|
|
213
|
+
edits.push(removeMember(original, a, member));
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
diffValue(context, member.value, match.value);
|
|
217
|
+
}
|
|
218
|
+
const additions = (b.members ?? []).filter((member) => !present.has(member.key));
|
|
219
|
+
if (additions.length === 0)
|
|
220
|
+
return;
|
|
221
|
+
const survivors = (a.members ?? []).filter((member) => wanted.has(member.key));
|
|
222
|
+
const indent = memberIndent(original, a, survivors[0]);
|
|
223
|
+
const text = additions
|
|
224
|
+
.map((member) => `"${escapeKey(member.key)}": ${transplant(updated, member.value, indent, original)}`)
|
|
225
|
+
.join(`,\n${indent}`);
|
|
226
|
+
const last = survivors[survivors.length - 1];
|
|
227
|
+
if (last !== undefined) {
|
|
228
|
+
edits.push({ start: last.end, end: last.end, text: `,\n${indent}${text}` });
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
// The object is losing every member it had and gaining these, or was empty.
|
|
232
|
+
// Either way its whole body is written out.
|
|
233
|
+
edits.push({
|
|
234
|
+
start: a.start + 1,
|
|
235
|
+
end: a.end - 1,
|
|
236
|
+
text: `\n${indent}${text}\n${indentAt(original, a.start)}`,
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
/** Where a new member's line should start. */
|
|
240
|
+
function memberIndent(original, a, sample) {
|
|
241
|
+
if (sample !== undefined)
|
|
242
|
+
return indentAt(original, sample.start);
|
|
243
|
+
return `${indentAt(original, a.start)}${indentUnit(original)}`;
|
|
244
|
+
}
|
|
245
|
+
function escapeKey(key) {
|
|
246
|
+
// `JSON.stringify` owns the escape rules; strip the quotes it adds.
|
|
247
|
+
return JSON.stringify(key).slice(1, -1);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Removes a member, along with one comma and the whitespace that put it on its
|
|
251
|
+
* own line.
|
|
252
|
+
*
|
|
253
|
+
* The comma taken is the one *after* it, unless it is the last member, in which
|
|
254
|
+
* case the one before it goes instead — leave either behind and the document
|
|
255
|
+
* stops being JSON.
|
|
256
|
+
*/
|
|
257
|
+
function removeMember(original, owner, member) {
|
|
258
|
+
const start = whitespaceStart(original, member.start);
|
|
259
|
+
let end = member.end;
|
|
260
|
+
while (end < original.length && WHITESPACE.has(original[end]))
|
|
261
|
+
end += 1;
|
|
262
|
+
if (original[end] === ",")
|
|
263
|
+
return { start, end: end + 1, text: "" };
|
|
264
|
+
// Last one: take the comma in front instead, if there is one.
|
|
265
|
+
const before = whitespaceStart(original, member.start);
|
|
266
|
+
if (original[before - 1] === ",") {
|
|
267
|
+
return { start: before - 1, end: member.end, text: "" };
|
|
268
|
+
}
|
|
269
|
+
// The only member. The braces close on an empty body.
|
|
270
|
+
return { start: owner.start + 1, end: owner.end - 1, text: "" };
|
|
271
|
+
}
|
|
272
|
+
function diffArray(context, a, b) {
|
|
273
|
+
const { original, updated, edits } = context;
|
|
274
|
+
const items = a.items ?? [];
|
|
275
|
+
const wanted = b.items ?? [];
|
|
276
|
+
const pairing = align(items.map(itemKey), wanted.map(itemKey));
|
|
277
|
+
const matched = new Set(pairing.filter((index) => index >= 0));
|
|
278
|
+
// A wholesale change reads worse as a hundred small edits than as one
|
|
279
|
+
// replacement, and pairing nothing means there is no structure to keep.
|
|
280
|
+
if (matched.size === 0 && (items.length > 0 || wanted.length > 0)) {
|
|
281
|
+
edits.push({
|
|
282
|
+
start: a.start,
|
|
283
|
+
end: a.end,
|
|
284
|
+
text: transplant(updated, b, indentAt(original, a.start), original),
|
|
285
|
+
});
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const indent = items[0] === undefined
|
|
289
|
+
? `${indentAt(original, a.start)}${indentUnit(original)}`
|
|
290
|
+
: indentAt(original, items[0].start);
|
|
291
|
+
for (const [index, item] of items.entries()) {
|
|
292
|
+
const match = pairing[index] ?? -1;
|
|
293
|
+
if (match < 0) {
|
|
294
|
+
edits.push(removeItem(original, a, item, index, items));
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
diffValue(context, item, wanted[match]);
|
|
298
|
+
}
|
|
299
|
+
for (const [index, item] of wanted.entries()) {
|
|
300
|
+
if (matched.has(index))
|
|
301
|
+
continue;
|
|
302
|
+
const at = insertionPoint(original, items, pairing, index);
|
|
303
|
+
const text = transplant(updated, item, indent, original);
|
|
304
|
+
edits.push(at.after
|
|
305
|
+
? { start: at.offset, end: at.offset, text: `,\n${indent}${text}` }
|
|
306
|
+
: { start: at.offset, end: at.offset, text: `${text},\n${indent}` });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
/** Where a new item belongs, and whether it follows what is already there. */
|
|
310
|
+
function insertionPoint(original, items, pairing, index) {
|
|
311
|
+
for (let before = index - 1; before >= 0; before -= 1) {
|
|
312
|
+
const inA = pairing.indexOf(before);
|
|
313
|
+
if (inA >= 0)
|
|
314
|
+
return { offset: items[inA].end, after: true };
|
|
315
|
+
}
|
|
316
|
+
for (let after = index + 1; after < pairing.length + items.length; after += 1) {
|
|
317
|
+
const inA = pairing.indexOf(after);
|
|
318
|
+
if (inA >= 0)
|
|
319
|
+
return { offset: items[inA].start, after: false };
|
|
320
|
+
}
|
|
321
|
+
// Nothing kept on either side of it. Reachable only with at least one item
|
|
322
|
+
// paired — an array with none goes through the wholesale branch above — but
|
|
323
|
+
// stated rather than assumed, because being wrong here would be an exception.
|
|
324
|
+
const last = items[items.length - 1];
|
|
325
|
+
if (last === undefined)
|
|
326
|
+
return { offset: original.length, after: true };
|
|
327
|
+
return { offset: whitespaceStart(original, last.end), after: true };
|
|
328
|
+
}
|
|
329
|
+
/** Removes an array item and one comma, the same way {@link removeMember} does. */
|
|
330
|
+
function removeItem(original, owner, item, index, items) {
|
|
331
|
+
const start = whitespaceStart(original, item.start);
|
|
332
|
+
let end = item.end;
|
|
333
|
+
while (end < original.length && WHITESPACE.has(original[end]))
|
|
334
|
+
end += 1;
|
|
335
|
+
if (original[end] === ",")
|
|
336
|
+
return { start, end: end + 1, text: "" };
|
|
337
|
+
if (index > 0) {
|
|
338
|
+
const before = whitespaceStart(original, item.start);
|
|
339
|
+
if (original[before - 1] === ",")
|
|
340
|
+
return { start: before - 1, end: item.end, text: "" };
|
|
341
|
+
}
|
|
342
|
+
if (items.length === 1)
|
|
343
|
+
return { start: owner.start + 1, end: owner.end - 1, text: "" };
|
|
344
|
+
return { start, end: item.end, text: "" };
|
|
345
|
+
}
|
|
346
|
+
/** Applies edits to the source, refusing any pair that overlaps. */
|
|
347
|
+
function applyEdits(source, edits) {
|
|
348
|
+
const ordered = [...edits].sort((x, y) => x.start - y.start || x.end - y.end);
|
|
349
|
+
const parts = [];
|
|
350
|
+
let cursor = 0;
|
|
351
|
+
for (const edit of ordered) {
|
|
352
|
+
if (edit.start < cursor)
|
|
353
|
+
throw new Error("overlapping edits");
|
|
354
|
+
parts.push(source.slice(cursor, edit.start), edit.text);
|
|
355
|
+
cursor = edit.end;
|
|
356
|
+
}
|
|
357
|
+
parts.push(source.slice(cursor));
|
|
358
|
+
return parts.join("");
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Rewrites `original` to say what `updated` says, changing as little as it can.
|
|
362
|
+
*
|
|
363
|
+
* The result is `updated`'s document written with `original`'s formatting: its
|
|
364
|
+
* indentation, its key order, its number and string spellings. A member nobody
|
|
365
|
+
* touched comes back byte for byte.
|
|
366
|
+
*
|
|
367
|
+
* The patch is checked against `updated` before it is returned — object members
|
|
368
|
+
* compared without regard to order, array items with — so a result that would
|
|
369
|
+
* say anything else is discarded in favour of `updated` itself. That is also
|
|
370
|
+
* what happens when either document will not parse. Calling this is never worse
|
|
371
|
+
* than not.
|
|
372
|
+
*
|
|
373
|
+
* @param original - The document as it stands.
|
|
374
|
+
* @param updated - The same document as the serializer would write it now.
|
|
375
|
+
*
|
|
376
|
+
* @example
|
|
377
|
+
* ```typescript
|
|
378
|
+
* const onDisk = await readFile("approval.form", "utf8");
|
|
379
|
+
* const { json } = preserveJsonFormatting(onDisk, Form.export(edited));
|
|
380
|
+
* // Renaming one label changes one line, whatever indentation the file uses.
|
|
381
|
+
* ```
|
|
382
|
+
*/
|
|
383
|
+
export function preserveJsonFormatting(original, updated) {
|
|
384
|
+
const rewritten = { json: updated, outcome: "rewritten" };
|
|
385
|
+
let a;
|
|
386
|
+
let b;
|
|
387
|
+
let wanted;
|
|
388
|
+
try {
|
|
389
|
+
a = parseJsonSpans(original);
|
|
390
|
+
b = parseJsonSpans(updated);
|
|
391
|
+
wanted = JSON.parse(updated);
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
return rewritten;
|
|
395
|
+
}
|
|
396
|
+
let candidate;
|
|
397
|
+
try {
|
|
398
|
+
const edits = [];
|
|
399
|
+
diffValue({ original, updated, edits }, a, b);
|
|
400
|
+
if (edits.length === 0)
|
|
401
|
+
return { json: original, outcome: "preserved" };
|
|
402
|
+
candidate = applyEdits(original, edits);
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
return rewritten;
|
|
406
|
+
}
|
|
407
|
+
try {
|
|
408
|
+
if (!sameValue(JSON.parse(candidate), wanted))
|
|
409
|
+
return rewritten;
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
412
|
+
return rewritten;
|
|
413
|
+
}
|
|
414
|
+
return { json: candidate, outcome: "preserved" };
|
|
415
|
+
}
|
|
416
|
+
//# sourceMappingURL=json-patch.js.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A JSON document parsed into a tree that remembers where everything was.
|
|
3
|
+
*
|
|
4
|
+
* `JSON.parse` gives values with the source thrown away, which is right for
|
|
5
|
+
* everything that reads a document. Rewriting one in place needs the opposite:
|
|
6
|
+
* the exact offsets of each value and each member, so an edit can replace one
|
|
7
|
+
* string instead of regenerating the file.
|
|
8
|
+
*
|
|
9
|
+
* Deliberately not a validator. It accepts what `JSON.parse` accepts and does
|
|
10
|
+
* not try to describe what is wrong with anything else — the caller has already
|
|
11
|
+
* decided this is JSON, and a document that will not parse simply gets no tree.
|
|
12
|
+
*
|
|
13
|
+
* @packageDocumentation
|
|
14
|
+
*/
|
|
15
|
+
/** What a value is, without looking at it. */
|
|
16
|
+
export type JsonKind = "object" | "array" | "string" | "number" | "boolean" | "null";
|
|
17
|
+
/** A value, and where it was written. */
|
|
18
|
+
export interface JsonNode {
|
|
19
|
+
readonly kind: JsonKind;
|
|
20
|
+
/** The value itself, for scalars. Objects and arrays carry their parts. */
|
|
21
|
+
readonly value?: string | number | boolean | null;
|
|
22
|
+
/** Members in written order, for an object. */
|
|
23
|
+
readonly members?: JsonMember[];
|
|
24
|
+
/** Items in written order, for an array. */
|
|
25
|
+
readonly items?: JsonNode[];
|
|
26
|
+
/** Offset of the value's first character. */
|
|
27
|
+
readonly start: number;
|
|
28
|
+
/** Offset just past the value's last character. */
|
|
29
|
+
readonly end: number;
|
|
30
|
+
}
|
|
31
|
+
/** One `"key": value` pair, and where it was written. */
|
|
32
|
+
export interface JsonMember {
|
|
33
|
+
/** The key with its escapes decoded — what a comparison should use. */
|
|
34
|
+
readonly key: string;
|
|
35
|
+
readonly value: JsonNode;
|
|
36
|
+
/** Offset of the key's opening quote. */
|
|
37
|
+
readonly start: number;
|
|
38
|
+
/** Offset just past the member's value; the same as `value.end`. */
|
|
39
|
+
readonly end: number;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Parses a document into a tree that knows its own offsets.
|
|
43
|
+
*
|
|
44
|
+
* @param text - A JSON document.
|
|
45
|
+
* @throws Error when it is not one.
|
|
46
|
+
*/
|
|
47
|
+
export declare function parseJsonSpans(text: string): JsonNode;
|
|
48
|
+
//# sourceMappingURL=json-spans.d.ts.map
|