@dataverse-to-code/test 0.24.0 → 1.0.1

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/sim.js CHANGED
@@ -832,19 +832,19 @@ ${widths}
832
832
  if (ctx)
833
833
  ctx.aliasResolveCache = nodes;
834
834
  }
835
- let found = void 0;
835
+ let found2 = void 0;
836
836
  for (const node of nodes) {
837
837
  if (node === this)
838
838
  break;
839
839
  if (node.anchor === this.source)
840
- found = node;
840
+ found2 = node;
841
841
  }
842
- if (found && ctx) {
842
+ if (found2 && ctx) {
843
843
  const { anchors, doc: doc2, maxAliasCount } = ctx;
844
- let data = anchors.get(found);
844
+ let data = anchors.get(found2);
845
845
  if (!data) {
846
- toJS(found, null, ctx);
847
- data = anchors.get(found);
846
+ toJS(found2, null, ctx);
847
+ data = anchors.get(found2);
848
848
  }
849
849
  if (data?.res === void 0) {
850
850
  const msg = "This should not happen: Alias anchor was not resolved?";
@@ -853,14 +853,14 @@ ${widths}
853
853
  if (maxAliasCount >= 0) {
854
854
  data.count += 1;
855
855
  if (data.aliasCount === 0)
856
- data.aliasCount = getAliasCount(doc2, found, anchors);
856
+ data.aliasCount = getAliasCount(doc2, found2, anchors);
857
857
  if (data.count * data.aliasCount > maxAliasCount) {
858
858
  const msg = "Excessive alias count indicates a resource exhaustion attack";
859
859
  throw new ReferenceError(msg);
860
860
  }
861
861
  }
862
862
  }
863
- return found;
863
+ return found2;
864
864
  }
865
865
  toJSON(_arg, ctx) {
866
866
  if (!ctx)
@@ -1403,9 +1403,9 @@ ${indent}`) + "'";
1403
1403
  return quotedString(value, ctx);
1404
1404
  }
1405
1405
  const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? " " : "");
1406
- const literal2 = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.BLOCK_FOLDED ? false : type === Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
1406
+ const literal3 = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.BLOCK_FOLDED ? false : type === Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
1407
1407
  if (!value)
1408
- return literal2 ? "|\n" : ">\n";
1408
+ return literal3 ? "|\n" : ">\n";
1409
1409
  let chomp;
1410
1410
  let endStart;
1411
1411
  for (endStart = value.length; endStart > 0; --endStart) {
@@ -1454,7 +1454,7 @@ ${indent}`) + "'";
1454
1454
  if (onComment)
1455
1455
  onComment();
1456
1456
  }
1457
- if (!literal2) {
1457
+ if (!literal3) {
1458
1458
  const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
1459
1459
  let literalFallback = false;
1460
1460
  const foldOptions = getFoldOptions(ctx, true);
@@ -1495,9 +1495,9 @@ ${indent}${start}${value}${end}`;
1495
1495
  const str = value.replace(/\n+/g, `$&
1496
1496
  ${indent}`);
1497
1497
  if (actualString) {
1498
- const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str);
1498
+ const test2 = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str);
1499
1499
  const { compat, tags } = ctx.doc.schema;
1500
- if (tags.some(test) || compat?.some(test))
1500
+ if (tags.some(test2) || compat?.some(test2))
1501
1501
  return quotedString(value, ctx);
1502
1502
  }
1503
1503
  return implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false));
@@ -2888,14 +2888,14 @@ ${cn.comment}` : item.comment;
2888
2888
  }
2889
2889
  static from(schema4, iterable, ctx) {
2890
2890
  const { replacer } = ctx;
2891
- const set2 = new this(schema4);
2891
+ const set3 = new this(schema4);
2892
2892
  if (iterable && Symbol.iterator in Object(iterable))
2893
2893
  for (let value of iterable) {
2894
2894
  if (typeof replacer === "function")
2895
2895
  value = replacer.call(iterable, value, value);
2896
- set2.items.push(createPair(value, null, ctx));
2896
+ set3.items.push(createPair(value, null, ctx));
2897
2897
  }
2898
- return set2;
2898
+ return set3;
2899
2899
  }
2900
2900
  };
2901
2901
  YAMLSet.tag = "tag:yaml.org,2002:set";
@@ -3592,13 +3592,13 @@ ${cn.comment}` : item.comment;
3592
3592
  var bare = (id) => id.replace(/[{}]/g, "").toLowerCase();
3593
3593
  var dateOnly = (col) => col.type === "date" || col.behavior === "dateOnly";
3594
3594
  var day = (d) => Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
3595
- var asDate = (s) => new Date(s.length === 10 ? `${s}T00:00:00Z` : /(Z|[+-]\d\d:?\d\d)$/.test(s) ? s : `${s}Z`);
3595
+ var asDate = (s) => new Date(s.length === 10 ? `${s}T00:00:00Z` : /(Z|[+-]\d\d:?\d\d)$/i.test(s) ? s : `${s}Z`);
3596
3596
  function option(col, v) {
3597
3597
  if (typeof v === "number") return v;
3598
3598
  const text = String(v).trim();
3599
3599
  if (/^-?\d+$/.test(text)) return Number(text);
3600
- const matches = col.options.filter((o) => o.label.toLowerCase() === text.toLowerCase());
3601
- return matches.length > 0 ? matches[0].value : null;
3600
+ const matches2 = col.options.filter((o) => o.label.toLowerCase() === text.toLowerCase());
3601
+ return matches2.length > 0 ? matches2[0].value : null;
3602
3602
  }
3603
3603
  function fromRecord(col, record, nameOf, tableOf) {
3604
3604
  if (LOOKUP.has(col.type)) {
@@ -3619,7 +3619,10 @@ ${cn.comment}` : item.comment;
3619
3619
  return String(v);
3620
3620
  }
3621
3621
  function toRecord(col, value) {
3622
- if (LOOKUP.has(col.type)) return { [`_${col.name}_value`]: Array.isArray(value) && value.length > 0 ? value[0].id : null };
3622
+ if (LOOKUP.has(col.type)) {
3623
+ const v = Array.isArray(value) && value.length > 0 ? value[0] : void 0;
3624
+ return { [`_${col.name}_value`]: v?.id ?? null, [`_${col.name}_value@Microsoft.Dynamics.CRM.lookuplogicalname`]: v?.entityType ?? null };
3625
+ }
3623
3626
  if (value === null) return { [col.name]: null };
3624
3627
  if (col.type === "choices") return { [col.name]: value.join(",") };
3625
3628
  if (value instanceof Date) return { [col.name]: dateOnly(col) ? value.toISOString().slice(0, 10) : value.toISOString() };
@@ -3639,9 +3642,9 @@ ${cn.comment}` : item.comment;
3639
3642
  if (DATE.has(col.type)) return asDate(text);
3640
3643
  if (col.type === "choice" || col.type === "choices") {
3641
3644
  if (/^-?\d+$/.test(text)) return Number(text);
3642
- const matches = col.options.filter((o) => o.label.toLowerCase() === text.toLowerCase());
3643
- if (matches.length !== 1) throw new NotSimulated(`the choice label "${text}" on ${col.name} (${matches.length === 0 ? "no option has it" : "two options share it"})`);
3644
- return matches[0].value;
3645
+ const matches2 = col.options.filter((o) => o.label.toLowerCase() === text.toLowerCase());
3646
+ if (matches2.length !== 1) throw new NotSimulated(`the choice label "${text}" on ${col.name} (${matches2.length === 0 ? "no option has it" : "two options share it"})`);
3647
+ return matches2[0].value;
3645
3648
  }
3646
3649
  if (LOOKUP.has(col.type)) return [{ id: bare(text), name: "", entityType: col.target ?? "" }];
3647
3650
  return text;
@@ -3736,7 +3739,8 @@ ${cn.comment}` : item.comment;
3736
3739
  const givenNode = doc.get("given", true);
3737
3740
  if (source && isMap(givenNode)) {
3738
3741
  const pair = givenNode.items.find((p) => isScalar(p.key) && p.key.value === "records");
3739
- if (pair) pair.key.commentBefore = ` ${source}: real data, check before committing`;
3742
+ const from = source.replace(/ \((anonymised|real data)\)$/, "");
3743
+ if (pair) pair.key.commentBefore = / \(anonymised\)$/.test(source) ? ` ${from}: anonymised (fake personal values), check before committing` : ` ${from}: real data, check before committing`;
3740
3744
  }
3741
3745
  return doc.toString();
3742
3746
  }
@@ -3754,6 +3758,11 @@ ${cn.comment}` : item.comment;
3754
3758
  }
3755
3759
  };
3756
3760
 
3761
+ // ../../extension/src/core/fetchxml/lookups.ts
3762
+ function lookupColumnsOf(meta) {
3763
+ return Object.fromEntries(Object.entries(meta).map(([t, m]) => [t, Object.entries(m.columns).filter(([, c]) => c.kind === "lookup").map(([n]) => n)]));
3764
+ }
3765
+
3757
3766
  // ../../extension/src/sim/formState.ts
3758
3767
  var FormState = class {
3759
3768
  columns = /* @__PURE__ */ new Map();
@@ -3819,8 +3828,50 @@ ${cn.comment}` : item.comment;
3819
3828
  }
3820
3829
  };
3821
3830
 
3831
+ // ../../extension/src/sim/procedureLog.ts
3832
+ var original = /* @__PURE__ */ Symbol("dqlOriginal");
3833
+ var messageOf = (e) => e && typeof e === "object" && typeof e.message === "string" ? e.message : String(e);
3834
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
3835
+ var argumentsText = (a) => {
3836
+ try {
3837
+ return JSON.stringify(a) ?? "";
3838
+ } catch {
3839
+ return Array.isArray(a) ? "[\u2026]" : a && typeof a === "object" ? "{\u2026}" : String(a);
3840
+ }
3841
+ };
3842
+ function watchProcedures(scope, log, changes, transactions) {
3843
+ const dql = scope.Dql;
3844
+ if (!dql || typeof dql !== "object") return;
3845
+ for (const name of Object.keys(dql)) {
3846
+ const current = dql[name];
3847
+ if (name.startsWith("_") || name === "DqlError" || typeof current !== "function") continue;
3848
+ const fn = current[original] ?? current;
3849
+ const wrapped = async function(...args) {
3850
+ const call = `Dql.${name}(${args.length > 0 ? argumentsText(args[0]) : ""})`;
3851
+ const changesBefore = changes();
3852
+ const transactionsBefore = transactions();
3853
+ let result;
3854
+ try {
3855
+ result = await fn.apply(this, args);
3856
+ } catch (e) {
3857
+ log.add("procedure", `${call} \u2192 error: ${messageOf(e)}`);
3858
+ throw e;
3859
+ }
3860
+ const made = changes() - changesBefore;
3861
+ const parts = [];
3862
+ if (Array.isArray(result)) parts.push(plural(result.length, "row"));
3863
+ if (made > 0) parts.push(plural(made, "change") + (transactions() > transactionsBefore ? " (transaction)" : ""));
3864
+ log.add("procedure", `${call} \u2192 ${parts.length > 0 ? parts.join(", ") : "done"}`);
3865
+ return result;
3866
+ };
3867
+ Object.assign(wrapped, fn);
3868
+ wrapped[original] = fn;
3869
+ dql[name] = wrapped;
3870
+ }
3871
+ }
3872
+
3822
3873
  // ../../extension/src/sim/formula.ts
3823
- function evaluateFormula(text, valueOf, target) {
3874
+ function evaluateFormula(text, valueOf2, target) {
3824
3875
  const toks = text.match(/\d+(?:\.\d+)?|[A-Za-z_]\w*|[-+*/()]|\S/g) ?? [];
3825
3876
  const fail = () => {
3826
3877
  throw new NotSimulated(`the formula "${text}"`);
@@ -3840,7 +3891,7 @@ ${cn.comment}` : item.comment;
3840
3891
  if (t !== void 0 && /^\d/.test(t)) return Number(t);
3841
3892
  if (t !== void 0 && /^[A-Za-z_]/.test(t)) {
3842
3893
  if (toks[p] === "(") throw new NotSimulated(`the formula function ${t}`);
3843
- const v = valueOf(t);
3894
+ const v = valueOf2(t);
3844
3895
  if (v === null) return null;
3845
3896
  if (typeof v === "number" || v instanceof Date) return v;
3846
3897
  throw new NotSimulated(`the formula "${text}" (${t} isn't a number or a date)`);
@@ -4043,6 +4094,61 @@ ${cn.comment}` : item.comment;
4043
4094
  }
4044
4095
  };
4045
4096
 
4097
+ // ../../extension/src/core/offlineChanges.ts
4098
+ var idKey = (id) => id.replace(/[{}]/g, "").toLowerCase();
4099
+ var rowKey = (table, id) => `${table.toLowerCase()}
4100
+ ${idKey(id)}`;
4101
+ var fromPulled = (r) => /^pulled from /.test(r.source ?? "");
4102
+ var plain = (v) => Object.prototype.toString.call(v) === "[object Date]" ? v.toISOString() : Array.isArray(v) ? v.map(plain) : v;
4103
+ var LOOKUP_TABLE = "@Microsoft.Dynamics.CRM.lookuplogicalname";
4104
+ function written(values) {
4105
+ return Object.fromEntries(Object.entries(values).filter(([k]) => !k.includes("@")).map(([k, v]) => {
4106
+ const lookup = /^_(.+)_value$/.exec(k)?.[1];
4107
+ const table = values[`${k}${LOOKUP_TABLE}`];
4108
+ if (lookup && typeof table === "string" && typeof v === "string") return [lookup, { table, id: v }];
4109
+ return [lookup ?? k, plain(v)];
4110
+ }));
4111
+ }
4112
+ var ISO_TIME = /^\d{4}-\d{2}-\d{2}T/;
4113
+ function meaning(v, col) {
4114
+ const p = plain(v);
4115
+ if (p === null || p === void 0 || p === "") return null;
4116
+ if (col?.kind === "choice") {
4117
+ const byLabel = new Map(Object.entries(col.options).map(([value, label]) => [label.toLowerCase(), Number(value)]));
4118
+ const one = (x) => typeof x === "number" ? x : /^\s*-?\d+\s*$/.test(String(x)) ? Number(x) : byLabel.get(String(x).trim().toLowerCase()) ?? String(x).trim();
4119
+ if (Array.isArray(p)) return { set: p.map(one).map(String).sort() };
4120
+ if (typeof p === "string" && /[,;]/.test(p)) return { set: p.split(/[,;]/).map((x) => x.trim()).filter(Boolean).map(one).map(String).sort() };
4121
+ return one(p);
4122
+ }
4123
+ if (typeof p === "string" && ISO_TIME.test(p) && !Number.isNaN(Date.parse(p))) return { instant: Date.parse(p) };
4124
+ return p;
4125
+ }
4126
+ function same(a, b, col) {
4127
+ let x = meaning(a, col), y = meaning(b, col);
4128
+ const isSet = (v) => !!v && typeof v === "object" && "set" in v;
4129
+ if (isSet(x) && !isSet(y) && y !== null) y = { set: [String(y)] };
4130
+ if (isSet(y) && !isSet(x) && x !== null) x = { set: [String(x)] };
4131
+ return JSON.stringify(x) === JSON.stringify(y);
4132
+ }
4133
+ function changeSetOf(baseline, current, meta = {}) {
4134
+ const before = new Map(baseline.map((r) => [rowKey(r.table, r.id), r]));
4135
+ const now = new Set(current.map((r) => rowKey(r.table, r.id)));
4136
+ const set3 = { created: [], updated: [], deleted: [] };
4137
+ for (const r of current) {
4138
+ const values = written(r.values);
4139
+ const was = before.get(rowKey(r.table, r.id));
4140
+ if (!was) {
4141
+ set3.created.push({ table: r.table, id: r.id, values: Object.fromEntries(Object.entries(values).filter(([, v]) => v !== null && v !== void 0)) });
4142
+ continue;
4143
+ }
4144
+ const old = written(was.values);
4145
+ const changed = Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(values), ...Object.keys(old)])].filter((k) => !same(values[k], old[k], meta[r.table]?.columns[k])).map((k) => [k, values[k] ?? null]));
4146
+ if (Object.keys(changed).length) set3.updated.push({ table: r.table, id: r.id, values: changed, ...fromPulled(was) ? { pulled: true } : {} });
4147
+ }
4148
+ for (const r of baseline) if (!now.has(rowKey(r.table, r.id))) set3.deleted.push({ table: r.table, id: r.id, ...fromPulled(r) ? { pulled: true } : {} });
4149
+ return set3;
4150
+ }
4151
+
4046
4152
  // ../../extension/src/sim/odata.ts
4047
4153
  var SUPPORTED = /* @__PURE__ */ new Set(["$select", "$filter", "$orderby", "$top"]);
4048
4154
  var OPS = /* @__PURE__ */ new Set(["eq", "ne", "gt", "ge", "lt", "le", "and", "or", "not"]);
@@ -4170,17 +4276,41 @@ ${cn.comment}` : item.comment;
4170
4276
 
4171
4277
  // ../../extension/src/sim/store.ts
4172
4278
  var key = (id) => id.replace(/[{}]/g, "").toLowerCase();
4279
+ var GUID = /^\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}?$/;
4173
4280
  var Store = class {
4174
4281
  constructor(tables, records, newId, lookupColumns = {}) {
4175
4282
  this.tables = tables;
4176
4283
  this.newId = newId;
4177
4284
  this.lookupColumns = lookupColumns;
4178
4285
  for (const r of records) this.put({ table: r.table, id: r.id, values: this.normalise(r.table, r.values), ...r.source ? { source: r.source } : {} });
4286
+ this.baseline = this.written();
4179
4287
  }
4180
4288
  tables;
4181
4289
  newId;
4182
4290
  lookupColumns;
4183
4291
  records = /* @__PURE__ */ new Map();
4292
+ /** The rows as loaded (or as last saved), that changes() compares with. */
4293
+ baseline;
4294
+ /** What changed since the rows were loaded (or last saved): rows created, updated (only the changed columns) and deleted. */
4295
+ changes(meta) {
4296
+ return changeSetOf(this.baseline, this.written(), meta);
4297
+ }
4298
+ /** The rows as loaded (or as last saved), as written. */
4299
+ loadedRows() {
4300
+ return this.baseline;
4301
+ }
4302
+ /** The changes are saved (to a seed scenario): changes() starts again from the rows now. */
4303
+ markSaved() {
4304
+ this.baseline = this.written();
4305
+ }
4306
+ listeners = [];
4307
+ /** Called after each create, update, delete and restore (Try Form tells VS Code its rows). */
4308
+ onChange(listener) {
4309
+ this.listeners.push(listener);
4310
+ }
4311
+ changed() {
4312
+ for (const l of this.listeners) l();
4313
+ }
4184
4314
  /** Lookups given as col: id (seed output, hand-written records) are held as the Web API holds them: _col_value. */
4185
4315
  normalise(table, values) {
4186
4316
  const lookups = new Set(this.lookupColumns[table] ?? []);
@@ -4209,21 +4339,37 @@ ${cn.comment}` : item.comment;
4209
4339
  values: Object.fromEntries(Object.entries(r.values).filter(([k]) => !k.includes("@")).map(([k, v]) => [/^_(.+)_value$/.exec(k)?.[1] ?? k, v]))
4210
4340
  }));
4211
4341
  }
4342
+ /** A copy of every record, to put back with restore (a change set that fails). */
4343
+ snapshot() {
4344
+ return structuredClone(this.records);
4345
+ }
4346
+ restore(snapshot) {
4347
+ this.records = structuredClone(snapshot);
4348
+ this.changed();
4349
+ }
4212
4350
  get(table, id) {
4213
4351
  return this.records.get(table)?.get(key(id));
4214
4352
  }
4353
+ /** A new record: its primary id the one given (as Dataverse takes a create's), else a new one. */
4215
4354
  create(table, values) {
4216
- const id = this.newId();
4217
- this.put({ table, id, values: this.normalise(table, { ...values }) });
4355
+ const pk = this.primaryId(table), given = values[pk];
4356
+ const takes = typeof given === "string" && GUID.test(given);
4357
+ const id = takes ? key(given) : this.newId();
4358
+ if (takes && this.get(table, id)) throw new Error("A record with these values already exists.");
4359
+ const rest = { ...values };
4360
+ delete rest[pk];
4361
+ this.put({ table, id, values: this.normalise(table, rest) });
4362
+ this.changed();
4218
4363
  return id;
4219
4364
  }
4220
4365
  update(table, id, values) {
4221
4366
  const r = this.get(table, id);
4222
4367
  if (!r) throw new Error(`No ${table} record ${id} in the offline data.`);
4223
4368
  r.values = { ...r.values, ...this.normalise(table, values) };
4369
+ this.changed();
4224
4370
  }
4225
4371
  delete(table, id) {
4226
- this.records.get(table)?.delete(key(id));
4372
+ if (this.records.get(table)?.delete(key(id))) this.changed();
4227
4373
  }
4228
4374
  /** A record's name: its primary name, or for a table the form doesn't know (pulled data), its first text value. */
4229
4375
  nameOf(table, id) {
@@ -4267,6 +4413,571 @@ ${cn.comment}` : item.comment;
4267
4413
  }
4268
4414
  };
4269
4415
 
4416
+ // ../../extension/src/core/fetchxml/collation.ts
4417
+ var collator = new Intl.Collator("en", { sensitivity: "base" });
4418
+ var collate = (a, b) => collator.compare(a.replace(/ +$/, ""), b.replace(/ +$/, ""));
4419
+ var STROKES = { "\xF8": "o", "\xF0": "d", "\u0111": "d", "\u0127": "h", "\u0142": "l", "\u0140": "l", "\xDF": "ss", "\xE6": "ae", "\u0153": "oe" };
4420
+ function unit(c) {
4421
+ if (/[\u007f-\u0084\u0086-\u009f­​-‏⁠-⁤]/.test(c)) return "";
4422
+ let f = c.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase();
4423
+ f = (STROKES[c.toLowerCase()] ?? f).replace(/[øðđħłßæœ]/g, (x) => STROKES[x]);
4424
+ return /\s/.test(f) && !/\s/.test(c) ? c : f;
4425
+ }
4426
+ var esc2 = (t) => t.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&");
4427
+ var ONE = "[^\uE000\uE001](?:\uE000[^\uE000\uE001])*\uE001";
4428
+ function set2(chars) {
4429
+ let singles = "";
4430
+ const several = [];
4431
+ for (let k = 0; k < chars.length; k++) {
4432
+ const u = unit(chars[k]);
4433
+ if (chars[k + 1] === "-" && k + 2 < chars.length && u.length === 1 && unit(chars[k + 2]).length === 1) {
4434
+ singles += `${esc2(u)}-${esc2(unit(chars[k + 2]))}`;
4435
+ k += 2;
4436
+ } else if (u.length === 1) singles += esc2(u);
4437
+ else if (u.length > 1) several.push(u.split("").map(esc2).join("\uE000") + "\uE001");
4438
+ }
4439
+ return `(?:${singles ? `[${singles}]\uE001` : "(?!)"}${several.map((x) => `|${x}`).join("")})`;
4440
+ }
4441
+ var builds = 0;
4442
+ var matchers = /* @__PURE__ */ new Map();
4443
+ function matcher(pattern) {
4444
+ const known = matchers.get(pattern);
4445
+ if (known) return known;
4446
+ builds++;
4447
+ let re = "";
4448
+ let letters = [];
4449
+ const flush = () => {
4450
+ if (letters.length) re += letters.map(esc2).join("[\uE000\uE001]") + "\uE001";
4451
+ letters = [];
4452
+ };
4453
+ for (let i = 0; i < pattern.length; i++) {
4454
+ const ch = pattern[i];
4455
+ let end;
4456
+ if (ch === "%") {
4457
+ flush();
4458
+ re += "(?:[^\uE001]*\uE001)*";
4459
+ } else if (ch === "_") {
4460
+ flush();
4461
+ re += ONE;
4462
+ } else if (ch === "[" && (end = pattern.indexOf("]", i + 2)) > 0) {
4463
+ flush();
4464
+ const inside = pattern.slice(i + 1, end);
4465
+ re += inside[0] === "^" ? `(?!${set2(inside.slice(1))})${ONE}` : set2(inside);
4466
+ i = end;
4467
+ } else letters = letters.concat(unit(ch).split(""));
4468
+ }
4469
+ flush();
4470
+ if (matchers.size >= 1e3) matchers.clear();
4471
+ const built = new RegExp(`^${re}$`);
4472
+ matchers.set(pattern, built);
4473
+ return built;
4474
+ }
4475
+ function like(value, pattern) {
4476
+ const text = Array.prototype.map.call(value.replace(/[\uE000\uE001]/g, ""), (c) => {
4477
+ const u = unit(c);
4478
+ return u ? u.split("").join("\uE000") + "\uE001" : "";
4479
+ }).join("");
4480
+ return matcher(pattern).test(text);
4481
+ }
4482
+ var literal2 = (s) => s.replace(/[%_[]/g, "[$&]");
4483
+
4484
+ // ../../extension/src/core/fetchxml/xml.ts
4485
+ var decode = (s) => s.replace(/&(lt|gt|amp|quot|apos|#\d+|#x[0-9a-f]+);/gi, (_, e) => e === "lt" ? "<" : e === "gt" ? ">" : e === "amp" ? "&" : e === "quot" ? '"' : e === "apos" ? "'" : String.fromCodePoint(e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)));
4486
+ function parseXml(src) {
4487
+ const root = { name: "#root", attrs: {}, children: [], text: "" };
4488
+ const stack = [root];
4489
+ const tokens2 = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[([\s\S]*?)\]\]>|<(\/?)([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)|(<[^<>]*>?)/g;
4490
+ for (const m of src.matchAll(tokens2)) {
4491
+ const [whole, cdata, close, name, attrText, selfClose, text, unreadable] = m;
4492
+ if (unreadable !== void 0) throw new Error(`FetchXML: can't read "${unreadable}".`);
4493
+ if (cdata !== void 0) {
4494
+ stack[stack.length - 1].text += cdata;
4495
+ continue;
4496
+ }
4497
+ if (whole.startsWith("<!--") || whole.startsWith("<?")) continue;
4498
+ if (text !== void 0) {
4499
+ stack[stack.length - 1].text += decode(text);
4500
+ continue;
4501
+ }
4502
+ if (close) {
4503
+ const top = stack.pop();
4504
+ if (!top || top.name !== name) throw new Error(`FetchXML: </${name}> doesn't close <${top?.name ?? ""}>.`);
4505
+ continue;
4506
+ }
4507
+ const attrs = {};
4508
+ for (const a of (attrText ?? "").matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) attrs[a[1]] = decode(a[2] ?? a[3] ?? "");
4509
+ const node = { name, attrs, children: [], text: "" };
4510
+ stack[stack.length - 1].children.push(node);
4511
+ if (!selfClose) stack.push(node);
4512
+ }
4513
+ if (stack.length !== 1) throw new Error(`FetchXML: <${stack[stack.length - 1].name}> isn't closed.`);
4514
+ if (root.children.length !== 1) throw new Error("FetchXML: one root element expected.");
4515
+ return root.children[0];
4516
+ }
4517
+
4518
+ // ../../extension/src/core/fetchxml/evaluate.ts
4519
+ var MAIN = "";
4520
+ var LOOKUP_TABLE2 = "@Microsoft.Dynamics.CRM.lookuplogicalname";
4521
+ var FORMATTED = "@OData.Community.Display.V1.FormattedValue";
4522
+ var GUID2 = /^\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?$/i;
4523
+ var DAY = /^\d{4}-\d{2}-\d{2}/;
4524
+ var normId = (v) => v.replace(/[{}]/g, "").toLowerCase();
4525
+ var isDate = (v) => Object.prototype.toString.call(v) === "[object Date]";
4526
+ var notSimulated = (what) => {
4527
+ throw new NotSimulated(`FetchXML ${what}`);
4528
+ };
4529
+ var primaryIdOf = (ctx, table) => ctx.meta[table]?.primaryId ?? `${table}id`;
4530
+ function lookupId(values, col) {
4531
+ if (`_${col}_value` in values) return values[`_${col}_value`] ?? null;
4532
+ const bind = values[`${col}@odata.bind`];
4533
+ if (typeof bind === "string") return /\(([^)]+)\)\s*$/.exec(bind)?.[1] ?? null;
4534
+ const v = values[col];
4535
+ if (Array.isArray(v)) return v[0]?.id ?? null;
4536
+ if (v && typeof v === "object" && "id" in v) return String(v.id);
4537
+ return void 0;
4538
+ }
4539
+ function isLookup2(ctx, table, col, rec) {
4540
+ if (ctx.meta[table]?.columns[col]?.kind === "lookup") return true;
4541
+ return !!rec && lookupId(rec.values, col) !== void 0 && !(col in rec.values && typeof rec.values[col] === "string");
4542
+ }
4543
+ function valueOf(ctx, table, rec, col) {
4544
+ if (!rec) return null;
4545
+ if (col === primaryIdOf(ctx, table)) return rec.id;
4546
+ const id = lookupId(rec.values, col);
4547
+ if (id !== void 0) return id;
4548
+ return rec.values[col] ?? null;
4549
+ }
4550
+ function outValue(ctx, table, rec, col) {
4551
+ const v = valueOf(ctx, table, rec, col);
4552
+ return typeof v === "string" && (col === primaryIdOf(ctx, table) || isLookup2(ctx, table, col, rec)) ? normId(v) : v;
4553
+ }
4554
+ function compare2(actual, wanted) {
4555
+ if (typeof actual === "number" && wanted.trim() !== "" && !Number.isNaN(Number(wanted))) return actual - Number(wanted);
4556
+ if (typeof actual === "boolean") return (actual ? 1 : 0) - (wanted === "true" || wanted === "1" ? 1 : 0);
4557
+ let a = isDate(actual) ? actual.toISOString() : String(actual);
4558
+ let b = wanted;
4559
+ if (GUID2.test(a) && GUID2.test(b)) {
4560
+ a = normId(a);
4561
+ b = normId(b);
4562
+ } else if (DAY.test(a) && DAY.test(b)) {
4563
+ if (a.length === 10 || b.length === 10) {
4564
+ a = a.slice(0, 10);
4565
+ b = b.slice(0, 10);
4566
+ } else {
4567
+ const d = asDate(a).getTime() - asDate(b).getTime();
4568
+ if (!Number.isNaN(d)) return d;
4569
+ }
4570
+ } else return collate(a, b);
4571
+ return a < b ? -1 : a > b ? 1 : 0;
4572
+ }
4573
+ function matches(op, actual, wanted) {
4574
+ if (op === "null") return actual === null || actual === void 0;
4575
+ if (op === "not-null") return !(actual === null || actual === void 0);
4576
+ if (actual === null || actual === void 0) return false;
4577
+ switch (op) {
4578
+ case "eq":
4579
+ return compare2(actual, wanted[0]) === 0;
4580
+ case "ne":
4581
+ return compare2(actual, wanted[0]) !== 0;
4582
+ case "gt":
4583
+ return compare2(actual, wanted[0]) > 0;
4584
+ case "ge":
4585
+ return compare2(actual, wanted[0]) >= 0;
4586
+ case "lt":
4587
+ return compare2(actual, wanted[0]) < 0;
4588
+ case "le":
4589
+ return compare2(actual, wanted[0]) <= 0;
4590
+ case "in":
4591
+ return wanted.some((w) => compare2(actual, w) === 0);
4592
+ case "not-in":
4593
+ return wanted.every((w) => compare2(actual, w) !== 0);
4594
+ case "between":
4595
+ return compare2(actual, wanted[0]) >= 0 && compare2(actual, wanted[1]) <= 0;
4596
+ case "not-between":
4597
+ return !(compare2(actual, wanted[0]) >= 0 && compare2(actual, wanted[1]) <= 0);
4598
+ case "like":
4599
+ return like(String(actual), wanted[0]);
4600
+ case "not-like":
4601
+ return !like(String(actual), wanted[0]);
4602
+ case "begins-with":
4603
+ return like(String(actual), `${literal2(wanted[0])}%`);
4604
+ case "not-begin-with":
4605
+ return !like(String(actual), `${literal2(wanted[0])}%`);
4606
+ case "ends-with":
4607
+ return like(String(actual), `%${literal2(wanted[0])}`);
4608
+ case "not-end-with":
4609
+ return !like(String(actual), `%${literal2(wanted[0])}`);
4610
+ default:
4611
+ return notSimulated(`operator "${op}"`);
4612
+ }
4613
+ }
4614
+ function test(ctx, filter, row, alias) {
4615
+ const type = filter.attrs.type ?? "and";
4616
+ if (type !== "and" && type !== "or") notSimulated(`filter type "${type}"`);
4617
+ const results = filter.children.map((c) => {
4618
+ if (c.name === "filter") return test(ctx, c, row, alias);
4619
+ if (c.name === "link-entity") {
4620
+ const { exists, type: type2 } = linkOf(ctx, c);
4621
+ if (!exists) notSimulated(`a link-type "${type2}" link-entity in a filter`);
4622
+ return found(ctx, c, alias, row).length > 0 === (type2 === "any");
4623
+ }
4624
+ if (c.name !== "condition") return notSimulated(`<${c.name}> in a filter`);
4625
+ if (c.attrs.valueof) notSimulated("valueof");
4626
+ const at = c.attrs.entityname ?? alias;
4627
+ const table = ctx.tables.get(at) ?? notSimulated(`entityname "${at}"`);
4628
+ if (!row.has(at)) notSimulated(`entityname "${at}" (a link with no columns: any / not any)`);
4629
+ const wanted = c.attrs.value !== void 0 ? [c.attrs.value] : c.children.filter((v) => v.name === "value").map((v) => v.text.trim());
4630
+ return matches(c.attrs.operator ?? "eq", valueOf(ctx, table, row.get(at) ?? null, c.attrs.attribute), wanted);
4631
+ });
4632
+ return type === "and" ? results.every(Boolean) : results.some(Boolean);
4633
+ }
4634
+ var KNOWN_IN_ENTITY = /* @__PURE__ */ new Set(["attribute", "all-attributes", "filter", "order", "link-entity"]);
4635
+ var linksIn = (node) => node.children.flatMap((c) => c.name === "link-entity" ? [c] : c.name === "filter" ? linksIn(c) : []);
4636
+ function checkAliases(entity, seen = /* @__PURE__ */ new Set()) {
4637
+ for (const link of linksIn(entity)) {
4638
+ const alias = link.attrs.alias ?? link.attrs.name;
4639
+ if (seen.has(alias)) notSimulated(`link-entity alias "${alias}" used twice`);
4640
+ seen.add(alias);
4641
+ checkAliases(link, seen);
4642
+ }
4643
+ }
4644
+ var brought = (node) => {
4645
+ for (const c of node.children) {
4646
+ if (c.name === "attribute" || c.name === "all-attributes") return "attributes";
4647
+ if (c.name === "order") return "an order";
4648
+ const inner = c.name === "link-entity" ? brought(c) : null;
4649
+ if (inner) return inner;
4650
+ }
4651
+ return null;
4652
+ };
4653
+ var checks = 0;
4654
+ function linkOf(ctx, link) {
4655
+ const known = ctx.links.get(link);
4656
+ if (known) return known;
4657
+ const checked = checkLink(ctx, link);
4658
+ ctx.links.set(link, checked);
4659
+ return checked;
4660
+ }
4661
+ function checkLink(ctx, link) {
4662
+ checks++;
4663
+ for (const c of link.children) if (!KNOWN_IN_ENTITY.has(c.name)) notSimulated(`<${c.name}>`);
4664
+ const alias = link.attrs.alias ?? link.attrs.name;
4665
+ const type = link.attrs["link-type"] ?? "inner";
4666
+ const exists = type === "any" || type === "not any";
4667
+ if (type !== "inner" && type !== "outer" && !exists) notSimulated(`link-type "${type}"`);
4668
+ const extra = exists ? brought(link) : null;
4669
+ if (extra) notSimulated(`${extra} in a link-type "${type}" link`);
4670
+ ctx.tables.set(alias, link.attrs.name);
4671
+ return { alias, type, exists };
4672
+ }
4673
+ function found(ctx, link, alias, row) {
4674
+ const table = link.attrs.name, linkAlias = link.attrs.alias ?? table;
4675
+ if (!ctx.candidates.has(link)) ctx.candidates.set(link, ctx.records(table));
4676
+ const key2 = valueOf(ctx, ctx.tables.get(alias), row.get(alias) ?? null, link.attrs.to);
4677
+ const matched = key2 === null ? [] : ctx.candidates.get(link).map((r) => new Map(row).set(linkAlias, r)).filter((r) => {
4678
+ const v = valueOf(ctx, table, r.get(linkAlias), link.attrs.from);
4679
+ return v !== null && compare2(v, String(key2)) === 0;
4680
+ }).filter((r) => link.children.filter((c) => c.name === "filter").every((f) => test(ctx, f, r, linkAlias)));
4681
+ return join(ctx, link, linkAlias, matched);
4682
+ }
4683
+ function join(ctx, entity, alias, rows) {
4684
+ for (const link of entity.children.filter((c) => c.name === "link-entity")) {
4685
+ const { alias: linkAlias, type, exists } = linkOf(ctx, link);
4686
+ if (exists && alias !== MAIN) notSimulated(`a link-type "${type}" link-entity directly inside a link-entity (Dataverse refuses it: put it in the link-entity's <filter>)`);
4687
+ const next = [];
4688
+ for (const row of rows) {
4689
+ const deeper = found(ctx, link, alias, row);
4690
+ if (exists) {
4691
+ if (deeper.length > 0 === (type === "any")) next.push(row);
4692
+ continue;
4693
+ }
4694
+ if (deeper.length) next.push(...deeper);
4695
+ else if (type === "outer") next.push(new Map(row).set(linkAlias, null));
4696
+ }
4697
+ rows = next;
4698
+ }
4699
+ return rows;
4700
+ }
4701
+ function specs(entity, alias) {
4702
+ const own = entity.children.flatMap((c) => {
4703
+ if (c.name === "all-attributes") return [{ alias, name: "*", groupby: false, all: true }];
4704
+ if (c.name !== "attribute") return [];
4705
+ if (c.attrs.dategrouping) notSimulated("date grouping");
4706
+ return [{ alias, name: c.attrs.name, as: c.attrs.alias, groupby: c.attrs.groupby === "true", aggregate: c.attrs.aggregate }];
4707
+ });
4708
+ return [...own, ...entity.children.filter((c) => c.name === "link-entity").flatMap((l) => specs(l, l.attrs.alias ?? l.attrs.name))];
4709
+ }
4710
+ function annotate(ctx, out, key2, table, col, value, rec) {
4711
+ if (value === null || value === void 0) return;
4712
+ const m = ctx.meta[table]?.columns[col];
4713
+ if (m?.kind === "choice") {
4714
+ out[`${key2}${FORMATTED}`] = m.options[String(value)] ?? null;
4715
+ return;
4716
+ }
4717
+ if (m?.kind === "yesNo") {
4718
+ out[`${key2}${FORMATTED}`] = value === true || value === 1 ? m.trueLabel : m.falseLabel;
4719
+ return;
4720
+ }
4721
+ if (!isLookup2(ctx, table, col, rec)) return;
4722
+ const id = normId(String(value));
4723
+ const targets = m?.kind === "lookup" ? m.targets : Object.keys(ctx.meta);
4724
+ const target = targets.find((t) => ctx.records(t).some((r) => normId(r.id) === id)) ?? (targets.length === 1 ? targets[0] : null);
4725
+ const found2 = target ? ctx.records(target).find((r) => normId(r.id) === id) : void 0;
4726
+ const nameCol = target ? ctx.meta[target]?.primaryName : void 0;
4727
+ out[`${key2}${LOOKUP_TABLE2}`] = target;
4728
+ out[`${key2}${FORMATTED}`] = found2 && nameCol ? found2.values[nameCol] ?? null : null;
4729
+ }
4730
+ function keyOf(ctx, s, rec) {
4731
+ if (s.as) return s.as;
4732
+ const table = ctx.tables.get(s.alias);
4733
+ if (s.alias !== MAIN) return `${s.alias}.${s.name}`;
4734
+ return isLookup2(ctx, table, s.name, rec) && s.name !== primaryIdOf(ctx, table) ? `_${s.name}_value` : s.name;
4735
+ }
4736
+ function plainRow(ctx, row, all, withId) {
4737
+ const mainTable = ctx.tables.get(MAIN);
4738
+ const out = withId ? { [primaryIdOf(ctx, mainTable)]: normId(row.get(MAIN).id) } : {};
4739
+ for (const s of all) {
4740
+ const rec = row.get(s.alias) ?? null;
4741
+ const table = ctx.tables.get(s.alias);
4742
+ if (s.all) {
4743
+ if (rec) for (const col of Object.keys(rec.values)) out[s.alias === MAIN ? col : `${s.alias}.${col}`] = rec.values[col];
4744
+ continue;
4745
+ }
4746
+ const key2 = keyOf(ctx, s, rec);
4747
+ const value = outValue(ctx, table, rec, s.name);
4748
+ out[key2] = value;
4749
+ annotate(ctx, out, key2, table, s.name, value, rec);
4750
+ }
4751
+ return out;
4752
+ }
4753
+ function aggregateRows(ctx, rows, all) {
4754
+ const groupBy = all.filter((s) => s.groupby);
4755
+ const groups = /* @__PURE__ */ new Map();
4756
+ if (!groupBy.length) groups.set("", rows);
4757
+ for (const row of groupBy.length ? rows : []) {
4758
+ const key2 = JSON.stringify(groupBy.map((s) => {
4759
+ const v = valueOf(ctx, ctx.tables.get(s.alias), row.get(s.alias) ?? null, s.name);
4760
+ return GUID2.test(String(v)) ? normId(String(v)) : v;
4761
+ }));
4762
+ groups.set(key2, [...groups.get(key2) ?? [], row]);
4763
+ }
4764
+ const kinds = /* @__PURE__ */ new Map();
4765
+ const columnKind = (s) => {
4766
+ if (!kinds.has(s)) kinds.set(s, kindOf(rows.map((r) => valueOf(ctx, ctx.tables.get(s.alias), r.get(s.alias) ?? null, s.name))));
4767
+ return kinds.get(s);
4768
+ };
4769
+ return [...groups.values()].map((group) => {
4770
+ const out = {};
4771
+ for (const s of all) {
4772
+ const table = ctx.tables.get(s.alias);
4773
+ const key2 = s.as ?? s.name;
4774
+ if (s.groupby) {
4775
+ const rec = group[0].get(s.alias) ?? null;
4776
+ const value = outValue(ctx, table, rec, s.name);
4777
+ out[key2] = value;
4778
+ annotate(ctx, out, key2, table, s.name, value, rec);
4779
+ continue;
4780
+ }
4781
+ const values = group.map((r) => valueOf(ctx, table, r.get(s.alias) ?? null, s.name)).filter((v) => v !== null && v !== void 0);
4782
+ const numbers = values.map(Number);
4783
+ if ((s.aggregate === "sum" || s.aggregate === "avg") && values.some((v) => typeof v !== "number")) notSimulated(`aggregate "${s.aggregate}" over non-numbers`);
4784
+ switch (s.aggregate) {
4785
+ case "count":
4786
+ out[key2] = group.length;
4787
+ break;
4788
+ case "countcolumn":
4789
+ out[key2] = values.length;
4790
+ break;
4791
+ case "sum":
4792
+ out[key2] = numbers.length ? numbers.reduce((a, b) => a + b, 0) : null;
4793
+ break;
4794
+ case "avg":
4795
+ out[key2] = numbers.length ? numbers.reduce((a, b) => a + b, 0) / numbers.length : null;
4796
+ break;
4797
+ // In the column's order, as ORDER BY sorts it: its kind from the whole column, not only this group.
4798
+ case "min":
4799
+ out[key2] = values.length ? values.reduce((a, b) => ordering(b, a, columnKind(s)) < 0 ? b : a) : null;
4800
+ break;
4801
+ case "max":
4802
+ out[key2] = values.length ? values.reduce((a, b) => ordering(b, a, columnKind(s)) > 0 ? b : a) : null;
4803
+ break;
4804
+ default:
4805
+ notSimulated(s.aggregate ? `aggregate "${s.aggregate}"` : `attribute "${s.name}" neither grouped nor aggregated`);
4806
+ }
4807
+ }
4808
+ return out;
4809
+ });
4810
+ }
4811
+ var kindOf = (values) => values.some((v) => typeof v === "number" || typeof v === "boolean") ? "number" : void 0;
4812
+ var numberOf = (v) => typeof v === "number" ? Number.isNaN(v) ? null : v : typeof v === "boolean" ? v ? 1 : 0 : typeof v === "string" && /^\s*[+-]?(?:\d+\.?\d*|\.\d+)\s*$/.test(v) ? Number(v) : null;
4813
+ var guidOrder = (v) => {
4814
+ const g = normId(v).split("-"), rev = (h2) => h2.match(/../g).reverse().join("");
4815
+ return g[4] + g[3] + rev(g[2]) + rev(g[1]) + rev(g[0]);
4816
+ };
4817
+ function ordering(a, b, kind) {
4818
+ const none = (v) => v === null || v === void 0;
4819
+ if (none(a) || none(b)) return none(a) && none(b) ? 0 : none(a) ? -1 : 1;
4820
+ if (kind === "number") {
4821
+ const x = numberOf(a), y = numberOf(b);
4822
+ if (x !== null && y !== null) return x === y ? 0 : x < y ? -1 : 1;
4823
+ if (x !== null || y !== null) return x !== null ? -1 : 1;
4824
+ const p = `${typeof a}:${String(a)}`, q = `${typeof b}:${String(b)}`;
4825
+ return p < q ? -1 : p > q ? 1 : 0;
4826
+ }
4827
+ if (typeof a === "string" && typeof b === "string" && GUID2.test(a) && GUID2.test(b)) {
4828
+ const x = guidOrder(a), y = guidOrder(b);
4829
+ return x < y ? -1 : x > y ? 1 : 0;
4830
+ }
4831
+ return compare2(a, isDate(b) ? b.toISOString() : String(b));
4832
+ }
4833
+ function sortValue(ctx, table, rec, col, raw) {
4834
+ const value = valueOf(ctx, table, rec, col);
4835
+ if (raw) return value;
4836
+ const labels = {};
4837
+ annotate(ctx, labels, "v", table, col, value, rec);
4838
+ return `v${FORMATTED}` in labels ? labels[`v${FORMATTED}`] ?? "" : value;
4839
+ }
4840
+ function ordersOf(entity, alias) {
4841
+ return [
4842
+ ...entity.children.filter((c) => c.name === "order").map((order) => ({ order, alias })),
4843
+ ...entity.children.filter((c) => c.name === "link-entity").flatMap((l) => ordersOf(l, l.attrs.alias ?? l.attrs.name))
4844
+ ];
4845
+ }
4846
+ function evaluateFetch(fetchXml, records, meta) {
4847
+ const fetch = parseXml(fetchXml);
4848
+ if (fetch.name !== "fetch") notSimulated(`<${fetch.name}>`);
4849
+ const entity = fetch.children.find((c) => c.name === "entity") ?? notSimulated("without <entity>");
4850
+ for (const c of entity.children) if (!KNOWN_IN_ENTITY.has(c.name)) notSimulated(`<${c.name}>`);
4851
+ checkAliases(entity);
4852
+ const ctx = { records, meta, tables: /* @__PURE__ */ new Map([[MAIN, entity.attrs.name]]), candidates: /* @__PURE__ */ new Map(), links: /* @__PURE__ */ new Map() };
4853
+ let rows = records(entity.attrs.name).map((r) => /* @__PURE__ */ new Map([[MAIN, r]]));
4854
+ rows = join(ctx, entity, MAIN, rows);
4855
+ rows = rows.filter((row) => entity.children.filter((c) => c.name === "filter").every((f) => test(ctx, f, row, MAIN)));
4856
+ const all = specs(entity, MAIN);
4857
+ const aggregate = fetch.attrs.aggregate === "true";
4858
+ const distinct = fetch.attrs.distinct === "true";
4859
+ const pairs2 = aggregate ? aggregateRows(ctx, rows, all).map((out) => ({ out })) : rows.map((row) => ({ row, out: plainRow(ctx, row, all, !distinct) }));
4860
+ let result = pairs2;
4861
+ if (distinct) {
4862
+ const seen = /* @__PURE__ */ new Set();
4863
+ result = result.filter((p) => {
4864
+ const k = JSON.stringify(p.out);
4865
+ if (seen.has(k)) return false;
4866
+ seen.add(k);
4867
+ return true;
4868
+ });
4869
+ }
4870
+ const orders = ordersOf(entity, MAIN);
4871
+ if (orders.length) {
4872
+ const raw = fetch.attrs.useraworderby === "true";
4873
+ const pick = (p, { order: o, alias }) => o.attrs.alias ? byAlias(p.out, o.attrs.alias) : p.row ? sortValue(ctx, ctx.tables.get(alias), p.row.get(alias) ?? null, o.attrs.attribute, raw) : p.out[alias === MAIN ? o.attrs.attribute : `${alias}.${o.attrs.attribute}`];
4874
+ const kindAt = (s) => ctx.meta[ctx.tables.get(s.alias)]?.columns[s.name]?.kind;
4875
+ const labelled = new Set(all.filter((s) => s.groupby && s.as && (kindAt(s) === "yesNo" || kindAt(s) === "choice")).map((s) => s.as));
4876
+ const zeroed = new Set(all.filter((s) => s.as && (s.aggregate === "sum" || s.aggregate === "avg" || (s.aggregate === "min" || s.aggregate === "max") && result.every((p) => p.out[s.as] === null || typeof p.out[s.as] === "number"))).map((s) => s.as));
4877
+ const byAlias = (out, a) => {
4878
+ const v = out[a];
4879
+ if (v === null || v === void 0) return zeroed.has(a) ? 0 : v;
4880
+ return !raw && labelled.has(a) ? out[`${a}${FORMATTED}`] ?? "" : v;
4881
+ };
4882
+ const keyed = result.map((p) => ({ p, keys: orders.map((o) => pick(p, o)) }));
4883
+ const kinds = orders.map((_, k) => kindOf(keyed.map((x) => x.keys[k])));
4884
+ keyed.sort((a, b) => {
4885
+ for (let k = 0; k < orders.length; k++) {
4886
+ const d = ordering(a.keys[k], b.keys[k], kinds[k]) * (orders[k].order.attrs.descending === "true" ? -1 : 1);
4887
+ if (d) return d;
4888
+ }
4889
+ return 0;
4890
+ });
4891
+ result = keyed.map((x) => x.p);
4892
+ }
4893
+ let moreRecords = false;
4894
+ if (fetch.attrs.count) {
4895
+ const count = Number(fetch.attrs.count), page = Number(fetch.attrs.page ?? "1");
4896
+ moreRecords = result.length > page * count;
4897
+ result = result.slice((page - 1) * count, page * count);
4898
+ }
4899
+ if (fetch.attrs.top) result = result.slice(0, Number(fetch.attrs.top));
4900
+ return { entities: result.map((p) => p.out), moreRecords };
4901
+ }
4902
+
4903
+ // ../../extension/src/sim/webApi.ts
4904
+ var asStored = (data) => Object.fromEntries(Object.entries(data).map(([k, v]) => [k, Object.prototype.toString.call(v) === "[object Date]" ? v.toISOString() : v]));
4905
+ function offlineWebApi(store, meta, onChange, onRead) {
4906
+ const notFound = (table, id) => Object.assign(new Error(`${table} with id ${id} was not found in the offline data`), { errorCode: -2147220969 });
4907
+ const api2 = {
4908
+ async retrieveRecord(table, id, options = "") {
4909
+ onRead?.(table);
4910
+ const r = store.get(table, id);
4911
+ if (!r) throw notFound(table, id);
4912
+ return store.webApi(table, r, /\$select=([^&]*)/.exec(options)?.[1]?.split(","));
4913
+ },
4914
+ async retrieveMultipleRecords(table, options = "") {
4915
+ onRead?.(table);
4916
+ const fetch = /^\?fetchXml=(.*)$/s.exec(options);
4917
+ if (fetch) {
4918
+ let xml;
4919
+ try {
4920
+ xml = decodeURIComponent(fetch[1]);
4921
+ } catch (e) {
4922
+ throw new Error(`?fetchXml= isn't URI-encoded properly (${e.message}).`);
4923
+ }
4924
+ const joined = new Set([...xml.matchAll(/<link-entity\b[^>]*?\sname\s*=\s*(["'])(.*?)\1/g)].map((m) => m[2]).filter((t) => t !== table));
4925
+ for (const t of joined) onRead?.(t);
4926
+ const answer = evaluateFetch(xml, (t) => store.all(t), meta);
4927
+ return { entities: answer.entities, ...answer.moreRecords ? { "@Microsoft.Dynamics.CRM.morerecords": true } : {} };
4928
+ }
4929
+ return { entities: store.query(table, options) };
4930
+ },
4931
+ async createRecord(table, data) {
4932
+ const id = store.create(table, asStored(data));
4933
+ onChange?.("create", table);
4934
+ return { entityType: table, id };
4935
+ },
4936
+ async updateRecord(table, id, data) {
4937
+ if (!store.get(table, id)) throw notFound(table, id);
4938
+ store.update(table, id, asStored(data));
4939
+ onChange?.("update", table);
4940
+ return { entityType: table, id };
4941
+ },
4942
+ async deleteRecord(table, id) {
4943
+ if (!store.get(table, id)) throw notFound(table, id);
4944
+ store.delete(table, id);
4945
+ onChange?.("delete", table);
4946
+ return { entityType: table, id };
4947
+ },
4948
+ online: {
4949
+ async executeMultiple(requests) {
4950
+ const one = async (r) => {
4951
+ const op = r.getMetadata?.().operationName;
4952
+ const missing = (what) => {
4953
+ throw new Error(`executeMultiple: ${what}.`);
4954
+ };
4955
+ if (op === "Create") return api2.createRecord(r.etn ?? missing("a Create request needs etn"), r.payload ?? {});
4956
+ if (op === "Update") return r.etn && r.id ? api2.updateRecord(r.etn, r.id, r.payload ?? {}) : missing("an Update request needs etn and id");
4957
+ if (op === "Delete") return r.entityReference?.entityType && r.entityReference.id ? api2.deleteRecord(r.entityReference.entityType, r.entityReference.id) : missing("a Delete request needs entityReference (entityType and id)");
4958
+ throw new Error(`executeMultiple: "${op}" isn't simulated offline.`);
4959
+ };
4960
+ const out = [];
4961
+ for (const item of requests) {
4962
+ if (!Array.isArray(item)) {
4963
+ out.push({ ok: true, ...await one(item) });
4964
+ continue;
4965
+ }
4966
+ const before = store.snapshot();
4967
+ try {
4968
+ for (const r of item) out.push({ ok: true, ...await one(r) });
4969
+ } catch (e) {
4970
+ store.restore(before);
4971
+ throw e;
4972
+ }
4973
+ }
4974
+ return out;
4975
+ }
4976
+ }
4977
+ };
4978
+ return api2;
4979
+ }
4980
+
4270
4981
  // ../../extension/src/sim/xrm.ts
4271
4982
  function createXrm(state, store, log, pkg, hooks, user) {
4272
4983
  const miss = (what) => log.add("notSimulated", what);
@@ -4469,38 +5180,43 @@ ${cn.comment}` : item.comment;
4469
5180
  throw e;
4470
5181
  }
4471
5182
  });
4472
- const notFound = (table, id) => Object.assign(new Error(`${table} with id ${id} was not found in the offline data`), { errorCode: -2147220969 });
5183
+ const offline = offlineWebApi(store, pkg.meta ?? {}, () => {
5184
+ if (hooks.counts) hooks.counts.changes++;
5185
+ });
4473
5186
  const xrm = g({
4474
5187
  WebApi: g({
4475
5188
  retrieveRecord: webApi("retrieveRecord", async (table, id, options = "") => {
4476
5189
  if (/\$expand/.test(options)) throw new NotSimulated("$expand");
4477
- const r = store.get(table, id);
4478
- if (!r) throw notFound(table, id);
5190
+ const r = await offline.retrieveRecord(table, id, options);
4479
5191
  log.add("xrm", `WebApi.retrieveRecord ${table} ${id}`);
4480
- const select = /\$select=([^&]*)/.exec(options)?.[1]?.split(",");
4481
- return store.webApi(table, r, select);
5192
+ return r;
4482
5193
  }),
4483
5194
  retrieveMultipleRecords: webApi("retrieveMultipleRecords", async (table, options = "") => {
4484
5195
  log.add("xrm", `WebApi.retrieveMultipleRecords ${table} ${options}`);
4485
- return { entities: store.query(table, options) };
5196
+ return offline.retrieveMultipleRecords(table, options);
4486
5197
  }),
4487
5198
  createRecord: async (table, data) => {
4488
- const id = store.create(table, data);
4489
- log.add("xrm", `WebApi.createRecord ${table} \u2192 ${id}`);
4490
- return { entityType: table, id };
5199
+ const r = await offline.createRecord(table, data);
5200
+ log.add("xrm", `WebApi.createRecord ${table} \u2192 ${r.id}`);
5201
+ return r;
4491
5202
  },
4492
5203
  updateRecord: async (table, id, data) => {
4493
- if (!store.get(table, id)) throw notFound(table, id);
4494
- store.update(table, id, data);
5204
+ const r = await offline.updateRecord(table, id, data);
4495
5205
  log.add("xrm", `WebApi.updateRecord ${table} ${id}`);
4496
- return { entityType: table, id };
5206
+ return r;
4497
5207
  },
4498
5208
  deleteRecord: async (table, id) => {
4499
- if (!store.get(table, id)) throw notFound(table, id);
4500
- store.delete(table, id);
5209
+ const r = await offline.deleteRecord(table, id);
4501
5210
  log.add("xrm", `WebApi.deleteRecord ${table} ${id}`);
4502
- return { entityType: table, id };
4503
- }
5211
+ return r;
5212
+ },
5213
+ online: g({
5214
+ executeMultiple: webApi("online.executeMultiple", async (requests) => {
5215
+ log.add("xrm", `WebApi.online.executeMultiple ${requests.length} request(s)`);
5216
+ if (hooks.counts && requests.some((r) => Array.isArray(r))) hooks.counts.transactions++;
5217
+ return offline.online.executeMultiple(requests);
5218
+ })
5219
+ }, "Xrm.WebApi.online")
4504
5220
  }, "Xrm.WebApi"),
4505
5221
  Navigation: g({
4506
5222
  openAlertDialog: async (a) => {
@@ -4549,23 +5265,23 @@ ${cn.comment}` : item.comment;
4549
5265
  throw new NotSimulated(`the handler parameters ${text}`);
4550
5266
  }
4551
5267
  }
4552
- var messageOf = (e) => e && typeof e === "object" && typeof e.message === "string" ? e.message : String(e);
5268
+ var messageOf2 = (e) => e && typeof e === "object" && typeof e.message === "string" ? e.message : String(e);
4553
5269
  var isPromise = (v) => !!v && typeof v.then === "function";
4554
5270
  var Simulator = class {
4555
5271
  constructor(pkg, host) {
4556
5272
  this.pkg = pkg;
4557
5273
  this.host = host;
4558
- const lookups = { [pkg.table]: pkg.columns.filter(isLookup).map((c) => c.name) };
5274
+ const lookups = { ...lookupColumnsOf(pkg.meta ?? {}), [pkg.table]: pkg.columns.filter(isLookup).map((c) => c.name) };
4559
5275
  this.store = new Store(pkg.tables, pkg.records, host.newId, lookups);
4560
5276
  this.state = new FormState(pkg);
4561
5277
  const rules = new RuleEngine(pkg.rules, this.state, this.log, {
4562
5278
  setValue: (field2, value) => {
4563
5279
  const col = this.state.columns.get(field2);
4564
5280
  const before = this.state.values.get(field2) ?? null;
4565
- const same = isEmpty(before) && isEmpty(value) || col !== void 0 && compare(col, before, value) === 0;
5281
+ const same2 = isEmpty(before) && isEmpty(value) || col !== void 0 && compare(col, before, value) === 0;
4566
5282
  this.state.values.set(field2, value);
4567
5283
  this.state.dirty.add(field2);
4568
- if (!same) rules.onChange(field2);
5284
+ if (!same2) rules.onChange(field2);
4569
5285
  }
4570
5286
  });
4571
5287
  this.rules = rules;
@@ -4574,7 +5290,8 @@ ${cn.comment}` : item.comment;
4574
5290
  save: () => this.save(),
4575
5291
  alert: () => {
4576
5292
  },
4577
- confirm: (text) => host.confirm ? host.confirm(text) : true
5293
+ confirm: (text) => host.confirm ? host.confirm(text) : true,
5294
+ counts: this.counts
4578
5295
  }, host.user ?? { id: "00000000-0000-0000-0000-000000000001", name: "Offline User" });
4579
5296
  this.Xrm = made.Xrm;
4580
5297
  this.formContext = made.formContext;
@@ -4592,6 +5309,7 @@ ${cn.comment}` : item.comment;
4592
5309
  context;
4593
5310
  attribute;
4594
5311
  pending = [];
5312
+ counts = { changes: 0, transactions: 0 };
4595
5313
  /** Waits for the promises handlers returned (WebApi calls), including ones those started. */
4596
5314
  async settle() {
4597
5315
  while (this.pending.length > 0) {
@@ -4606,7 +5324,7 @@ ${cn.comment}` : item.comment;
4606
5324
  e.logged = true;
4607
5325
  return;
4608
5326
  }
4609
- this.log.add("error", `${event}: ${name} threw ${messageOf(e)}`);
5327
+ this.log.add("error", `${event}: ${name} threw ${messageOf2(e)}`);
4610
5328
  }
4611
5329
  invoke(event, name, run) {
4612
5330
  try {
@@ -4642,6 +5360,11 @@ ${cn.comment}` : item.comment;
4642
5360
  this.state.changed();
4643
5361
  }
4644
5362
  async open(recordId) {
5363
+ if (this.host.scope) {
5364
+ const dql = this.host.scope.Dql;
5365
+ if (dql && typeof dql === "object") dql._local = true;
5366
+ watchProcedures(this.host.scope, this.log, () => this.counts.changes, () => this.counts.transactions);
5367
+ }
4645
5368
  for (const lib of this.pkg.libraries) {
4646
5369
  if (!lib.src) this.log.add("error", `library ${lib.name} isn't in the project (webresources/${lib.name})`);
4647
5370
  }
@@ -4734,7 +5457,9 @@ ${cn.comment}` : item.comment;
4734
5457
  }
4735
5458
  this.state.formNotifications.delete("rules");
4736
5459
  const values = {};
4737
- for (const [field2, v] of this.state.values) Object.assign(values, toRecord(this.state.columns.get(field2), v));
5460
+ for (const [field2, v] of this.state.values) {
5461
+ if (!this.state.recordId || this.state.dirty.has(field2)) Object.assign(values, toRecord(this.state.columns.get(field2), v));
5462
+ }
4738
5463
  if (this.state.recordId) this.store.update(this.pkg.table, this.state.recordId, values);
4739
5464
  else {
4740
5465
  this.state.recordId = this.store.create(this.pkg.table, values);
@@ -4801,9 +5526,15 @@ ${cn.comment}` : item.comment;
4801
5526
  for (const el of Array.from(document.querySelectorAll("[data-tests-status]"))) el.textContent = testsText;
4802
5527
  });
4803
5528
  }
4804
- function startPage(root, pkg, host, post) {
5529
+ function dataSource(records) {
5530
+ const sources = new Set((records ?? []).map((r) => r.source).filter((s) => !!s));
5531
+ if ([...sources].some((s) => / \(real data\)$/.test(s))) return "Using real data";
5532
+ return [...sources].some((s) => / \(anonymised\)$/.test(s)) ? "Using anonymised data" : "";
5533
+ }
5534
+ function startPage(root, pkg, host, post, offlineChanges) {
4805
5535
  listenForTestStatus();
4806
5536
  const sim = new Simulator(pkg, host);
5537
+ if (offlineChanges?.changed) sim.store.onChange(offlineChanges.changed);
4807
5538
  if (typeof window !== "undefined") {
4808
5539
  const w = window;
4809
5540
  w.__simXrm = sim.Xrm;
@@ -4826,9 +5557,11 @@ ${cn.comment}` : item.comment;
4826
5557
  button("copyTest", "Copy as test"),
4827
5558
  button("loadSeed", "Load from seed"),
4828
5559
  button("loadPulled", "Load pulled data"),
5560
+ button("saveChanges", "Save offline changes\u2026"),
4829
5561
  h("span", { class: "al-sizes", role: "group", "aria-label": "Screen size" }, ...SIZES.map((s) => h("button", { type: "button", "data-al-size": s.size, "aria-pressed": String(s.size === size) }, s.label))),
4830
5562
  h("span", { class: "al-themesource" }, typeof document !== "undefined" ? document.body.dataset.themeSource ?? "" : ""),
4831
5563
  h("span", { class: "sim-tests", "data-tests-status": "" }, testsText),
5564
+ h("span", { class: "sim-datasource", "data-sim-datasource": "" }, dataSource(pkg.records)),
4832
5565
  h("span", { class: "sim-note" }, "Offline: nothing is sent to Dataverse.")
4833
5566
  );
4834
5567
  root.replaceChildren(toolbar, h(
@@ -4959,7 +5692,7 @@ ${cn.comment}` : item.comment;
4959
5692
  };
4960
5693
  const restart = (id) => {
4961
5694
  const records = sim.store.written();
4962
- const next = startPage(root, { ...pkg, records, open: id }, host, post);
5695
+ const next = startPage(root, { ...pkg, records, open: id }, host, post, offlineChanges);
4963
5696
  page.sim = next.sim;
4964
5697
  page.recorder = next.recorder;
4965
5698
  };
@@ -4980,6 +5713,7 @@ ${cn.comment}` : item.comment;
4980
5713
  else if (action === "copyTest") post({ type: "copyTest", yaml: page.recorder.testYaml() });
4981
5714
  else if (action === "loadSeed") post({ type: "loadSeed" });
4982
5715
  else if (action === "loadPulled") post({ type: "loadPulled" });
5716
+ else if (action === "saveChanges") post({ type: "saveOfflineChanges", ...offlineChanges?.() });
4983
5717
  });
4984
5718
  draw();
4985
5719
  page.ready = sim.open().then(() => {
@@ -5010,6 +5744,7 @@ ${cn.comment}` : item.comment;
5010
5744
  return saved;
5011
5745
  },
5012
5746
  expand: (tab, expanded) => current().sim.setTabExpanded(tab, expanded),
5747
+ records: (table) => current().sim.store.all(table).map((r) => ({ ...r, values: Object.fromEntries(Object.entries(r.values).map(([k, v]) => [k, toWire(v)])) })),
5013
5748
  snapshot() {
5014
5749
  const { sim } = current();
5015
5750
  const fields = {};
@@ -5042,6 +5777,7 @@ ${cn.comment}` : item.comment;
5042
5777
  const post = (m) => vscode ? vscode.postMessage(m) : window.dispatchEvent(new CustomEvent("sim-post", { detail: m }));
5043
5778
  let n = 0;
5044
5779
  const host = {
5780
+ scope: window,
5045
5781
  resolve: (name) => {
5046
5782
  let v = window;
5047
5783
  for (const part of name.split(".")) v = v?.[part];
@@ -5051,12 +5787,30 @@ ${cn.comment}` : item.comment;
5051
5787
  newId: () => typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `00000000-0000-4000-8000-${String(++n).padStart(12, "0")}`,
5052
5788
  confirm: () => window.__simAnswers?.shift() ?? true
5053
5789
  };
5054
- let current = startPage(root, window.__simPackage, host, post);
5790
+ let loaded = [];
5791
+ const changes = () => {
5792
+ const now = current.sim.store.written();
5793
+ return { changes: changeSetOf(loaded, now, current.sim.pkg.meta), current: now, loaded };
5794
+ };
5795
+ changes.changed = () => post({ type: "offlineRows", ...changes() });
5796
+ let current = startPage(root, window.__simPackage, host, post, changes);
5797
+ loaded = window.__simPackage.loaded ?? current.sim.store.loadedRows();
5055
5798
  post({ type: "ready" });
5056
5799
  window.addEventListener("message", (e) => {
5057
5800
  const m = e.data;
5058
- if (m.type === "package" && m.pkg) current = startPage(root, m.pkg, host, post);
5059
- else if (m.type === "records" && m.records) current = startPage(root, { ...current.sim.pkg, records: m.records, open: void 0 }, host, post);
5801
+ if (m.type === "package" && m.pkg) {
5802
+ current = startPage(root, m.pkg, host, post, changes);
5803
+ loaded = m.pkg.loaded ?? current.sim.store.loadedRows();
5804
+ changes.changed?.();
5805
+ } else if (m.type === "records" && m.records) {
5806
+ current = startPage(root, { ...current.sim.pkg, records: m.records, loaded: void 0, open: void 0 }, host, post, changes);
5807
+ loaded = current.sim.store.loadedRows();
5808
+ changes.changed?.();
5809
+ } else if (m.type === "requestSave") post({ type: "saveOfflineChanges", ...changes() });
5810
+ else if (m.type === "offlineSaved") {
5811
+ loaded = m.rows ?? current.sim.store.written();
5812
+ changes.changed?.();
5813
+ }
5060
5814
  });
5061
5815
  window.__sim = () => current;
5062
5816
  window.__simAnswers ??= [];