@bpmnkit/core 1.9.0 → 1.10.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.
Files changed (108) hide show
  1. package/agent-cards/bpmn.md +3 -3
  2. package/builder-reference.md +11 -9
  3. package/dist/bpmn/auto-layout.js +82 -26
  4. package/dist/bpmn/bpmn-builder.d.ts +84 -7
  5. package/dist/bpmn/bpmn-builder.js +313 -78
  6. package/dist/bpmn/bpmn-model.d.ts +2 -0
  7. package/dist/bpmn/bpmn-parser.js +68 -76
  8. package/dist/bpmn/bpmn-serializer.js +60 -19
  9. package/dist/bpmn/bpmnlint.js +4 -69
  10. package/dist/bpmn/builder-rules.d.ts +20 -0
  11. package/dist/bpmn/builder-rules.js +120 -0
  12. package/dist/bpmn/camunda-compat-data.d.ts +10 -148
  13. package/dist/bpmn/camunda-compat-data.js +16 -407
  14. package/dist/bpmn/camunda-compat-feel.d.ts +3 -0
  15. package/dist/bpmn/camunda-compat-feel.js +1 -1
  16. package/dist/bpmn/camunda-compat.js +7 -6
  17. package/dist/bpmn/camunda7/export.js +4 -1
  18. package/dist/bpmn/camunda7/juel.js +2 -1
  19. package/dist/bpmn/camunda7/migrate.d.ts +23 -0
  20. package/dist/bpmn/camunda7/migrate.js +75 -3
  21. package/dist/bpmn/compact-stream.js +2 -1
  22. package/dist/bpmn/compact.d.ts +80 -4
  23. package/dist/bpmn/compact.js +220 -38
  24. package/dist/bpmn/feel-condition.d.ts +9 -0
  25. package/dist/bpmn/feel-condition.js +19 -0
  26. package/dist/bpmn/full-operations.js +31 -4
  27. package/dist/bpmn/index.d.ts +13 -3
  28. package/dist/bpmn/index.js +16 -15
  29. package/dist/bpmn/operations.d.ts +4 -4
  30. package/dist/bpmn/operations.js +14 -2
  31. package/dist/bpmn/optimize/bpmnlint-rules.js +7 -40
  32. package/dist/bpmn/optimize/index.js +15 -1
  33. package/dist/bpmn/optimize/tasks.js +12 -3
  34. package/dist/bpmn/process-delta.d.ts +18 -0
  35. package/dist/bpmn/process-delta.js +20 -2
  36. package/dist/bpmn/process-text-writer.js +27 -1
  37. package/dist/bpmn/process-text.d.ts +9 -3
  38. package/dist/bpmn/process-text.js +122 -16
  39. package/dist/bpmn/stable-ids.d.ts +2 -0
  40. package/dist/bpmn/stable-ids.js +8 -0
  41. package/dist/bpmn/zeebe-extensions.js +2 -1
  42. package/dist/bpmn/zeebe-placement.js +6 -129
  43. package/dist/bpmn/zeebe-validate/context.d.ts +132 -0
  44. package/dist/bpmn/zeebe-validate/context.js +241 -0
  45. package/dist/bpmn/zeebe-validate/gate.d.ts +87 -0
  46. package/dist/bpmn/zeebe-validate/gate.js +492 -0
  47. package/dist/bpmn/zeebe-validate/index.d.ts +37 -0
  48. package/dist/bpmn/zeebe-validate/index.js +106 -0
  49. package/dist/bpmn/zeebe-validate/rules/events.d.ts +4 -0
  50. package/dist/bpmn/zeebe-validate/rules/events.js +580 -0
  51. package/dist/bpmn/zeebe-validate/rules/extensions.d.ts +4 -0
  52. package/dist/bpmn/zeebe-validate/rules/extensions.js +411 -0
  53. package/dist/bpmn/zeebe-validate/rules/gateways.d.ts +3 -0
  54. package/dist/bpmn/zeebe-validate/rules/gateways.js +296 -0
  55. package/dist/bpmn/zeebe-validate/rules/references.d.ts +3 -0
  56. package/dist/bpmn/zeebe-validate/rules/references.js +495 -0
  57. package/dist/bpmn/zeebe-validate/rules/structure.d.ts +3 -0
  58. package/dist/bpmn/zeebe-validate/rules/structure.js +629 -0
  59. package/dist/bpmn/zeebe-validate/rules/tasks.d.ts +4 -0
  60. package/dist/bpmn/zeebe-validate/rules/tasks.js +446 -0
  61. package/dist/bpmn/zeebe-validate/xml.d.ts +15 -0
  62. package/dist/bpmn/zeebe-validate/xml.js +1062 -0
  63. package/dist/bpmn/zeebe-validate/xsd.d.ts +19 -0
  64. package/dist/bpmn/zeebe-validate/xsd.js +350 -0
  65. package/dist/connectors/apply-element.d.ts +5 -2
  66. package/dist/connectors/apply-element.js +6 -0
  67. package/dist/connectors/apply-many.d.ts +9 -2
  68. package/dist/connectors/apply-many.js +17 -2
  69. package/dist/connectors/apply.d.ts +4 -2
  70. package/dist/connectors/deployability.d.ts +27 -0
  71. package/dist/connectors/deployability.js +41 -0
  72. package/dist/connectors/index.d.ts +1 -0
  73. package/dist/connectors/lines.d.ts +10 -0
  74. package/dist/connectors/lines.js +13 -4
  75. package/dist/dmn/dmn-model.d.ts +24 -4
  76. package/dist/dmn/dmn-parser.js +37 -3
  77. package/dist/dmn/dmn-serializer.js +48 -47
  78. package/dist/dmn/lint.js +4 -11
  79. package/dist/errors.d.ts +30 -1
  80. package/dist/errors.js +31 -0
  81. package/dist/form/form-model.d.ts +11 -0
  82. package/dist/form/form-parser.d.ts +1 -0
  83. package/dist/form/form-parser.js +48 -12
  84. package/dist/form/form-serializer.js +40 -17
  85. package/dist/form/lint.js +6 -40
  86. package/dist/generated/bpmn-elements.d.ts +5 -0
  87. package/dist/generated/bpmn-elements.js +151 -0
  88. package/dist/generated/camunda-compat-data.d.ts +148 -0
  89. package/dist/generated/camunda-compat-data.js +371 -0
  90. package/dist/generated/dmn-elements.d.ts +12 -0
  91. package/dist/generated/dmn-elements.js +45 -0
  92. package/dist/generated/form-elements.d.ts +5 -0
  93. package/dist/generated/form-elements.js +45 -0
  94. package/dist/generated/lint-rules.d.ts +17 -0
  95. package/dist/generated/lint-rules.js +116 -0
  96. package/dist/generated/zeebe-elements.d.ts +10 -0
  97. package/dist/generated/zeebe-elements.js +168 -0
  98. package/dist/generated/zeebe-rules.d.ts +25 -0
  99. package/dist/generated/zeebe-rules.js +202 -0
  100. package/dist/index.d.ts +10 -4
  101. package/dist/index.js +4 -1
  102. package/dist/layout/annotations.js +21 -1
  103. package/dist/layout/orthogonal.js +9 -3
  104. package/dist/plan/compile.d.ts +26 -1
  105. package/dist/plan/compile.js +48 -6
  106. package/dist/plan/merge.d.ts +2 -1
  107. package/dist/plan/merge.js +13 -5
  108. package/package.json +2 -2
@@ -0,0 +1,1062 @@
1
+ import { XSD_ELEMENTS, XSD_ENUMS, XSD_TYPES } from "./xsd.js";
2
+ /*
3
+ * Zeebe reads BPMN with a validating Xerces parser (BPMN20.xsd), which stops at
4
+ * the first well-formedness or schema error. This is a small strict scanner and
5
+ * XSD content-model check that reports that first error with Xerces' own text,
6
+ * so the finding reads like Zeebe's rejection. It walks the text in document
7
+ * order exactly once, as Xerces does, so "first" means the same thing.
8
+ */
9
+ const MODEL = "http://www.omg.org/spec/BPMN/20100524/MODEL";
10
+ const XSI = "http://www.w3.org/2001/XMLSchema-instance";
11
+ const XML_NS = "http://www.w3.org/XML/1998/namespace";
12
+ const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
13
+ const XSD_NS = "http://www.w3.org/2001/XMLSchema";
14
+ /** Prefixes the schema table uses for each target namespace. */
15
+ const SCHEMA_PREFIXES = [
16
+ ["", MODEL],
17
+ ["bpmndi", "http://www.omg.org/spec/BPMN/20100524/DI"],
18
+ ["di", "http://www.omg.org/spec/DD/20100524/DI"],
19
+ ["dc", "http://www.omg.org/spec/DD/20100524/DC"],
20
+ ];
21
+ /** What ZCheck prints before Xerces' message for a parse failure (zeebe-verdicts.json). */
22
+ const PARSE_PREFIX = "PARSE: SAXException while parsing input stream / ";
23
+ const SUGGESTIONS = {
24
+ "xml-schema": "Fix the XML so it is well-formed and the BPMN elements follow the schema order.",
25
+ "target-namespace": "Add a targetNamespace attribute to bpmn:definitions.",
26
+ "sequence-flow-refs": "Give the sequence flow both sourceRef and targetRef.",
27
+ "boundary-attached-ref": "Set attachedToRef to the activity the boundary event is attached to.",
28
+ "association-refs": "Give the association or message flow both sourceRef and targetRef.",
29
+ "xsd-required-name": "Add the attribute the BPMN schema requires.",
30
+ "id-ncname-unique": "Use unique ids that are valid XML names (no spaces, no leading digit).",
31
+ "idref-resolves": "Point the reference at an existing element id that is a valid XML name.",
32
+ "xsd-content": "Remove the attribute or value the BPMN schema does not allow.",
33
+ "id-present": "Give the element a non-empty id.",
34
+ };
35
+ const BUILTIN_SIMPLE = new Set([
36
+ "string",
37
+ "anyURI",
38
+ "boolean",
39
+ "integer",
40
+ "int",
41
+ "double",
42
+ "ID",
43
+ "IDREF",
44
+ "QName",
45
+ ]);
46
+ /** Pseudo-type of `di:extension`, whose anonymous type takes any foreign content. */
47
+ const EXT_TYPE = "#ext";
48
+ /** A table entry, ignoring `Object.prototype` (an element named `constructor` is not in the schema). */
49
+ function own(table, key) {
50
+ return Object.hasOwn(table, key) ? table[key] : undefined;
51
+ }
52
+ function nsOfPrefix(prefix) {
53
+ for (const [p, ns] of SCHEMA_PREFIXES)
54
+ if (p === prefix)
55
+ return ns;
56
+ return "";
57
+ }
58
+ /** A table name such as `bpmndi:BPMNShape` or `task`, split into namespace and local name. */
59
+ function schemaName(name) {
60
+ const colon = name.indexOf(":");
61
+ if (colon < 0)
62
+ return { ns: MODEL, local: name };
63
+ return { ns: nsOfPrefix(name.slice(0, colon)), local: name.slice(colon + 1) };
64
+ }
65
+ /** The table key of a namespace-qualified name, or `undefined` outside the BPMN schemas. */
66
+ function schemaKey(ns, local) {
67
+ for (const [p, uri] of SCHEMA_PREFIXES)
68
+ if (uri === ns)
69
+ return p === "" ? local : `${p}:${local}`;
70
+ return undefined;
71
+ }
72
+ /** Splits on `sep` outside parentheses and braces. */
73
+ function splitTop(text, sep) {
74
+ const out = [];
75
+ let depth = 0;
76
+ let start = 0;
77
+ for (let i = 0; i < text.length; i++) {
78
+ const ch = text[i];
79
+ if (ch === "(" || ch === "{")
80
+ depth++;
81
+ else if (ch === ")" || ch === "}")
82
+ depth--;
83
+ else if (ch === sep && depth === 0) {
84
+ out.push(text.slice(start, i));
85
+ start = i + 1;
86
+ }
87
+ }
88
+ out.push(text.slice(start));
89
+ return out;
90
+ }
91
+ /** Splits an occurrence suffix off a particle: `a*` -> `["a", 0, Infinity]`. */
92
+ function occurrence(text) {
93
+ const last = text[text.length - 1];
94
+ if (last === "?")
95
+ return [text.slice(0, -1), 0, 1];
96
+ if (last === "*")
97
+ return [text.slice(0, -1), 0, Number.POSITIVE_INFINITY];
98
+ if (last === "+")
99
+ return [text.slice(0, -1), 1, Number.POSITIVE_INFINITY];
100
+ if (last === "}") {
101
+ const open = text.lastIndexOf("{");
102
+ const [min, max] = text.slice(open + 1, -1).split(",");
103
+ return [
104
+ text.slice(0, open),
105
+ Number(min),
106
+ max === undefined || max === "" ? Number.POSITIVE_INFINITY : Number(max),
107
+ ];
108
+ }
109
+ return [text, 1, 1];
110
+ }
111
+ function parseAlt(text, typeNs) {
112
+ const [body, min, max] = occurrence(text);
113
+ if (body === "#any")
114
+ return { alt: { kind: "any", ns: "", local: "" }, min, max };
115
+ if (body === "#other")
116
+ return { alt: { kind: "other", ns: typeNs, local: "" }, min, max };
117
+ const eq = body.indexOf("=");
118
+ if (eq < 0) {
119
+ const { ns, local } = schemaName(body);
120
+ return { alt: { kind: "ref", ns, local }, min, max };
121
+ }
122
+ const { ns, local } = schemaName(body.slice(0, eq));
123
+ return { alt: { kind: "local", ns, local, type: body.slice(eq + 1) }, min, max };
124
+ }
125
+ function parseParticle(text, typeNs) {
126
+ if (!text.startsWith("(")) {
127
+ const { alt, min, max } = parseAlt(text, typeNs);
128
+ return { alts: [alt], min, max };
129
+ }
130
+ const close = text.lastIndexOf(")");
131
+ const [, min, max] = occurrence(`x${text.slice(close + 1)}`);
132
+ const alts = splitTop(text.slice(1, close), "|").map((a) => parseAlt(a, typeNs));
133
+ // A choice's occurrence bounds combine with its alternatives' (the timer choice of three optional elements may be empty).
134
+ return {
135
+ alts: alts.map((a) => a.alt),
136
+ min: min * Math.min(...alts.map((a) => a.min)),
137
+ max: max * Math.max(...alts.map((a) => a.max)),
138
+ };
139
+ }
140
+ const TYPE_CACHE = new Map();
141
+ function complexType(name) {
142
+ if (TYPE_CACHE.has(name))
143
+ return TYPE_CACHE.get(name);
144
+ const spec = own(XSD_TYPES, name);
145
+ let result;
146
+ if (spec !== undefined) {
147
+ const [base = "", particles = "", attrs = "", flags = ""] = splitTop(spec, "|");
148
+ const ns = schemaName(name).ns;
149
+ const parent = base === "" ? undefined : complexType(base);
150
+ const own = particles === "" ? [] : splitTop(particles, ",").map((p) => parseParticle(p, ns));
151
+ const ownAttrs = attrs === ""
152
+ ? []
153
+ : attrs.split(",").map((a) => {
154
+ const eq = a.indexOf("=");
155
+ const required = a.endsWith("!");
156
+ return {
157
+ name: a.slice(0, eq),
158
+ type: a.slice(eq + 1, required ? -1 : undefined),
159
+ required,
160
+ };
161
+ });
162
+ // Xerces lists a derived type's own attributes before the inherited ones.
163
+ const inherited = (parent?.attrs ?? []).filter((a) => !ownAttrs.some((o) => o.name === a.name));
164
+ result = {
165
+ name,
166
+ ns,
167
+ particles: [...(parent?.particles ?? []), ...own],
168
+ attrs: [...ownAttrs, ...inherited],
169
+ anyAttr: flags.includes("@") || (parent?.anyAttr ?? false),
170
+ mixed: flags.includes("~") || (own.length === 0 && (parent?.mixed ?? false)),
171
+ abstract: flags.includes("!"),
172
+ };
173
+ }
174
+ TYPE_CACHE.set(name, result);
175
+ return result;
176
+ }
177
+ function isSimpleType(name) {
178
+ return BUILTIN_SIMPLE.has(name) || own(XSD_ENUMS, name) !== undefined;
179
+ }
180
+ /** A global element's type and substitution head. */
181
+ function globalElement(key) {
182
+ const spec = own(XSD_ELEMENTS, key);
183
+ if (spec === undefined)
184
+ return undefined;
185
+ const slash = spec.indexOf("/");
186
+ return slash < 0 ? { type: spec } : { type: spec.slice(0, slash), head: spec.slice(slash + 1) };
187
+ }
188
+ /** Whether a type is, or derives from, `ancestor`. */
189
+ function derivesFrom(type, ancestor) {
190
+ let current = type;
191
+ for (let guard = 0; current !== undefined && guard < 32; guard++) {
192
+ if (current === ancestor)
193
+ return true;
194
+ const spec = own(XSD_TYPES, current);
195
+ const base = spec === undefined ? "" : (splitTop(spec, "|")[0] ?? "");
196
+ current = base === "" ? undefined : base;
197
+ }
198
+ return false;
199
+ }
200
+ function altLabel(alt) {
201
+ if (alt.kind === "any")
202
+ return "WC[##any]";
203
+ if (alt.kind === "other")
204
+ return `WC[##other:"${alt.ns}"]`;
205
+ return `"${alt.ns}":${alt.local}`;
206
+ }
207
+ /** Xerces' rendering of an element in "Invalid content" messages. */
208
+ function expandedName(ns, local) {
209
+ return ns === "" ? local : `{"${ns}":${local}}`;
210
+ }
211
+ // ---------------------------------------------------------------------------
212
+ // Lexical checks
213
+ // ---------------------------------------------------------------------------
214
+ function isNameStart(cp) {
215
+ return ((cp >= 0x61 && cp <= 0x7a) ||
216
+ (cp >= 0x41 && cp <= 0x5a) ||
217
+ cp === 0x5f ||
218
+ (cp >= 0xc0 && cp <= 0xd6) ||
219
+ (cp >= 0xd8 && cp <= 0xf6) ||
220
+ (cp >= 0xf8 && cp <= 0x2ff) ||
221
+ (cp >= 0x370 && cp <= 0x37d) ||
222
+ (cp >= 0x37f && cp <= 0x1fff) ||
223
+ (cp >= 0x200c && cp <= 0x200d) ||
224
+ (cp >= 0x2070 && cp <= 0x218f) ||
225
+ (cp >= 0x2c00 && cp <= 0x2fef) ||
226
+ (cp >= 0x3001 && cp <= 0xd7ff) ||
227
+ (cp >= 0xf900 && cp <= 0xfdcf) ||
228
+ (cp >= 0xfdf0 && cp <= 0xfffd) ||
229
+ (cp >= 0x10000 && cp <= 0xeffff));
230
+ }
231
+ function isNameChar(cp) {
232
+ return (isNameStart(cp) ||
233
+ cp === 0x2d ||
234
+ cp === 0x2e ||
235
+ (cp >= 0x30 && cp <= 0x39) ||
236
+ cp === 0xb7 ||
237
+ (cp >= 0x300 && cp <= 0x36f) ||
238
+ (cp >= 0x203f && cp <= 0x2040));
239
+ }
240
+ function isNcName(text) {
241
+ if (text === "")
242
+ return false;
243
+ let first = true;
244
+ for (const ch of text) {
245
+ const cp = ch.codePointAt(0) ?? 0;
246
+ if (first ? !isNameStart(cp) : !isNameChar(cp))
247
+ return false;
248
+ first = false;
249
+ }
250
+ return true;
251
+ }
252
+ function isQName(text) {
253
+ const colon = text.indexOf(":");
254
+ if (colon < 0)
255
+ return isNcName(text);
256
+ return isNcName(text.slice(0, colon)) && isNcName(text.slice(colon + 1));
257
+ }
258
+ /** XSD whitespace collapse (`xsd:token` and every non-string built-in). */
259
+ function collapse(text) {
260
+ return text.replace(/[ \t\n\r]+/g, " ").replace(/^ | $/g, "");
261
+ }
262
+ function isXmlWhitespace(text) {
263
+ return /^[ \t\n\r]*$/.test(text);
264
+ }
265
+ function isXmlChar(cp) {
266
+ return (cp === 0x9 ||
267
+ cp === 0xa ||
268
+ cp === 0xd ||
269
+ (cp >= 0x20 && cp <= 0xd7ff) ||
270
+ (cp >= 0xe000 && cp <= 0xfffd) ||
271
+ (cp >= 0x10000 && cp <= 0x10ffff));
272
+ }
273
+ const DOUBLE = /^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$|^(-?INF|NaN)$/;
274
+ // ---------------------------------------------------------------------------
275
+ // Scanner and validator
276
+ // ---------------------------------------------------------------------------
277
+ /** The first error, in Zeebe's words. */
278
+ class XmlFailure {
279
+ rule;
280
+ message;
281
+ constructor(rule, message) {
282
+ this.rule = rule;
283
+ this.message = message;
284
+ }
285
+ }
286
+ const Mode = { Skip: 0, Complex: 1, Simple: 2 };
287
+ const PREDEFINED = {
288
+ lt: "<",
289
+ gt: ">",
290
+ amp: "&",
291
+ quot: '"',
292
+ apos: "'",
293
+ };
294
+ /** Types whose elements Zeebe requires an id on (`IdentifiableBpmnElementValidator`). */
295
+ const ID_REQUIRED_TYPES = ["tFlowElement", "tProcess", "tMessage", "tSignal", "tEscalation"];
296
+ class XmlChecker {
297
+ s;
298
+ i = 0;
299
+ lineStarts = [0];
300
+ stack = [];
301
+ ids = new Set();
302
+ idrefs = [];
303
+ /** Elements without the id Zeebe requires, by the id Zeebe would name them under. */
304
+ missingIds = [];
305
+ /** The element each id names (the first one), as Zeebe's `getModelElementById` finds it. */
306
+ elementsById = new Map();
307
+ flowNodes = [];
308
+ flowSources = new Set();
309
+ constructor(s) {
310
+ this.s = s;
311
+ for (let k = 0; k < s.length; k++) {
312
+ const ch = s.charCodeAt(k);
313
+ if (ch === 0x0a)
314
+ this.lineStarts.push(k + 1);
315
+ else if (ch === 0x0d && s.charCodeAt(k + 1) !== 0x0a)
316
+ this.lineStarts.push(k + 1);
317
+ }
318
+ }
319
+ line(pos) {
320
+ let lo = 0;
321
+ let hi = this.lineStarts.length - 1;
322
+ while (lo < hi) {
323
+ const mid = (lo + hi + 1) >> 1;
324
+ if ((this.lineStarts[mid] ?? 0) <= pos)
325
+ lo = mid;
326
+ else
327
+ hi = mid - 1;
328
+ }
329
+ return lo + 1;
330
+ }
331
+ fatal(text, pos = this.i, rule = "xml-schema") {
332
+ return new XmlFailure(rule, `${PARSE_PREFIX}Fatal Error: URI=null Line=${this.line(pos)}: ${text}`);
333
+ }
334
+ error(rule, text, pos) {
335
+ return new XmlFailure(rule, `${PARSE_PREFIX}Error: URI=null Line=${this.line(pos)}: ${text}`);
336
+ }
337
+ startsWith(text) {
338
+ return this.s.startsWith(text, this.i);
339
+ }
340
+ skipWs() {
341
+ const start = this.i;
342
+ while (this.i < this.s.length && /[ \t\n\r]/.test(this.s[this.i] ?? ""))
343
+ this.i++;
344
+ return this.i > start;
345
+ }
346
+ readName() {
347
+ const start = this.i;
348
+ const first = this.s.codePointAt(this.i) ?? -1;
349
+ if (!isNameStart(first) && first !== 0x3a)
350
+ return undefined;
351
+ this.i += first > 0xffff ? 2 : 1;
352
+ while (this.i < this.s.length) {
353
+ const cp = this.s.codePointAt(this.i) ?? -1;
354
+ if (!isNameChar(cp) && cp !== 0x3a)
355
+ break;
356
+ this.i += cp > 0xffff ? 2 : 1;
357
+ }
358
+ return this.s.slice(start, this.i);
359
+ }
360
+ /** Reads a reference at `&` and returns its replacement text. */
361
+ readReference() {
362
+ this.i++;
363
+ if (this.s[this.i] === "#") {
364
+ this.i++;
365
+ const hex = this.s[this.i] === "x";
366
+ if (hex)
367
+ this.i++;
368
+ const start = this.i;
369
+ while (this.i < this.s.length && /[0-9a-fA-F]/.test(this.s[this.i] ?? ""))
370
+ this.i++;
371
+ const digits = this.s.slice(start, this.i);
372
+ if (digits === "" || (!hex && /[a-fA-F]/.test(digits)))
373
+ throw this.fatal(hex
374
+ ? 'A hexadecimal representation must immediately follow the "&#x" in a character reference.'
375
+ : 'A decimal representation must immediately follow the "&#" in a character reference.');
376
+ if (this.s[this.i] !== ";")
377
+ throw this.fatal("The character reference must end with the ';' delimiter.");
378
+ this.i++;
379
+ const cp = Number.parseInt(digits, hex ? 16 : 10);
380
+ if (!isXmlChar(cp))
381
+ throw this.fatal(`Character reference "&#${hex ? "x" : ""}${digits}" is an invalid XML character.`);
382
+ return String.fromCodePoint(cp);
383
+ }
384
+ const name = this.readName();
385
+ if (name === undefined)
386
+ throw this.fatal("The entity name must immediately follow the '&' in the entity reference.");
387
+ if (this.s[this.i] !== ";")
388
+ throw this.fatal(`The reference to entity "${name}" must end with the ';' delimiter.`);
389
+ this.i++;
390
+ const value = own(PREDEFINED, name);
391
+ if (value === undefined)
392
+ throw this.fatal(`The entity "${name}" was referenced, but not declared.`);
393
+ return value;
394
+ }
395
+ skipComment() {
396
+ const end = this.s.indexOf("-->", this.i + 4);
397
+ if (end < 0)
398
+ throw this.fatal("XML document structures must start and end within the same entity.", this.s.length);
399
+ const dashes = this.s.indexOf("--", this.i + 4);
400
+ if (dashes < end)
401
+ throw this.fatal('The string "--" is not permitted within comments.', dashes);
402
+ this.i = end + 3;
403
+ }
404
+ skipPi() {
405
+ const target = /^<\?([^\s?]*)/.exec(this.s.slice(this.i, this.i + 64))?.[1] ?? "";
406
+ if (target.toLowerCase() === "xml")
407
+ throw this.fatal('The processing instruction target matching "[xX][mM][lL]" is not allowed.');
408
+ const end = this.s.indexOf("?>", this.i + 2);
409
+ if (end < 0)
410
+ throw this.fatal("XML document structures must start and end within the same entity.", this.s.length);
411
+ this.i = end + 2;
412
+ }
413
+ /** Misc before or after the root: whitespace, comments and processing instructions. */
414
+ skipMisc() {
415
+ for (;;) {
416
+ this.skipWs();
417
+ if (this.startsWith("<!--"))
418
+ this.skipComment();
419
+ else if (this.startsWith("<?"))
420
+ this.skipPi();
421
+ else
422
+ return;
423
+ }
424
+ }
425
+ run() {
426
+ if (this.s.charCodeAt(0) === 0xfeff)
427
+ this.i = 1;
428
+ if (this.startsWith("<?xml") && /[ \t\n\r?]/.test(this.s[this.i + 5] ?? "")) {
429
+ const end = this.s.indexOf("?>", this.i);
430
+ if (end < 0)
431
+ throw this.fatal("XML document structures must start and end within the same entity.", this.s.length);
432
+ const encoding = /\bencoding\s*=\s*(["'])(.*?)\1/.exec(this.s.slice(this.i, end))?.[2];
433
+ if (encoding !== undefined && !/^[A-Za-z][A-Za-z0-9._-]*$/.test(encoding))
434
+ throw this.fatal(`Invalid encoding name "${encoding}".`);
435
+ this.i = end + 2;
436
+ }
437
+ this.skipMisc();
438
+ if (this.i >= this.s.length)
439
+ throw this.fatal("Premature end of file.");
440
+ if (this.startsWith("<!DOCTYPE"))
441
+ throw this.fatal('DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.');
442
+ if (this.s[this.i] !== "<")
443
+ throw this.fatal("Content is not allowed in prolog.");
444
+ this.startTag();
445
+ while (this.stack.length > 0)
446
+ this.content();
447
+ this.skipMisc();
448
+ if (this.i < this.s.length) {
449
+ if (this.s[this.i] === "<")
450
+ throw this.fatal("The markup in the document following the root element must be well-formed.");
451
+ throw this.fatal("Content is not allowed in trailing section.");
452
+ }
453
+ }
454
+ content() {
455
+ if (this.i >= this.s.length)
456
+ throw this.fatal("XML document structures must start and end within the same entity.");
457
+ if (this.s[this.i] !== "<") {
458
+ this.text();
459
+ return;
460
+ }
461
+ if (this.startsWith("</"))
462
+ this.endTag();
463
+ else if (this.startsWith("<!--"))
464
+ this.skipComment();
465
+ else if (this.startsWith("<![CDATA[")) {
466
+ const end = this.s.indexOf("]]>", this.i + 9);
467
+ if (end < 0)
468
+ throw this.fatal("XML document structures must start and end within the same entity.", this.s.length);
469
+ this.onText(this.s.slice(this.i + 9, end));
470
+ this.i = end + 3;
471
+ }
472
+ else if (this.startsWith("<?"))
473
+ this.skipPi();
474
+ else
475
+ this.startTag();
476
+ }
477
+ text() {
478
+ let out = "";
479
+ while (this.i < this.s.length && this.s[this.i] !== "<") {
480
+ const ch = this.s[this.i] ?? "";
481
+ if (ch === "&") {
482
+ out += this.readReference();
483
+ continue;
484
+ }
485
+ if (ch === "]" && this.startsWith("]]>"))
486
+ throw this.fatal('The character sequence "]]>" must not appear in content unless used to mark the end of a CDATA section.');
487
+ const cp = this.s.codePointAt(this.i) ?? 0;
488
+ if (!isXmlChar(cp))
489
+ throw this.fatal(`An invalid XML character (Unicode: 0x${cp.toString(16)}) was found in the element content of the document.`);
490
+ const width = cp > 0xffff ? 2 : 1;
491
+ out += this.s.slice(this.i, this.i + width);
492
+ this.i += width;
493
+ }
494
+ this.onText(out);
495
+ }
496
+ onText(text) {
497
+ const top = this.stack[this.stack.length - 1];
498
+ if (top === undefined || top.mode === Mode.Skip)
499
+ return;
500
+ top.text += text;
501
+ if (!isXmlWhitespace(text))
502
+ top.sawText = true;
503
+ }
504
+ startTag() {
505
+ this.i++;
506
+ const raw = this.readName();
507
+ if (raw === undefined)
508
+ throw this.fatal(this.stack.length === 0
509
+ ? "The markup in the document preceding the root element must be well-formed."
510
+ : "The content of elements must consist of well-formed character data or markup.");
511
+ const attrs = [];
512
+ let selfClose = false;
513
+ const eof = () => {
514
+ if (this.i >= this.s.length)
515
+ throw this.fatal("XML document structures must start and end within the same entity.");
516
+ };
517
+ for (;;) {
518
+ const ws = this.skipWs();
519
+ eof();
520
+ if (this.s[this.i] === ">") {
521
+ this.i++;
522
+ break;
523
+ }
524
+ if (this.startsWith("/>")) {
525
+ this.i += 2;
526
+ selfClose = true;
527
+ break;
528
+ }
529
+ const name = ws ? this.readName() : undefined;
530
+ eof();
531
+ if (name === undefined)
532
+ throw this.fatal(`Element type "${raw}" must be followed by either attribute specifications, ">" or "/>".`);
533
+ this.skipWs();
534
+ eof();
535
+ if (this.s[this.i] !== "=")
536
+ throw this.fatal(`Attribute name "${name}" associated with an element type "${raw}" must be followed by the ' = ' character.`);
537
+ this.i++;
538
+ this.skipWs();
539
+ eof();
540
+ const quote = this.s[this.i];
541
+ if (quote !== '"' && quote !== "'")
542
+ throw this.fatal(`Open quote is expected for attribute "${name}" associated with an element type "${raw}".`);
543
+ this.i++;
544
+ let value = "";
545
+ for (;;) {
546
+ if (this.i >= this.s.length)
547
+ throw this.fatal("XML document structures must start and end within the same entity.");
548
+ const ch = this.s[this.i] ?? "";
549
+ if (ch === quote) {
550
+ this.i++;
551
+ break;
552
+ }
553
+ if (ch === "<")
554
+ throw this.fatal(`The value of attribute "${name}" associated with an element type "${raw}" must not contain the '<' character.`);
555
+ if (ch === "&") {
556
+ value += this.readReference();
557
+ continue;
558
+ }
559
+ const cp = this.s.codePointAt(this.i) ?? 0;
560
+ if (!isXmlChar(cp))
561
+ throw this.fatal(`An invalid XML character (Unicode: 0x${cp.toString(16)}) was found in the value of attribute "${name}" and element is "${raw}".`);
562
+ // Attribute-value normalization: line breaks and tabs become spaces.
563
+ if (ch === "\r" && this.s[this.i + 1] === "\n")
564
+ this.i++;
565
+ const width = cp > 0xffff ? 2 : 1;
566
+ value +=
567
+ ch === "\t" || ch === "\n" || ch === "\r" ? " " : this.s.slice(this.i, this.i + width);
568
+ this.i += width;
569
+ }
570
+ if (attrs.some((a) => a.raw === name))
571
+ throw this.fatal(`Attribute "${name}" was already specified for element "${raw}".`);
572
+ attrs.push({ raw: name, value });
573
+ }
574
+ const endPos = this.i - 1;
575
+ const parent = this.stack[this.stack.length - 1];
576
+ const nsMap = this.namespaces(attrs, parent?.nsMap);
577
+ const [prefix, local] = splitQName(raw);
578
+ const ns = prefix === "" ? (nsMap.get("") ?? "") : this.resolvePrefix(nsMap, prefix);
579
+ if (ns === undefined)
580
+ throw this.fatal(`The prefix "${prefix}" for element "${raw}" is not bound.`, endPos);
581
+ const resolved = [];
582
+ for (const a of attrs) {
583
+ if (a.raw === "xmlns" || a.raw.startsWith("xmlns:"))
584
+ continue;
585
+ const [ap, al] = splitQName(a.raw);
586
+ const ans = ap === "" ? "" : this.resolvePrefix(nsMap, ap);
587
+ if (ans === undefined)
588
+ throw this.fatal(`The prefix "${ap}" for attribute "${a.raw}" associated with an element type "${raw}" is not bound.`, endPos);
589
+ resolved.push({ raw: a.raw, prefix: ap, local: al, ns: ans, value: a.value });
590
+ }
591
+ const idAttr = resolved.find((a) => a.ns === "" && a.local === "id");
592
+ const frame = {
593
+ raw,
594
+ ns,
595
+ local,
596
+ nsMap,
597
+ mode: Mode.Skip,
598
+ pi: -1,
599
+ pc: 0,
600
+ text: "",
601
+ sawText: false,
602
+ sawChild: false,
603
+ ownerId: idAttr !== undefined && idAttr.value !== "" ? idAttr.value : (parent?.ownerId ?? ""),
604
+ skipped: (parent?.skipped ?? false) ||
605
+ (ns === MODEL &&
606
+ local === "process" &&
607
+ resolved.find((a) => a.ns === "" && a.local === "isExecutable")?.value.toLowerCase() !==
608
+ "true"),
609
+ path: parent === undefined ? [0] : [...parent.path, parent.children++],
610
+ children: 0,
611
+ };
612
+ if (idAttr !== undefined && !this.elementsById.has(idAttr.value))
613
+ this.elementsById.set(idAttr.value, { ns, local });
614
+ this.validateStart(frame, parent, resolved, endPos);
615
+ this.collectRefs(frame, resolved);
616
+ this.stack.push(frame);
617
+ if (selfClose)
618
+ this.finish(endPos);
619
+ }
620
+ endTag() {
621
+ this.i += 2;
622
+ const top = this.stack[this.stack.length - 1];
623
+ if (top === undefined)
624
+ return;
625
+ // Like Xerces, match the open element's name first, then require the '>'.
626
+ if (!this.startsWith(top.raw))
627
+ throw this.fatal(`The element type "${top.raw}" must be terminated by the matching end-tag "</${top.raw}>".`);
628
+ this.i += top.raw.length;
629
+ this.skipWs();
630
+ if (this.s[this.i] !== ">")
631
+ throw this.fatal(`The end-tag for element type "${top.raw}" must end with a '>' delimiter.`);
632
+ this.i++;
633
+ this.finish(this.i - 1);
634
+ }
635
+ resolvePrefix(nsMap, prefix) {
636
+ if (prefix === "xml")
637
+ return XML_NS;
638
+ if (prefix === "xmlns")
639
+ return XMLNS_NS;
640
+ const uri = nsMap.get(prefix);
641
+ return uri === "" ? undefined : uri;
642
+ }
643
+ namespaces(attrs, inherited) {
644
+ const decls = attrs.filter((a) => a.raw === "xmlns" || a.raw.startsWith("xmlns:"));
645
+ if (decls.length === 0 && inherited !== undefined)
646
+ return inherited;
647
+ const map = new Map(inherited ?? []);
648
+ for (const d of decls)
649
+ map.set(d.raw === "xmlns" ? "" : d.raw.slice(6), d.value);
650
+ return map;
651
+ }
652
+ collectRefs(frame, attrs) {
653
+ if (frame.skipped || frame.ns !== MODEL || frame.ct === undefined)
654
+ return;
655
+ const attr = (name) => attrs.find((a) => a.ns === "" && a.local === name)?.value;
656
+ if (frame.local === "sequenceFlow") {
657
+ const source = attr("sourceRef");
658
+ if (source !== undefined)
659
+ this.flowSources.add(collapse(source));
660
+ }
661
+ if (!derivesFrom(frame.ct.name, "tFlowNode"))
662
+ return;
663
+ frame.node = {
664
+ local: frame.local,
665
+ path: frame.path,
666
+ outgoing: [],
667
+ incoming: [],
668
+ gateway: frame.local === "exclusiveGateway" || frame.local === "inclusiveGateway",
669
+ id: attr("id"),
670
+ resolvesIncoming: frame.local === "boundaryEvent" ||
671
+ (derivesFrom(frame.ct.name, "tTask") &&
672
+ attr("isForCompensation")?.toLowerCase() === "true"),
673
+ };
674
+ this.flowNodes.push(frame.node);
675
+ }
676
+ /**
677
+ * The exception Zeebe's validators throw resolving a flow node's `outgoing`
678
+ * (or a boundary event's `incoming`) to a sequence flow, for the first node in
679
+ * Zeebe's walk order: parents first, then children from the last to the first.
680
+ */
681
+ referenceFailure() {
682
+ const nodes = [...this.flowNodes].sort((a, b) => walkOrder(a.path, b.path));
683
+ for (const node of nodes) {
684
+ const refs = [
685
+ ...(node.gateway && !(node.id !== undefined && this.flowSources.has(node.id))
686
+ ? []
687
+ : node.outgoing),
688
+ ...(node.resolvesIncoming ? node.incoming : []),
689
+ ];
690
+ for (const ref of refs) {
691
+ const text = ref.trim();
692
+ const id = text.slice(text.indexOf(":") + 1);
693
+ const target = this.elementsById.get(id);
694
+ if (target === undefined)
695
+ return `PARSE: Unable to find a model element instance for id ${id}`;
696
+ if (target.ns === MODEL && target.local !== "sequenceFlow") {
697
+ const impl = `io.camunda.zeebe.model.bpmn.impl.instance.${target.local.charAt(0).toUpperCase()}${target.local.slice(1)}Impl`;
698
+ return `PARSE: class ${impl} cannot be cast to class io.camunda.zeebe.model.bpmn.instance.SequenceFlow`;
699
+ }
700
+ }
701
+ }
702
+ return undefined;
703
+ }
704
+ // -- schema validation ----------------------------------------------------
705
+ validateStart(frame, parent, attrs, pos) {
706
+ let typeName;
707
+ if (parent === undefined) {
708
+ const key = schemaKey(frame.ns, frame.local);
709
+ const decl = key === undefined ? undefined : globalElement(key);
710
+ if (decl === undefined)
711
+ throw this.error("xml-schema", `cvc-elt.1.a: Cannot find the declaration of element '${frame.raw}'.`, pos);
712
+ typeName = decl.type;
713
+ }
714
+ else {
715
+ if (parent.mode === Mode.Skip)
716
+ return;
717
+ // Xerces reports children of simple or empty content at the parent's end tag.
718
+ if (parent.mode === Mode.Simple || parent.ct?.particles.length === 0) {
719
+ parent.sawChild = true;
720
+ // Without a content model to place it, Xerces still validates a child by its global declaration.
721
+ const key = schemaKey(frame.ns, frame.local);
722
+ const decl = key === undefined ? undefined : globalElement(key);
723
+ if (decl === undefined)
724
+ return;
725
+ typeName = decl.type;
726
+ }
727
+ else {
728
+ const matched = this.step(parent, frame, pos);
729
+ if (matched === undefined)
730
+ return;
731
+ typeName = matched;
732
+ }
733
+ }
734
+ if (typeName === EXT_TYPE)
735
+ return;
736
+ const xsiType = attrs.find((a) => a.ns === XSI && a.local === "type");
737
+ if (xsiType !== undefined) {
738
+ const declared = typeName;
739
+ typeName = this.xsiType(frame, xsiType.value, pos);
740
+ if (typeName !== declared && !derivesFrom(typeName, declared))
741
+ throw this.error("xml-schema", `cvc-elt.4.3: Type '${collapse(xsiType.value)}' is not validly derived from the type definition, '${schemaName(declared).local}', of element '${frame.raw}'.`, pos);
742
+ }
743
+ if (isSimpleType(typeName)) {
744
+ frame.mode = Mode.Simple;
745
+ frame.simple = typeName;
746
+ const extra = attrs.find((a) => a.ns !== XSI);
747
+ if (extra !== undefined)
748
+ throw this.error("xsd-content", `cvc-type.3.1.1: Element '${frame.raw}' is a simple type, so it cannot have attributes, excepting those whose namespace name is identical to '${XSI}' and whose [local name] is one of 'type', 'nil', 'schemaLocation' or 'noNamespaceSchemaLocation'. However, the attribute, '${extra.raw}' was found.`, pos);
749
+ return;
750
+ }
751
+ const ct = complexType(typeName);
752
+ if (ct === undefined)
753
+ return;
754
+ if (ct.abstract)
755
+ throw this.error("xml-schema", `cvc-type.2: The type definition cannot be abstract for element ${frame.raw}.`, pos);
756
+ frame.mode = Mode.Complex;
757
+ frame.ct = ct;
758
+ for (const a of attrs) {
759
+ if (a.ns === XSI)
760
+ continue;
761
+ const decl = a.ns === "" ? ct.attrs.find((d) => d.name === a.local) : undefined;
762
+ if (decl === undefined) {
763
+ if (a.ns !== "" && ct.anyAttr && a.ns !== ct.ns)
764
+ continue;
765
+ throw this.error("xsd-content", `cvc-complex-type.3.2.2: Attribute '${a.raw}' is not allowed to appear in element '${frame.raw}'.`, pos);
766
+ }
767
+ const failure = this.value(decl.type, a.value, frame.nsMap);
768
+ if (failure !== undefined)
769
+ throw this.error(failure[0], failure[1], pos);
770
+ }
771
+ for (const d of ct.attrs) {
772
+ if (!d.required || attrs.some((a) => a.ns === "" && a.local === d.name))
773
+ continue;
774
+ throw this.error(missingAttributeRule(frame.local, d.name), `cvc-complex-type.4: Attribute '${d.name}' must appear on element '${frame.raw}'.`, pos);
775
+ }
776
+ if (!frame.skipped &&
777
+ frame.ns === MODEL &&
778
+ !attrs.some((a) => a.ns === "" && a.local === "id") &&
779
+ ID_REQUIRED_TYPES.some((t) => derivesFrom(typeName, t)))
780
+ this.missingIds.push(parent?.ownerId ?? "");
781
+ }
782
+ xsiType(frame, raw, pos) {
783
+ const value = collapse(raw);
784
+ if (!isQName(value))
785
+ throw this.error("xml-schema", `cvc-elt.4.1: The value '${value}' of attribute '${XSI},type' of element '${frame.raw}' is not a valid QName.`, pos);
786
+ const [prefix, local] = splitQName(value);
787
+ const ns = prefix === "" ? (frame.nsMap.get("") ?? "") : this.resolvePrefix(frame.nsMap, prefix);
788
+ if (ns === XSD_NS && BUILTIN_SIMPLE.has(local))
789
+ return local;
790
+ const key = ns === undefined ? undefined : schemaKey(ns, local);
791
+ if (key === undefined || (own(XSD_TYPES, key) === undefined && !isSimpleType(key)))
792
+ throw this.error("xml-schema", `cvc-elt.4.2: Cannot resolve '${value}' to a type definition for element '${frame.raw}'.`, pos);
793
+ return key;
794
+ }
795
+ /** Matches a child against the parent's content model; the child's type, or `undefined` for wildcard content. */
796
+ step(parent, child, pos) {
797
+ const ct = parent.ct;
798
+ if (ct === undefined)
799
+ return undefined;
800
+ const ps = ct.particles;
801
+ const current = ps[parent.pi];
802
+ if (current !== undefined && parent.pc < current.max) {
803
+ const t = matchParticle(current, child);
804
+ if (t !== null) {
805
+ parent.pc++;
806
+ return t;
807
+ }
808
+ }
809
+ if (current === undefined || parent.pc >= current.min) {
810
+ for (let j = parent.pi + 1; j < ps.length; j++) {
811
+ const p = ps[j];
812
+ if (p === undefined)
813
+ break;
814
+ const t = matchParticle(p, child);
815
+ if (t !== null) {
816
+ parent.pi = j;
817
+ parent.pc = 1;
818
+ return t;
819
+ }
820
+ if (p.min > 0)
821
+ break;
822
+ }
823
+ }
824
+ const short = shortBy(current, parent.pc);
825
+ if (current !== undefined && short !== undefined)
826
+ throw this.error("xml-schema", `cvc-complex-type.2.4.${short === 1 ? "g" : "h"}: Invalid content was found starting with element '${child.raw}'. ${minimumMessage(current, short, " in the current sequence")}`, pos);
827
+ const expected = expectedAt(ps, parent.pi, parent.pc);
828
+ if (expected.length === 0)
829
+ throw this.error("xml-schema", `cvc-complex-type.2.4.d: Invalid content was found starting with element '${child.raw}'. No child element is expected at this point.`, pos);
830
+ throw this.error(isDeclared(child) ? "xml-schema" : "xsd-content", `cvc-complex-type.2.4.a: Invalid content was found starting with element '${expandedName(child.ns, child.local)}'. One of '{${expected.join(", ")}}' is expected.`, pos);
831
+ }
832
+ /** End of an element: content-model completion, simple content, and the document's IDREFs at the root. */
833
+ finish(pos) {
834
+ const frame = this.stack.pop();
835
+ if (frame === undefined)
836
+ return;
837
+ if (frame.mode === Mode.Complex && frame.ct !== undefined) {
838
+ const ct = frame.ct;
839
+ if ((frame.sawText && !ct.mixed) || frame.sawChild)
840
+ throw this.error("xml-schema", ct.particles.length === 0
841
+ ? `cvc-complex-type.2.1: Element '${frame.raw}' must have no character or element information item [children], because the type's content type is empty.`
842
+ : `cvc-complex-type.2.3: Element '${frame.raw}' cannot have character [children], because the type's content type is element-only.`, pos);
843
+ const current = ct.particles[frame.pi];
844
+ const short = shortBy(current, frame.pc);
845
+ if (current !== undefined && short !== undefined)
846
+ throw this.error("xml-schema", `cvc-complex-type.2.4.${short === 1 ? "i" : "j"}: The content of element '${frame.raw}' is not complete. ${minimumMessage(current, short, "")}`, pos);
847
+ if (!isComplete(ct.particles, frame.pi, frame.pc))
848
+ throw this.error("xml-schema", `cvc-complex-type.2.4.b: The content of element '${frame.raw}' is not complete. One of '{${expectedAt(ct.particles, frame.pi, frame.pc).join(", ")}}' is expected.`, pos);
849
+ }
850
+ else if (frame.mode === Mode.Simple && frame.simple !== undefined) {
851
+ if (frame.sawChild)
852
+ throw this.error("xml-schema", `cvc-type.3.1.2: Element '${frame.raw}' is a simple type, so it must have no element information item [children].`, pos);
853
+ const failure = this.value(frame.simple, frame.text, frame.nsMap);
854
+ if (failure !== undefined)
855
+ throw this.error(failure[0], failure[1], pos);
856
+ const owner = this.stack[this.stack.length - 1]?.node;
857
+ if (owner !== undefined && frame.ns === MODEL) {
858
+ if (frame.local === "outgoing")
859
+ owner.outgoing.push(frame.text);
860
+ else if (frame.local === "incoming")
861
+ owner.incoming.push(frame.text);
862
+ }
863
+ }
864
+ if (this.stack.length === 0) {
865
+ const missing = this.idrefs.find((ref) => !this.ids.has(ref));
866
+ if (missing !== undefined)
867
+ throw this.error("idref-resolves", `cvc-id.1: There is no ID/IDREF binding for IDREF '${missing}'.`, pos);
868
+ }
869
+ }
870
+ /** Validates a value against a simple type; the rule and Xerces' message on failure. */
871
+ value(type, raw, nsMap) {
872
+ if (type === "string" || type === "anyURI")
873
+ return undefined;
874
+ const enumeration = own(XSD_ENUMS, type);
875
+ if (enumeration !== undefined) {
876
+ if (enumeration.length === 0 || enumeration.includes(raw))
877
+ return undefined;
878
+ return [
879
+ "xsd-content",
880
+ `cvc-enumeration-valid: Value '${raw}' is not facet-valid with respect to enumeration '[${enumeration.join(", ")}]'. It must be a value from the enumeration.`,
881
+ ];
882
+ }
883
+ const v = collapse(raw);
884
+ const invalid = (rule, name) => [
885
+ rule,
886
+ `cvc-datatype-valid.1.2.1: '${v}' is not a valid value for '${name}'.`,
887
+ ];
888
+ switch (type) {
889
+ case "boolean":
890
+ return /^(true|false|1|0)$/.test(v) ? undefined : invalid("xsd-content", "boolean");
891
+ case "integer":
892
+ case "int":
893
+ return /^[+-]?[0-9]+$/.test(v) ? undefined : invalid("xsd-content", "integer");
894
+ case "double":
895
+ return DOUBLE.test(v) ? undefined : invalid("xsd-content", "double");
896
+ case "ID":
897
+ if (!isNcName(v))
898
+ return invalid("id-ncname-unique", "NCName");
899
+ if (this.ids.has(v))
900
+ return [
901
+ "id-ncname-unique",
902
+ `cvc-id.2: There are multiple occurrences of ID value '${v}'.`,
903
+ ];
904
+ this.ids.add(v);
905
+ return undefined;
906
+ case "IDREF":
907
+ if (!isNcName(v))
908
+ return invalid("idref-resolves", "NCName");
909
+ this.idrefs.push(v);
910
+ return undefined;
911
+ case "QName": {
912
+ if (!isQName(v))
913
+ return invalid("idref-resolves", "QName");
914
+ const [prefix] = splitQName(v);
915
+ if (prefix !== "" && this.resolvePrefix(nsMap, prefix) === undefined)
916
+ return [
917
+ "idref-resolves",
918
+ `UndeclaredPrefix: Cannot resolve '${v}' as a QName: the prefix '${prefix}' is not declared.`,
919
+ ];
920
+ return undefined;
921
+ }
922
+ default:
923
+ return undefined;
924
+ }
925
+ }
926
+ }
927
+ /** Zeebe's `ModelWalker` order: an element before its children, later siblings before earlier ones. */
928
+ function walkOrder(a, b) {
929
+ for (let k = 0; k < Math.min(a.length, b.length); k++) {
930
+ const x = a[k] ?? 0;
931
+ const y = b[k] ?? 0;
932
+ if (x !== y)
933
+ return y - x;
934
+ }
935
+ return a.length - b.length;
936
+ }
937
+ function splitQName(raw) {
938
+ const colon = raw.indexOf(":");
939
+ return colon < 0 ? ["", raw] : [raw.slice(0, colon), raw.slice(colon + 1)];
940
+ }
941
+ /** The type a child takes when it matches the particle, `undefined` for wildcard content, `null` when it does not match. */
942
+ function matchParticle(p, child) {
943
+ for (const alt of p.alts) {
944
+ switch (alt.kind) {
945
+ case "any":
946
+ return undefined;
947
+ case "other":
948
+ if (child.ns !== alt.ns && child.ns !== "")
949
+ return undefined;
950
+ break;
951
+ case "local":
952
+ if (child.ns === alt.ns && child.local === alt.local)
953
+ return alt.type ?? null;
954
+ break;
955
+ case "ref": {
956
+ const key = schemaKey(child.ns, child.local);
957
+ let decl = key === undefined ? undefined : globalElement(key);
958
+ const type = decl?.type;
959
+ let name = key;
960
+ for (let guard = 0; decl !== undefined && name !== undefined && guard < 16; guard++) {
961
+ const { ns, local } = schemaName(name);
962
+ if (ns === alt.ns && local === alt.local)
963
+ return type ?? null;
964
+ name = decl.head;
965
+ decl = name === undefined ? undefined : globalElement(name);
966
+ }
967
+ break;
968
+ }
969
+ }
970
+ }
971
+ return null;
972
+ }
973
+ function isDeclared(child) {
974
+ const key = schemaKey(child.ns, child.local);
975
+ return key !== undefined && globalElement(key) !== undefined;
976
+ }
977
+ /** What Xerces lists as allowed next: the current particle while it may repeat, then up to the next required one. */
978
+ function expectedAt(ps, pi, pc) {
979
+ const out = [];
980
+ const current = ps[pi];
981
+ if (current !== undefined) {
982
+ if (pc < current.max)
983
+ out.push(...current.alts.map(altLabel));
984
+ if (pc < current.min)
985
+ return out;
986
+ }
987
+ for (let j = pi + 1; j < ps.length; j++) {
988
+ const p = ps[j];
989
+ if (p === undefined)
990
+ break;
991
+ out.push(...p.alts.map(altLabel));
992
+ if (p.min > 0)
993
+ break;
994
+ }
995
+ return out;
996
+ }
997
+ /** How many more a counted particle (minOccurs above 1) needs once it has started, or `undefined`. */
998
+ function shortBy(p, count) {
999
+ if (p === undefined || p.min <= 1 || count === 0 || count >= p.min)
1000
+ return undefined;
1001
+ return p.min - count;
1002
+ }
1003
+ function minimumMessage(p, short, where) {
1004
+ const label = p.alts.map(altLabel).join(", ");
1005
+ const more = short === 1
1006
+ ? "One more instance is required to satisfy this constraint."
1007
+ : `'${short}' more instances are required to satisfy this constraint.`;
1008
+ return `'${label}' is expected to occur a minimum of '${p.min}' times${where}. ${more}`;
1009
+ }
1010
+ function isComplete(ps, pi, pc) {
1011
+ const current = ps[pi];
1012
+ if (current !== undefined && pc < current.min)
1013
+ return false;
1014
+ for (let j = pi + 1; j < ps.length; j++)
1015
+ if ((ps[j]?.min ?? 0) > 0)
1016
+ return false;
1017
+ return true;
1018
+ }
1019
+ function missingAttributeRule(element, attribute) {
1020
+ if (attribute === "targetNamespace" && element === "definitions")
1021
+ return "target-namespace";
1022
+ if (element === "sequenceFlow")
1023
+ return "sequence-flow-refs";
1024
+ if (element === "boundaryEvent" && attribute === "attachedToRef")
1025
+ return "boundary-attached-ref";
1026
+ if (element === "association" || element === "messageFlow")
1027
+ return "association-refs";
1028
+ return "xsd-required-name";
1029
+ }
1030
+ /**
1031
+ * Zeebe's parse and XSD stage (zeebe-rules.md section A, `check: "xml"`): what
1032
+ * the text must satisfy before BPMN Kit's tolerant parser reads it. Also the
1033
+ * missing ids Zeebe rejects (`id-present`), which BPMN Kit's parser cannot model,
1034
+ * and `incoming`/`outgoing` references Zeebe's validators fail to resolve.
1035
+ *
1036
+ * @returns `fatal` when Zeebe would stop at parsing, so the model rules are not run.
1037
+ */
1038
+ export function checkXml(xml, ctx) {
1039
+ const checker = new XmlChecker(xml);
1040
+ try {
1041
+ checker.run();
1042
+ }
1043
+ catch (err) {
1044
+ if (!(err instanceof XmlFailure))
1045
+ throw err;
1046
+ ctx.report(err.rule, "", err.message, SUGGESTIONS[err.rule] ?? "Fix the BPMN XML.");
1047
+ return { fatal: true };
1048
+ }
1049
+ const reference = checker.referenceFailure();
1050
+ if (reference !== undefined) {
1051
+ ctx.report("idref-resolves", "", reference, "Point incoming and outgoing at the ids of existing sequence flows.");
1052
+ return { fatal: true };
1053
+ }
1054
+ if (checker.missingIds.length > 0) {
1055
+ for (const owner of checker.missingIds)
1056
+ ctx.report("id-present", owner, "Element id must be present and not empty.", SUGGESTIONS["id-present"] ?? "");
1057
+ // BPMN Kit's parser cannot build a model without these ids, so the model rules cannot run.
1058
+ return { fatal: true };
1059
+ }
1060
+ return { fatal: false };
1061
+ }
1062
+ //# sourceMappingURL=xml.js.map