@olenbetong/appframe-core 2.11.9 → 2.12.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 (97) hide show
  1. package/dist/esm/af.common.js +1979 -609
  2. package/dist/esm/af.common.legacy.js +1933 -609
  3. package/dist/esm/af.common.legacy.min.js +4 -3
  4. package/dist/esm/af.common.legacy.min.js.map +1 -7
  5. package/dist/esm/af.common.min.js +4 -3
  6. package/dist/esm/af.common.min.js.map +1 -7
  7. package/dist/iife/af.common.js +2140 -694
  8. package/dist/iife/af.common.legacy.js +2094 -694
  9. package/dist/iife/af.common.legacy.min.js +4 -3
  10. package/dist/iife/af.common.legacy.min.js.map +1 -7
  11. package/dist/iife/af.common.min.js +4 -3
  12. package/dist/iife/af.common.min.js.map +1 -7
  13. package/es/alert.js +16 -1
  14. package/es/filter/convertFilter.d.ts +23 -0
  15. package/es/filter/convertFilter.js +26 -0
  16. package/es/filter/describeFilter.d.ts +13 -0
  17. package/es/filter/describeFilter.js +60 -0
  18. package/es/filter/describeFilter.test.d.ts +1 -0
  19. package/es/filter/describeFilter.test.js +68 -0
  20. package/es/filter/fields.d.ts +28 -0
  21. package/es/filter/fields.js +37 -0
  22. package/es/filter/fields.test.d.ts +1 -0
  23. package/es/filter/fields.test.js +49 -0
  24. package/es/filter/index.d.ts +8 -0
  25. package/es/filter/index.js +7 -0
  26. package/es/filter/operators.d.ts +37 -0
  27. package/es/filter/operators.js +229 -0
  28. package/es/filter/operators.test.d.ts +1 -0
  29. package/es/filter/operators.test.js +106 -0
  30. package/es/filter/savedFilters.d.ts +111 -0
  31. package/es/filter/savedFilters.js +118 -0
  32. package/es/filter/savedFilters.test.d.ts +1 -0
  33. package/es/filter/savedFilters.test.js +108 -0
  34. package/es/filter/standardLayout.d.ts +18 -0
  35. package/es/filter/standardLayout.js +55 -0
  36. package/es/filter/standardLayout.test.d.ts +1 -0
  37. package/es/filter/standardLayout.test.js +66 -0
  38. package/es/filter/tree.d.ts +70 -0
  39. package/es/filter/tree.js +185 -0
  40. package/es/filter/tree.test.d.ts +1 -0
  41. package/es/filter/tree.test.js +184 -0
  42. package/es/filter/types.d.ts +73 -0
  43. package/es/filter/types.js +1 -0
  44. package/es/index.d.ts +2 -0
  45. package/es/index.js +4 -2
  46. package/es/parseFunc.js +19 -2
  47. package/es/parseFunc.test.js +48 -4
  48. package/es/report/index.d.ts +6 -0
  49. package/es/report/index.js +5 -0
  50. package/es/report/parameterDefaults.d.ts +26 -0
  51. package/es/report/parameterDefaults.js +77 -0
  52. package/es/report/parameters.d.ts +46 -0
  53. package/es/report/parameters.js +188 -0
  54. package/es/report/parameters.test.d.ts +1 -0
  55. package/es/report/parameters.test.js +161 -0
  56. package/es/report/recordSource.d.ts +30 -0
  57. package/es/report/recordSource.js +105 -0
  58. package/es/report/render.d.ts +81 -0
  59. package/es/report/render.js +219 -0
  60. package/es/report/render.test.d.ts +1 -0
  61. package/es/report/render.test.js +144 -0
  62. package/es/report/report.d.ts +16 -0
  63. package/es/report/report.js +50 -0
  64. package/es/report/report.test.d.ts +1 -0
  65. package/es/report/report.test.js +86 -0
  66. package/es/report/types.d.ts +124 -0
  67. package/es/report/types.js +8 -0
  68. package/package.json +7 -7
  69. package/src/alert.ts +16 -1
  70. package/src/filter/convertFilter.ts +47 -0
  71. package/src/filter/describeFilter.test.ts +103 -0
  72. package/src/filter/describeFilter.ts +79 -0
  73. package/src/filter/fields.test.ts +58 -0
  74. package/src/filter/fields.ts +56 -0
  75. package/src/filter/index.ts +62 -0
  76. package/src/filter/operators.test.ts +136 -0
  77. package/src/filter/operators.ts +252 -0
  78. package/src/filter/savedFilters.test.ts +145 -0
  79. package/src/filter/savedFilters.ts +192 -0
  80. package/src/filter/standardLayout.test.ts +88 -0
  81. package/src/filter/standardLayout.ts +65 -0
  82. package/src/filter/tree.test.ts +258 -0
  83. package/src/filter/tree.ts +238 -0
  84. package/src/filter/types.ts +146 -0
  85. package/src/index.ts +3 -1
  86. package/src/parseFunc.test.ts +61 -4
  87. package/src/parseFunc.ts +29 -2
  88. package/src/report/index.ts +37 -0
  89. package/src/report/parameterDefaults.ts +101 -0
  90. package/src/report/parameters.test.ts +218 -0
  91. package/src/report/parameters.ts +230 -0
  92. package/src/report/recordSource.ts +123 -0
  93. package/src/report/render.test.ts +230 -0
  94. package/src/report/render.ts +269 -0
  95. package/src/report/report.test.ts +104 -0
  96. package/src/report/report.ts +51 -0
  97. package/src/report/types.ts +135 -0
@@ -1,515 +1,1915 @@
1
- // ../../node_modules/.pnpm/mitt@3.0.1/node_modules/mitt/dist/mitt.mjs
1
+ //#region ../../node_modules/.pnpm/mitt@3.0.1/node_modules/mitt/dist/mitt.mjs
2
2
  function mitt_default(n) {
3
- return { all: n = n || /* @__PURE__ */ new Map(), on: function(t, e) {
4
- var i = n.get(t);
5
- i ? i.push(e) : n.set(t, [e]);
6
- }, off: function(t, e) {
7
- var i = n.get(t);
8
- i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
9
- }, emit: function(t, e) {
10
- var i = n.get(t);
11
- i && i.slice().map(function(n2) {
12
- n2(e);
13
- }), (i = n.get("*")) && i.slice().map(function(n2) {
14
- n2(t, e);
15
- });
16
- } };
17
- }
18
-
19
- // src/SessionHandler.ts
3
+ return {
4
+ all: n = n || /* @__PURE__ */ new Map(),
5
+ on: function(t, e) {
6
+ var i = n.get(t);
7
+ i ? i.push(e) : n.set(t, [e]);
8
+ },
9
+ off: function(t, e) {
10
+ var i = n.get(t);
11
+ i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
12
+ },
13
+ emit: function(t, e) {
14
+ var i = n.get(t);
15
+ i && i.slice().map(function(n) {
16
+ n(e);
17
+ }), (i = n.get("*")) && i.slice().map(function(n) {
18
+ n(t, e);
19
+ });
20
+ }
21
+ };
22
+ }
23
+
24
+ //#endregion
25
+ //#region \0@oxc-project+runtime@0.143.0/helpers/esm/typeof.js
26
+ function _typeof(o) {
27
+ "@babel/helpers - typeof";
28
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
29
+ return typeof o;
30
+ } : function(o) {
31
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
32
+ }, _typeof(o);
33
+ }
34
+
35
+ //#endregion
36
+ //#region \0@oxc-project+runtime@0.143.0/helpers/esm/toPrimitive.js
37
+ function toPrimitive(t, r) {
38
+ if ("object" != _typeof(t) || !t) return t;
39
+ var e = t[Symbol.toPrimitive];
40
+ if (void 0 !== e) {
41
+ var i = e.call(t, r || "default");
42
+ if ("object" != _typeof(i)) return i;
43
+ throw new TypeError("@@toPrimitive must return a primitive value.");
44
+ }
45
+ return ("string" === r ? String : Number)(t);
46
+ }
47
+
48
+ //#endregion
49
+ //#region \0@oxc-project+runtime@0.143.0/helpers/esm/toPropertyKey.js
50
+ function toPropertyKey(t) {
51
+ var i = toPrimitive(t, "string");
52
+ return "symbol" == _typeof(i) ? i : i + "";
53
+ }
54
+
55
+ //#endregion
56
+ //#region \0@oxc-project+runtime@0.143.0/helpers/esm/defineProperty.js
57
+ function _defineProperty(e, r, t) {
58
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
59
+ value: t,
60
+ enumerable: !0,
61
+ configurable: !0,
62
+ writable: !0
63
+ }) : e[r] = t, e;
64
+ }
65
+
66
+ //#endregion
67
+ //#region src/SessionHandler.ts
20
68
  var SessionHandler = class {
21
- eventHandler = mitt_default();
22
- authenticated() {
23
- this.eventHandler.emit("onAuthenticated");
24
- }
25
- async expired(callback, type) {
26
- try {
27
- let authPromise = new Promise((resolve) => {
28
- let eventHandler = () => {
29
- this.eventHandler.off("onAuthenticated", eventHandler);
30
- callback?.();
31
- resolve();
32
- };
33
- this.eventHandler.on("onAuthenticated", eventHandler);
34
- });
35
- let dialog = document.querySelector("dialog.session-expired-dialog");
36
- if (!dialog) {
37
- dialog = document.createElement("dialog");
38
- dialog.className = "session-expired-dialog";
39
- dialog.style.display = "flex";
40
- dialog.style.padding = "0";
41
- dialog.style.left = "50%";
42
- dialog.style.transform = "translateX(-50%)";
43
- let link = "/login?ReturnUrl=%2fapi/sessionexpired/remove";
44
- if (type !== "RequireTwoFactor") {
45
- await fetch("/logout", { method: "POST" });
46
- } else {
47
- link = "/login?RequireTwoFactor=1&ReturnUrl=%2fapi/sessionexpired/remove";
48
- }
49
- dialog.innerHTML = `<iframe sandbox="allow-same-origin allow-scripts allow-modals allow-top-navigation-by-user-activation allow-forms" src="${link}" style="border:0;width:min(500px,100vw);height:min(700px, 100vh);"></iframe>`;
50
- document.body.append(dialog);
51
- dialog.showModal();
52
- await authPromise;
53
- dialog.remove();
54
- } else {
55
- await authPromise;
56
- }
57
- } catch (_) {
58
- window.location.href = `/login?ReturnUrl=${encodeURIComponent(window.location.pathname)}${encodeURIComponent(
59
- window.location.search
60
- )}`;
61
- }
62
- }
63
- attachEvent(eventName, handler) {
64
- return this.eventHandler.on(eventName, handler);
65
- }
66
- detachEvent(eventName, handler) {
67
- return this.eventHandler.off(eventName, handler);
68
- }
69
+ constructor() {
70
+ _defineProperty(this, "eventHandler", mitt_default());
71
+ }
72
+ authenticated() {
73
+ this.eventHandler.emit("onAuthenticated");
74
+ }
75
+ async expired(callback, type) {
76
+ try {
77
+ let authPromise = new Promise((resolve) => {
78
+ let eventHandler = () => {
79
+ this.eventHandler.off("onAuthenticated", eventHandler);
80
+ callback?.();
81
+ resolve();
82
+ };
83
+ this.eventHandler.on("onAuthenticated", eventHandler);
84
+ });
85
+ let dialog = document.querySelector("dialog.session-expired-dialog");
86
+ if (!dialog) {
87
+ dialog = document.createElement("dialog");
88
+ dialog.className = "session-expired-dialog";
89
+ dialog.style.display = "flex";
90
+ dialog.style.padding = "0";
91
+ dialog.style.left = "50%";
92
+ dialog.style.transform = "translateX(-50%)";
93
+ let link = "/login?ReturnUrl=%2fapi/sessionexpired/remove";
94
+ if (type !== "RequireTwoFactor") await fetch("/logout", { method: "POST" });
95
+ else link = "/login?RequireTwoFactor=1&ReturnUrl=%2fapi/sessionexpired/remove";
96
+ dialog.innerHTML = `<iframe sandbox="allow-same-origin allow-scripts allow-modals allow-top-navigation-by-user-activation allow-forms" src="${link}" style="border:0;width:min(500px,100vw);height:min(700px, 100vh);"></iframe>`;
97
+ document.body.append(dialog);
98
+ dialog.showModal();
99
+ await authPromise;
100
+ dialog.remove();
101
+ } else await authPromise;
102
+ } catch (_) {
103
+ window.location.href = `/login?ReturnUrl=${encodeURIComponent(window.location.pathname)}${encodeURIComponent(window.location.search)}`;
104
+ }
105
+ }
106
+ attachEvent(eventName, handler) {
107
+ return this.eventHandler.on(eventName, handler);
108
+ }
109
+ detachEvent(eventName, handler) {
110
+ return this.eventHandler.off(eventName, handler);
111
+ }
69
112
  };
70
113
 
71
- // src/UserSession.ts
114
+ //#endregion
115
+ //#region src/UserSession.ts
72
116
  var UserSession = class extends SessionHandler {
73
- amDesignator = "a.m.";
74
- dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
75
- dayNamesShort = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
76
- decimalSeparator = ".";
77
- domain = "OB";
78
- email;
79
- formats;
80
- groupSeparator = null;
81
- integratedSecurity = false;
82
- isDeveloper = false;
83
- login = "";
84
- loginType;
85
- monthNames = [
86
- "january",
87
- "february",
88
- "march",
89
- "april",
90
- "may",
91
- "june",
92
- "july",
93
- "august",
94
- "september",
95
- "october",
96
- "november",
97
- "december",
98
- ""
99
- ];
100
- monthNamesShort = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "augt", "sep", "oct", "nov", "dec", ""];
101
- name;
102
- pmDesignator = "p.m.";
103
- shortDateFormat = "dd.MM.yyyy";
104
- culture = "en-GB";
105
- uiculture = "en-GB";
106
- constructor(userData) {
107
- super();
108
- this.formats = {};
109
- Object.assign(this, userData);
110
- }
117
+ constructor(userData) {
118
+ super();
119
+ _defineProperty(this, "amDesignator", "a.m.");
120
+ _defineProperty(this, "dayNames", [
121
+ "sunday",
122
+ "monday",
123
+ "tuesday",
124
+ "wednesday",
125
+ "thursday",
126
+ "friday",
127
+ "saturday"
128
+ ]);
129
+ _defineProperty(this, "dayNamesShort", [
130
+ "sun",
131
+ "mon",
132
+ "tue",
133
+ "wed",
134
+ "thu",
135
+ "fri",
136
+ "sat"
137
+ ]);
138
+ _defineProperty(this, "decimalSeparator", ".");
139
+ _defineProperty(this, "domain", "OB");
140
+ _defineProperty(this, "email", void 0);
141
+ _defineProperty(this, "formats", void 0);
142
+ _defineProperty(this, "groupSeparator", null);
143
+ _defineProperty(this, "integratedSecurity", false);
144
+ _defineProperty(this, "isDeveloper", false);
145
+ _defineProperty(this, "login", "");
146
+ _defineProperty(this, "loginType", void 0);
147
+ _defineProperty(this, "monthNames", [
148
+ "january",
149
+ "february",
150
+ "march",
151
+ "april",
152
+ "may",
153
+ "june",
154
+ "july",
155
+ "august",
156
+ "september",
157
+ "october",
158
+ "november",
159
+ "december",
160
+ ""
161
+ ]);
162
+ _defineProperty(this, "monthNamesShort", [
163
+ "jan",
164
+ "feb",
165
+ "mar",
166
+ "apr",
167
+ "may",
168
+ "jun",
169
+ "jul",
170
+ "augt",
171
+ "sep",
172
+ "oct",
173
+ "nov",
174
+ "dec",
175
+ ""
176
+ ]);
177
+ _defineProperty(this, "name", void 0);
178
+ _defineProperty(this, "pmDesignator", "p.m.");
179
+ _defineProperty(this, "shortDateFormat", "dd.MM.yyyy");
180
+ _defineProperty(this, "culture", "en-GB");
181
+ _defineProperty(this, "uiculture", "en-GB");
182
+ this.formats = {};
183
+ Object.assign(this, userData);
184
+ }
111
185
  };
112
186
 
113
- // src/log.ts
114
- var article = window.af?.article?.id ?? window.window?.location.pathname.substring(1).split("/")[0];
187
+ //#endregion
188
+ //#region src/log.ts
189
+ const article = window.af?.article?.id ?? window.window?.location.pathname.substring(1).split("/")[0];
190
+ /**
191
+ * Logs an activity to the website activity log
192
+ *
193
+ * @param activity name of the activity we are logging
194
+ * @param parameters A dictionary of parameters used when doing the activity
195
+ * @param timeElapsed Number of milliseconds elapsed while executing
196
+ */
115
197
  async function logActivity(activity, parameters = {}, timeElapsed = 0) {
116
- try {
117
- let response = await fetch("/api/logging/log-activity", {
118
- method: "POST",
119
- body: JSON.stringify({
120
- article,
121
- timeElapsed,
122
- action: activity,
123
- parameters: {
124
- ...parameters,
125
- _session: getSessionData()
126
- }
127
- }),
128
- headers: { "Content-Type": "application/json", Accept: "application/json" }
129
- });
130
- if (!response.ok) {
131
- if (response.headers.get("Content-Type")?.includes("application/json")) {
132
- let data = await response.json();
133
- console.error(data.error);
134
- } else {
135
- console.error(`${response.status} ${response.statusText}`);
136
- }
137
- }
138
- } catch {
139
- }
198
+ try {
199
+ let response = await fetch("/api/logging/log-activity", {
200
+ method: "POST",
201
+ body: JSON.stringify({
202
+ article,
203
+ timeElapsed,
204
+ action: activity,
205
+ parameters: {
206
+ ...parameters,
207
+ _session: getSessionData()
208
+ }
209
+ }),
210
+ headers: {
211
+ "Content-Type": "application/json",
212
+ Accept: "application/json"
213
+ }
214
+ });
215
+ if (!response.ok) {
216
+ if (response.headers.get("Content-Type")?.includes("application/json")) {
217
+ let data = await response.json();
218
+ console.error(data.error);
219
+ } else console.error(`${response.status} ${response.statusText}`);
220
+ }
221
+ } catch {}
140
222
  }
223
+ /**
224
+ * Records the current time, and returns a function that logs the activity with the
225
+ * time elapsed when it is called.
226
+ *
227
+ * @param activity Name of the activity we are logging
228
+ * @param parameters A dictionary of parameters used when doing the activity
229
+ * @returns A function that should be called when the activity is completed to log it to the website log
230
+ */
141
231
  function startActivity(activity, startParameters = {}) {
142
- let start = performance.now();
143
- return (endParameters = {}) => logActivity(activity, { ...startParameters, ...endParameters }, performance.now() - start);
232
+ let start = performance.now();
233
+ return (endParameters = {}) => logActivity(activity, {
234
+ ...startParameters,
235
+ ...endParameters
236
+ }, performance.now() - start);
144
237
  }
238
+ /**
239
+ * Records the time used to execute an operation and returns the value of the operation and the time
240
+ * in milliseconds
241
+ */
145
242
  async function time(callback) {
146
- let start = performance.now();
147
- let returnValue = await callback();
148
- return [returnValue, performance.now() - start];
243
+ let start = performance.now();
244
+ return [await callback(), performance.now() - start];
149
245
  }
150
246
  async function logError(error) {
151
- try {
152
- if (!error) return;
153
- let data = typeof error === "string" ? { error } : typeof error === "object" ? "message" in error ? {
154
- error: error.message,
155
- stack: error.stack ?? null
156
- } : { error: error.toString() } : { error: "Unspecified error" };
157
- console.error(error);
158
- let result = await fetch("/data/Logger/LogError", {
159
- method: "POST",
160
- body: JSON.stringify(data),
161
- headers: {
162
- "Content-Type": "application/json; charset=utf-8"
163
- }
164
- });
165
- if (result.ok) {
166
- return await result.json();
167
- }
168
- console.error(Error("Failed to log error"));
169
- } catch {
170
- }
247
+ try {
248
+ if (!error) return;
249
+ let data = typeof error === "string" ? { error } : typeof error === "object" ? "message" in error ? {
250
+ error: error.message,
251
+ stack: error.stack ?? null
252
+ } : { error: error.toString() } : { error: "Unspecified error" };
253
+ console.error(error);
254
+ let result = await fetch("/data/Logger/LogError", {
255
+ method: "POST",
256
+ body: JSON.stringify(data),
257
+ headers: { "Content-Type": "application/json; charset=utf-8" }
258
+ });
259
+ if (result.ok) return await result.json();
260
+ console.error(Error("Failed to log error"));
261
+ } catch {}
171
262
  }
172
263
  function getSessionId() {
173
- return crypto.randomUUID?.();
264
+ return crypto.randomUUID?.();
174
265
  }
175
- var sessionStart = Date.now();
176
- var sessionId = getSessionId();
177
- var deviceId = "";
178
- var browserSessionId = "";
266
+ let sessionStart = Date.now();
267
+ let sessionId = getSessionId();
268
+ let deviceId = "";
269
+ let browserSessionId = "";
179
270
  if ("document" in window) {
180
- let startSession = () => logActivity("AfSessionInit", {
181
- "appframe-core": window.af?.common?.version,
182
- "appframe-data": window.af?.data?.version,
183
- "app-version": window.af?.article?.version
184
- });
185
- document.addEventListener("DOMContentLoaded", () => {
186
- deviceId = localStorage.getItem("_afDeviceId");
187
- browserSessionId = sessionStorage.getItem("_afSessionId");
188
- if (!deviceId) {
189
- deviceId = getSessionId();
190
- localStorage.setItem("_afDeviceId", deviceId);
191
- }
192
- if (!browserSessionId) {
193
- browserSessionId = sessionId;
194
- sessionStorage.setItem("_afSessionId", browserSessionId);
195
- }
196
- startSession();
197
- });
198
- document.addEventListener("visibilitychange", function logData() {
199
- if (document.visibilityState === "hidden") {
200
- navigator.sendBeacon(
201
- "/api/logging/log-activity",
202
- JSON.stringify({
203
- article,
204
- action: "AfSessionEnd",
205
- parameters: {
206
- _session: getSessionData()
207
- }
208
- })
209
- );
210
- } else {
211
- startSession();
212
- }
213
- });
271
+ let startSession = () => logActivity("AfSessionInit", {
272
+ "appframe-core": window.af?.common?.version,
273
+ "appframe-data": window.af?.data?.version,
274
+ "app-version": window.af?.article?.version
275
+ });
276
+ document.addEventListener("DOMContentLoaded", () => {
277
+ deviceId = localStorage.getItem("_afDeviceId");
278
+ browserSessionId = sessionStorage.getItem("_afSessionId");
279
+ if (!deviceId) {
280
+ deviceId = getSessionId();
281
+ localStorage.setItem("_afDeviceId", deviceId);
282
+ }
283
+ if (!browserSessionId) {
284
+ browserSessionId = sessionId;
285
+ sessionStorage.setItem("_afSessionId", browserSessionId);
286
+ }
287
+ startSession();
288
+ });
289
+ document.addEventListener("visibilitychange", function logData() {
290
+ if (document.visibilityState === "hidden") navigator.sendBeacon("/api/logging/log-activity", JSON.stringify({
291
+ article,
292
+ action: "AfSessionEnd",
293
+ parameters: { _session: getSessionData() }
294
+ }));
295
+ else startSession();
296
+ });
214
297
  }
215
298
  function getSessionData() {
216
- return {
217
- browserSessionId,
218
- sessionStart,
219
- sessionLength: Date.now() - sessionStart,
220
- sessionId,
221
- deviceId
222
- };
223
- }
224
-
225
- // src/errorHandler.ts
226
- if (true) {
227
- window.window?.addEventListener("error", (event) => {
228
- if (typeof event === "object" && "error" in event) {
229
- logError(event.error);
230
- } else if (typeof event === "object" && "message" in event) {
231
- logError(event);
232
- }
233
- });
234
- }
235
-
236
- // src/localStorage.ts
299
+ return {
300
+ browserSessionId,
301
+ sessionStart,
302
+ sessionLength: Date.now() - sessionStart,
303
+ sessionId,
304
+ deviceId
305
+ };
306
+ }
307
+
308
+ //#endregion
309
+ //#region src/errorHandler.ts
310
+ window.window?.addEventListener("error", (event) => {
311
+ if (typeof event === "object" && "error" in event) logError(event.error);
312
+ else if (typeof event === "object" && "message" in event) logError(event);
313
+ });
314
+
315
+ //#endregion
316
+ //#region src/localStorage.ts
237
317
  function getLocalKey(key) {
238
- return [af?.article?.id || "", "common", key].join(".");
318
+ return [
319
+ af?.article?.id || "",
320
+ "common",
321
+ key
322
+ ].join(".");
239
323
  }
240
324
  var LocalStorage = class {
241
- isPersisted = () => true;
242
- getLocalStorageKey(key, global) {
243
- return global ? ["common", key].join(".") : getLocalKey(key);
244
- }
245
- get(key, defaultValue, global) {
246
- const lsKey = this.getLocalStorageKey(key, global);
247
- const value = localStorage.getItem(lsKey);
248
- return value !== null ? JSON.parse(value) : defaultValue;
249
- }
250
- set(key, value, global) {
251
- localStorage.setItem(this.getLocalStorageKey(key, global), JSON.stringify(value));
252
- }
253
- remove(key, global) {
254
- const lsKey = this.getLocalStorageKey(key, global);
255
- if (localStorage.getItem(lsKey) !== null) {
256
- localStorage.removeItem(lsKey);
257
- return true;
258
- } else {
259
- return false;
260
- }
261
- }
262
- clear() {
263
- const baseKey = getLocalKey("");
264
- for (let key in localStorage) {
265
- if (key.slice(0, baseKey.length) === baseKey) {
266
- localStorage.removeItem(key);
267
- }
268
- }
269
- }
325
+ constructor() {
326
+ _defineProperty(this, "isPersisted", () => true);
327
+ }
328
+ getLocalStorageKey(key, global) {
329
+ return global ? ["common", key].join(".") : getLocalKey(key);
330
+ }
331
+ get(key, defaultValue, global) {
332
+ const lsKey = this.getLocalStorageKey(key, global);
333
+ const value = localStorage.getItem(lsKey);
334
+ return value !== null ? JSON.parse(value) : defaultValue;
335
+ }
336
+ set(key, value, global) {
337
+ localStorage.setItem(this.getLocalStorageKey(key, global), JSON.stringify(value));
338
+ }
339
+ remove(key, global) {
340
+ const lsKey = this.getLocalStorageKey(key, global);
341
+ if (localStorage.getItem(lsKey) !== null) {
342
+ localStorage.removeItem(lsKey);
343
+ return true;
344
+ } else return false;
345
+ }
346
+ clear() {
347
+ const baseKey = getLocalKey("");
348
+ for (let key in localStorage) if (key.slice(0, baseKey.length) === baseKey) localStorage.removeItem(key);
349
+ }
270
350
  };
271
351
  var localStorage_default = new LocalStorage();
272
352
 
273
- // src/date.ts
353
+ //#endregion
354
+ //#region src/date.ts
274
355
  function toLocalISODate(date) {
275
- return date ? toLocalISODateTime(date).substring(0, 10) : null;
356
+ return date ? toLocalISODateTime(date).substring(0, 10) : null;
276
357
  }
277
358
  function pad(num, digits = 2) {
278
- return String(num).padStart(digits, "0");
359
+ return String(num).padStart(digits, "0");
279
360
  }
280
361
  function toLocalISODateTime(date) {
281
- return date ? `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(
282
- date.getMinutes()
283
- )}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}` : null;
362
+ return date ? `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}` : null;
284
363
  }
364
+ /**
365
+ * Converts a date object to a string compatible with input type datetime-local.
366
+ * Will handle the UTC value of the date as if it was local, to be compatible with
367
+ * data objects.
368
+ *
369
+ * If null or undefined is passed, returns an empty string.
370
+ *
371
+ * @param date
372
+ */
285
373
  function toLocalDateTime(date) {
286
- return date ? date.toISOString().substring(0, 16) : "";
374
+ return date ? date.toISOString().substring(0, 16) : "";
287
375
  }
288
376
 
289
- // src/downloadBlob.ts
377
+ //#endregion
378
+ //#region src/downloadBlob.ts
290
379
  function downloadBlob(blob, fileName) {
291
- return new Promise((resolve, reject) => {
292
- try {
293
- const url = URL.createObjectURL(blob);
294
- const parent = document.body;
295
- const anchor = document.createElement("a");
296
- anchor.setAttribute("download", fileName);
297
- anchor.href = url;
298
- parent.append(anchor);
299
- anchor.click();
300
- parent.removeChild(anchor);
301
- setTimeout(() => {
302
- URL.revokeObjectURL(url);
303
- resolve();
304
- }, 250);
305
- } catch (ex) {
306
- reject(ex);
307
- }
308
- });
309
- }
310
-
311
- // src/invariant.ts
380
+ return new Promise((resolve, reject) => {
381
+ try {
382
+ const url = URL.createObjectURL(blob);
383
+ const parent = document.body;
384
+ const anchor = document.createElement("a");
385
+ anchor.setAttribute("download", fileName);
386
+ anchor.href = url;
387
+ parent.append(anchor);
388
+ anchor.click();
389
+ parent.removeChild(anchor);
390
+ setTimeout(() => {
391
+ URL.revokeObjectURL(url);
392
+ resolve();
393
+ }, 250);
394
+ } catch (ex) {
395
+ reject(ex);
396
+ }
397
+ });
398
+ }
399
+
400
+ //#endregion
401
+ //#region src/invariant.ts
402
+ /**
403
+ * Throws an error if the condition is falsy. The provided message is used as the error message.
404
+ * A function can be provided to lazily generate the message.
405
+ *
406
+ * @param {any} condition
407
+ * @param {string | (() => string)} [message]
408
+ * @returns {void}
409
+ */
312
410
  function invariant(condition, message) {
313
- if (condition) {
314
- return;
315
- }
316
- const provided = typeof message === "function" ? message() : message;
317
- throw new Error(provided ?? "Invariant failed");
411
+ if (condition) return;
412
+ const provided = typeof message === "function" ? message() : message;
413
+ throw new Error(provided ?? "Invariant failed");
318
414
  }
319
415
 
320
- // src/downloadRequest.ts
416
+ //#endregion
417
+ //#region src/downloadRequest.ts
321
418
  async function downloadRequest(request, { fileName, signal, onProgress }) {
322
- let bytesReceived = 0;
323
- onProgress?.({ status: "requested" });
324
- try {
325
- let response = await fetch(request);
326
- if (!response.ok || !response.body) {
327
- if (response.headers.get("content-type")?.includes("application/json")) {
328
- let data = await response.json();
329
- invariant(!data.error, data.error);
330
- }
331
- throw new Error(`${response.status} ${response.statusText}`);
332
- }
333
- try {
334
- const reader = response.body.getReader();
335
- const stream = new ReadableStream({
336
- start: (controller) => {
337
- function pump() {
338
- return reader.read().then((read) => {
339
- if (read.done) {
340
- controller.close();
341
- return;
342
- }
343
- bytesReceived += read.value.length;
344
- onProgress?.({ bytesReceived, status: "downloading" });
345
- controller.enqueue(read.value);
346
- return pump();
347
- });
348
- }
349
- return pump();
350
- }
351
- });
352
- response = new Response(stream);
353
- } catch {
354
- }
355
- const blob = await response.blob();
356
- onProgress?.({ bytesReceived, status: "downloaded" });
357
- await downloadBlob(blob, fileName);
358
- onProgress?.({ bytesReceived, status: "completed" });
359
- } catch (err) {
360
- if (signal?.aborted) {
361
- onProgress?.({ status: "cancelled" });
362
- } else {
363
- onProgress?.({ error: err.message, status: "error" });
364
- }
365
- }
366
- }
367
-
368
- // src/parseFunc.ts
369
- var funcRegex = /^function(?:\s+([a-zA-Z$_][a-zA-Z0-9$_]*))?\s*\(((?:(?:\s*[a-zA-Z$_][a-zA-Z0-9$_]*)(?:\s*,\s*[a-zA-Z$_][a-zA-Z0-9$_]*)*)?)\s*\)\s*\{((?:.|\n|\r)*)\}$/;
370
- function parseFunc(func) {
371
- const match = func.toString().match(funcRegex);
372
- invariant(match, "Unable to parse function!");
373
- return { name: func.name ?? match[1], args: match[2].split(",").map((a) => a.trim()), body: match[3] };
419
+ let bytesReceived = 0;
420
+ onProgress?.({ status: "requested" });
421
+ try {
422
+ let response = await fetch(request);
423
+ if (!response.ok || !response.body) {
424
+ if (response.headers.get("content-type")?.includes("application/json")) {
425
+ let data = await response.json();
426
+ invariant(!data.error, data.error);
427
+ }
428
+ throw new Error(`${response.status} ${response.statusText}`);
429
+ }
430
+ try {
431
+ const reader = response.body.getReader();
432
+ const stream = new ReadableStream({ start: (controller) => {
433
+ function pump() {
434
+ return reader.read().then((read) => {
435
+ if (read.done) {
436
+ controller.close();
437
+ return;
438
+ }
439
+ bytesReceived += read.value.length;
440
+ onProgress?.({
441
+ bytesReceived,
442
+ status: "downloading"
443
+ });
444
+ controller.enqueue(read.value);
445
+ return pump();
446
+ });
447
+ }
448
+ return pump();
449
+ } });
450
+ response = new Response(stream);
451
+ } catch {}
452
+ const blob = await response.blob();
453
+ onProgress?.({
454
+ bytesReceived,
455
+ status: "downloaded"
456
+ });
457
+ await downloadBlob(blob, fileName);
458
+ onProgress?.({
459
+ bytesReceived,
460
+ status: "completed"
461
+ });
462
+ } catch (err) {
463
+ if (signal?.aborted) onProgress?.({ status: "cancelled" });
464
+ else onProgress?.({
465
+ error: err.message,
466
+ status: "error"
467
+ });
468
+ }
374
469
  }
375
470
 
376
- // src/Namespace.ts
377
- function Namespace() {
471
+ //#endregion
472
+ //#region src/parseFunc.ts
473
+ const funcRegex = /^function(?:\s+([a-zA-Z$_][a-zA-Z0-9$_]*))?\s*\(((?:(?:\s*[a-zA-Z$_][a-zA-Z0-9$_]*)(?:\s*,\s*[a-zA-Z$_][a-zA-Z0-9$_]*)*)?)\s*\)\s*\{((?:.|\n|\r)*)\}$/;
474
+ const arrowBlockRegex = /^(?:\(([^)]*)\)|([a-zA-Z$_][a-zA-Z0-9$_]*))\s*=>\s*\{([\s\S]*)\}$/;
475
+ const arrowExpressionRegex = /^(?:\(([^)]*)\)|([a-zA-Z$_][a-zA-Z0-9$_]*))\s*=>\s*([\s\S]+)$/;
476
+ const parseArguments = (args) => args.split(",").map((a) => a.trim()).filter(Boolean);
477
+ function parseFunc(func) {
478
+ const funcString = func.toString();
479
+ const arrowBlockMatch = funcString.match(arrowBlockRegex);
480
+ if (arrowBlockMatch) {
481
+ const args = parseArguments(arrowBlockMatch[1] ?? arrowBlockMatch[2] ?? "");
482
+ return {
483
+ name: func.name,
484
+ args,
485
+ body: arrowBlockMatch[3]
486
+ };
487
+ }
488
+ const arrowExpressionMatch = funcString.match(arrowExpressionRegex);
489
+ if (arrowExpressionMatch) {
490
+ const args = parseArguments(arrowExpressionMatch[1] ?? arrowExpressionMatch[2] ?? "");
491
+ return {
492
+ name: func.name,
493
+ args,
494
+ body: arrowExpressionMatch[3]
495
+ };
496
+ }
497
+ const match = funcString.match(funcRegex);
498
+ invariant(match, "Unable to parse function!");
499
+ return {
500
+ name: func.name ?? match[1],
501
+ args: parseArguments(match[2]),
502
+ body: match[3]
503
+ };
378
504
  }
379
- Namespace.prototype = /* @__PURE__ */ Object.create(null);
380
- var Namespace_default = Namespace;
381
505
 
382
- // src/requireNamespace.ts
506
+ //#endregion
507
+ //#region src/Namespace.ts
508
+ function Namespace() {}
509
+ Namespace.prototype = Object.create(null);
510
+
511
+ //#endregion
512
+ //#region src/requireNamespace.ts
383
513
  function requireNamespace(root, namespace) {
384
- if (typeof root === "object") {
385
- if (typeof namespace === "string") {
386
- let path = namespace.split(".");
387
- return requireNamespace(root, path);
388
- } else if (Array.isArray(namespace)) {
389
- let current = root;
390
- for (let i = 0; i < namespace.length; i++) {
391
- current = current[namespace[i]] = current[namespace[i]] || new Namespace_default();
392
- }
393
- return current;
394
- }
395
- }
396
- }
397
-
398
- // src/expose.ts
514
+ if (typeof root === "object") {
515
+ if (typeof namespace === "string") return requireNamespace(root, namespace.split("."));
516
+ else if (Array.isArray(namespace)) {
517
+ let current = root;
518
+ for (let i = 0; i < namespace.length; i++) current = current[namespace[i]] = current[namespace[i]] || new Namespace();
519
+ return current;
520
+ }
521
+ }
522
+ }
523
+
524
+ //#endregion
525
+ //#region src/expose.ts
526
+ /**
527
+ * Expose a value to a potentially deeply nested global variable
528
+ * @param name {string | object} Either a dot-separated path to the global variable, or an object to expose the value on
529
+ * @param value {object | Function | Function[]} The value(s) to expose
530
+ */
399
531
  function expose(name, value, options = {}) {
400
- if (Array.isArray(value)) {
401
- for (let func of value) {
402
- const { name: funcName } = parseFunc(func);
403
- invariant(
404
- funcName,
405
- "Unable to detect name of function! Name it, or only supply one function and include name in first parameter."
406
- );
407
- expose(name, func);
408
- }
409
- } else {
410
- let keyName;
411
- let namespace;
412
- if (typeof value === "function") {
413
- keyName = parseFunc(value).name;
414
- }
415
- if (typeof name === "string") {
416
- let pathParts = name.split(".");
417
- if (!keyName) {
418
- keyName = pathParts[pathParts.length - 1];
419
- pathParts = pathParts.slice(0, pathParts.length - 1);
420
- }
421
- namespace = requireNamespace(window, pathParts);
422
- } else if (keyName && (typeof name === "object" || typeof name === "function")) {
423
- namespace = name;
424
- } else {
425
- invariant(false, "Invalid typeof parameter 'name', or unable to parse pValue!");
426
- }
427
- if (Object.hasOwn(namespace, keyName) && options?.overwrite !== true) {
428
- console.warn(`${[name, keyName].join(".")} is already defined!`);
429
- } else {
430
- namespace[keyName] = value;
431
- }
432
- }
433
- }
434
-
435
- // src/getLocalizedString.ts
532
+ if (Array.isArray(value)) for (let func of value) {
533
+ const { name: funcName } = parseFunc(func);
534
+ invariant(funcName, "Unable to detect name of function! Name it, or only supply one function and include name in first parameter.");
535
+ expose(name, func);
536
+ }
537
+ else {
538
+ let keyName;
539
+ let namespace;
540
+ if (typeof value === "function") keyName = parseFunc(value).name;
541
+ if (typeof name === "string") {
542
+ let pathParts = name.split(".");
543
+ if (!keyName) {
544
+ keyName = pathParts[pathParts.length - 1];
545
+ pathParts = pathParts.slice(0, pathParts.length - 1);
546
+ }
547
+ namespace = requireNamespace(window, pathParts);
548
+ } else if (keyName && (typeof name === "object" || typeof name === "function")) namespace = name;
549
+ else invariant(false, "Invalid typeof parameter 'name', or unable to parse pValue!");
550
+ if (Object.hasOwn(namespace, keyName) && options?.overwrite !== true) console.warn(`${[name, keyName].join(".")} is already defined!`);
551
+ else namespace[keyName] = value;
552
+ }
553
+ }
554
+
555
+ //#endregion
556
+ //#region src/getLocalizedString.ts
436
557
  async function fetchLocalizedString(text) {
437
- try {
438
- let response = await fetch(`/api/user/localize/new/${af.article.id}`, {
439
- body: JSON.stringify({ text }),
440
- headers: {
441
- Accept: "application/json; */*",
442
- "Content-Type": "application/json",
443
- "X-Requested-With": "XMLHttpRequest"
444
- },
445
- method: "POST"
446
- });
447
- if (response.ok) {
448
- return await response.json();
449
- }
450
- } catch {
451
- }
452
- return text;
558
+ try {
559
+ let response = await fetch(`/api/user/localize/new/${af.article.id}`, {
560
+ body: JSON.stringify({ text }),
561
+ headers: {
562
+ Accept: "application/json; */*",
563
+ "Content-Type": "application/json",
564
+ "X-Requested-With": "XMLHttpRequest"
565
+ },
566
+ method: "POST"
567
+ });
568
+ if (response.ok) return await response.json();
569
+ } catch {}
570
+ return text;
453
571
  }
454
572
  function getLocalizedString(string, wait) {
455
- if (typeof string === "string" && string.trim().length === 0) {
456
- return string;
457
- }
458
- if (string === void 0 || string === "" || string === null) {
459
- return;
460
- }
461
- if (window.af?.article?.i18n !== void 0) {
462
- if (!Object.hasOwn(af.article.i18n, string)) {
463
- af.article.i18n[string] = string;
464
- let promise = fetchLocalizedString(string).then((text) => {
465
- af.article.i18n[string] = text;
466
- return text;
467
- });
468
- if (wait) {
469
- return promise;
470
- }
471
- }
472
- return af.article.i18n[string];
473
- } else {
474
- return string;
475
- }
476
- }
477
-
478
- // src/getUserImage.ts
479
- var sizeMap = {
480
- xs: 64,
481
- sm: 128,
482
- md: 256,
483
- lg: 512,
484
- xl: void 0
573
+ if (typeof string === "string" && string.trim().length === 0) return string;
574
+ if (string === void 0 || string === "" || string === null) return;
575
+ if (window.af?.article?.i18n !== void 0) {
576
+ if (!Object.hasOwn(af.article.i18n, string)) {
577
+ af.article.i18n[string] = string;
578
+ let promise = fetchLocalizedString(string).then((text) => {
579
+ af.article.i18n[string] = text;
580
+ return text;
581
+ });
582
+ if (wait) return promise;
583
+ }
584
+ return af.article.i18n[string];
585
+ } else return string;
586
+ }
587
+
588
+ //#endregion
589
+ //#region src/filter/operators.ts
590
+ /**
591
+ * Operators that take no value at all.
592
+ *
593
+ * `eOperators.ParameterLessChecks` plus the blank checks.
594
+ */
595
+ const PARAMETERLESS_OPERATORS = [
596
+ "isnull",
597
+ "isnotnull",
598
+ "istrue",
599
+ "isfalse",
600
+ "isblank",
601
+ "isnotblank"
602
+ ];
603
+ /** Operators whose value is a two element `[from, to]` array. */
604
+ const PAIR_OPERATORS = [
605
+ "between",
606
+ "notbetween",
607
+ "datebetween",
608
+ "datenotbetween"
609
+ ];
610
+ /** Operators whose value is an array of values. */
611
+ const LIST_OPERATORS = ["inlist", "notinlist"];
612
+ function getOperatorArity(operator) {
613
+ if (PARAMETERLESS_OPERATORS.includes(operator)) return "none";
614
+ if (PAIR_OPERATORS.includes(operator)) return "pair";
615
+ if (LIST_OPERATORS.includes(operator)) return "list";
616
+ return "single";
617
+ }
618
+ /**
619
+ * Operator labels, keyed by operator. Comparison operators have a different
620
+ * label for dates than for numbers, matching the Windows filter editor.
621
+ *
622
+ * @see `appframe/Appframe3.Win/Controls/afFilterEditor/Utils/FilterLineControlUtils.vb`
623
+ */
624
+ const OPERATOR_LABELS = {
625
+ equals: "Equal to",
626
+ notequals: "Not equal to",
627
+ greaterthan: "Greater than",
628
+ greaterthanorequal: "Greater than or equal to",
629
+ lessthan: "Less than",
630
+ lessthanorequal: "Less than or equal to",
631
+ beginswith: "Begins with",
632
+ notbeginswith: "Does not begin with",
633
+ endswith: "Ends with",
634
+ notendswith: "Does not end with",
635
+ contains: "Contains",
636
+ notcontains: "Does not contain",
637
+ like: "Like",
638
+ notlike: "Not like",
639
+ isnull: "Is null",
640
+ isnotnull: "Is not null",
641
+ isblank: "Is empty",
642
+ isnotblank: "Is not empty",
643
+ istrue: "Is true",
644
+ isfalse: "Is false",
645
+ inlist: "In list",
646
+ notinlist: "Not in list",
647
+ between: "Between",
648
+ notbetween: "Not between",
649
+ dateequals: "Equal to",
650
+ notdatequals: "Not equal to",
651
+ dategreaterthan: "After",
652
+ dategreaterthanorequal: "On or after",
653
+ datelessthan: "Before",
654
+ datelessthanorequal: "Up to",
655
+ datebetween: "Between",
656
+ datenotbetween: "Not between"
657
+ };
658
+ /** Comparison operator labels used for date and time fields. */
659
+ const DATE_OPERATOR_LABELS = {
660
+ greaterthan: "After",
661
+ greaterthanorequal: "On or after",
662
+ lessthan: "Before",
663
+ lessthanorequal: "Up to"
664
+ };
665
+ /**
666
+ * Returns the localized label for an operator. Date fields get the
667
+ * "After"/"Before" wording instead of "Greater than"/"Less than".
668
+ */
669
+ function getOperatorLabel(operator, fieldType) {
670
+ let label = (fieldType === "date" || fieldType === "datetime" ? DATE_OPERATOR_LABELS[operator] : void 0) ?? OPERATOR_LABELS[operator];
671
+ return getLocalizedString(label ?? operator);
672
+ }
673
+ const EQUALITY = ["equals", "notequals"];
674
+ const LIST_CHECKS = ["inlist", "notinlist"];
675
+ const RANGE = ["between", "notbetween"];
676
+ const COMPARISONS = [
677
+ "greaterthan",
678
+ "greaterthanorequal",
679
+ "lessthan",
680
+ "lessthanorequal"
681
+ ];
682
+ const STRING_CHECKS = [
683
+ "contains",
684
+ "notcontains",
685
+ "beginswith",
686
+ "notbeginswith",
687
+ "endswith",
688
+ "notendswith",
689
+ "isblank",
690
+ "isnotblank"
691
+ ];
692
+ /**
693
+ * Operators offered per field type, in the order the Windows filter editor
694
+ * presents them.
695
+ */
696
+ const OPERATORS_BY_TYPE = {
697
+ date: [
698
+ ...EQUALITY,
699
+ ...LIST_CHECKS,
700
+ ...RANGE,
701
+ ...COMPARISONS
702
+ ],
703
+ datetime: [
704
+ ...EQUALITY,
705
+ ...LIST_CHECKS,
706
+ ...RANGE,
707
+ ...COMPARISONS
708
+ ],
709
+ number: [
710
+ ...EQUALITY,
711
+ ...LIST_CHECKS,
712
+ ...RANGE,
713
+ ...COMPARISONS
714
+ ],
715
+ boolean: ["istrue", "isfalse"],
716
+ string: [
717
+ ...EQUALITY,
718
+ ...STRING_CHECKS,
719
+ ...LIST_CHECKS,
720
+ ...RANGE,
721
+ ...COMPARISONS
722
+ ],
723
+ uniqueidentifier: [
724
+ ...EQUALITY,
725
+ ...STRING_CHECKS,
726
+ ...LIST_CHECKS,
727
+ ...RANGE,
728
+ ...COMPARISONS
729
+ ]
730
+ };
731
+ /** Default operator per field type. */
732
+ const DEFAULT_OPERATOR_BY_TYPE = {
733
+ date: "equals",
734
+ datetime: "equals",
735
+ number: "equals",
736
+ boolean: "istrue",
737
+ string: "beginswith",
738
+ uniqueidentifier: "beginswith"
739
+ };
740
+ /**
741
+ * Returns the operators available for a field. Nullable fields additionally get
742
+ * the null checks. Boolean fields never get null checks, since `istrue` and
743
+ * `isfalse` already cover the parameterless cases.
744
+ */
745
+ function getOperatorsForField(field) {
746
+ let operators = [...OPERATORS_BY_TYPE[field.type] ?? OPERATORS_BY_TYPE.string];
747
+ if (field.nullable && field.type !== "boolean") operators.push("isnull", "isnotnull");
748
+ return operators;
749
+ }
750
+ function getDefaultOperator(field) {
751
+ return DEFAULT_OPERATOR_BY_TYPE[field.type] ?? "equals";
752
+ }
753
+ /**
754
+ * The `valueType` to send for a field/operator combination.
755
+ *
756
+ * Parameterless operators send `"null"`, list and range operators send
757
+ * `"array"`, everything else sends the field's own value type.
758
+ */
759
+ function getValueType(field, operator) {
760
+ if (getOperatorArity(operator) === "none") return "null";
761
+ switch (field.type) {
762
+ case "number": return "number";
763
+ case "boolean": return "boolean";
764
+ case "date":
765
+ case "datetime": return "datetime";
766
+ case "uniqueidentifier": return "uniqueidentifier";
767
+ default: return "string";
768
+ }
769
+ }
770
+ /** Relative date values offered in the date value editor, in menu order. */
771
+ const RELATIVE_DATE_VALUES = [
772
+ "Yesterday",
773
+ "Today",
774
+ "Tomorrow",
775
+ "ThisWeek",
776
+ "ThisMonth",
777
+ "ThisYear",
778
+ "LastWeek",
779
+ "LastMonth",
780
+ "LastYear",
781
+ "NextWeek",
782
+ "NextMonth",
783
+ "NextYear"
784
+ ];
785
+ const DYNAMIC_VALUE_LABELS = {
786
+ CurrentUser: "Current user",
787
+ Yesterday: "Yesterday",
788
+ Today: "Today",
789
+ Tomorrow: "Tomorrow",
790
+ ThisWeek: "This week",
791
+ ThisMonth: "This month",
792
+ ThisYear: "This year",
793
+ LastWeek: "Last week",
794
+ LastMonth: "Last month",
795
+ LastYear: "Last year",
796
+ NextWeek: "Next week",
797
+ NextMonth: "Next month",
798
+ NextYear: "Next year",
799
+ UserYesterday: "Yesterday",
800
+ UserToday: "Today",
801
+ UserTomorrow: "Tomorrow",
802
+ UserThisWeek: "This week",
803
+ UserThisMonth: "This month",
804
+ UserThisYear: "This year",
805
+ UserLastWeek: "Last week",
806
+ UserLastMonth: "Last month",
807
+ UserLastYear: "Last year",
808
+ UserNextWeek: "Next week",
809
+ UserNextMonth: "Next month",
810
+ UserNextYear: "Next year"
811
+ };
812
+ function getDynamicValueLabel(value) {
813
+ return getLocalizedString(DYNAMIC_VALUE_LABELS[value] ?? value);
814
+ }
815
+ /**
816
+ * Returns the dynamic ("special") values that can be used with a field. Date
817
+ * fields get the relative dates; string fields can be compared to the current
818
+ * user name.
819
+ */
820
+ function getDynamicValuesForField(field) {
821
+ if (field.type === "date" || field.type === "datetime") return [...RELATIVE_DATE_VALUES];
822
+ if (field.type === "string") return ["CurrentUser"];
823
+ return [];
824
+ }
825
+ /**
826
+ * Aliases for names `eOperators.ToString()` can produce that are not operators
827
+ * in their own right. `Not` is the bare negation flag (i.e. "not equal to"),
828
+ * `Tweens` shares its numeric value with `NotBetween`, and combined flags are
829
+ * rendered as a comma separated list.
830
+ *
831
+ * @see `FilterElementConverter.FilterExpressionToDictionary`
832
+ */
833
+ const OPERATOR_ALIASES = {
834
+ not: "notequals",
835
+ tweens: "notbetween",
836
+ notdate: "notdatequals",
837
+ notdateequals: "notdatequals"
838
+ };
839
+ /**
840
+ * Normalizes an operator string coming from the server or from another filter
841
+ * producer (`AfGrid` emits PascalCase names) to the canonical lower-case form.
842
+ */
843
+ function normalizeOperator(operator) {
844
+ let normalized = operator.toLowerCase().replace(/[\s,]/g, "");
845
+ return OPERATOR_ALIASES[normalized] ?? normalized;
846
+ }
847
+
848
+ //#endregion
849
+ //#region src/filter/tree.ts
850
+ /**
851
+ * Creates the default empty filter: a single `and` group with no conditions.
852
+ */
853
+ function createEmptyFilter() {
854
+ return createEmptyGroup("and");
855
+ }
856
+ function createEmptyGroup(mode = "and") {
857
+ return {
858
+ type: "group",
859
+ mode,
860
+ items: []
861
+ };
862
+ }
863
+ function isGroup(item) {
864
+ return item.type === "group";
865
+ }
866
+ function isExpression(item) {
867
+ return item.type === "expression";
868
+ }
869
+ /**
870
+ * Normalizes any filter value into a tree the editor can render, without
871
+ * changing its structure. An expression is wrapped in a group; a missing filter
872
+ * becomes the default layout.
873
+ */
874
+ function toFilterTree(filter) {
875
+ if (!filter) return createEmptyFilter();
876
+ if (isExpression(filter)) return {
877
+ type: "group",
878
+ mode: "and",
879
+ items: [filter]
880
+ };
881
+ return filter;
882
+ }
883
+ /**
884
+ * True when the filter contains no expressions. An empty filter must not be
885
+ * saved or applied.
886
+ */
887
+ function isEmptyFilter(filter) {
888
+ return countExpressions(filter) === 0;
889
+ }
890
+ function countExpressions(filter) {
891
+ if (!filter) return 0;
892
+ if (isExpression(filter)) return 1;
893
+ return filter.items.reduce((total, item) => total + countExpressions(item), 0);
894
+ }
895
+ /**
896
+ * Removes incomplete expressions and empty groups from the whole tree. Returns
897
+ * null when nothing is left. Use before applying a filter to a data object so
898
+ * incomplete rows are not sent.
899
+ */
900
+ function pruneFilter(filter) {
901
+ if (!filter) return null;
902
+ if (isExpression(filter)) return isCompleteExpression(filter) ? {
903
+ type: "group",
904
+ mode: "and",
905
+ items: [filter]
906
+ } : null;
907
+ let items = filter.items.map((item) => isGroup(item) ? pruneFilter(item) : isCompleteExpression(item) ? item : null).filter((item) => item !== null);
908
+ if (items.length === 0) return null;
909
+ return {
910
+ ...filter,
911
+ items
912
+ };
913
+ }
914
+ /**
915
+ * True when an expression has everything it needs to be sent to the server.
916
+ */
917
+ function isCompleteExpression(item) {
918
+ if (isGroup(item)) return item.items.some(isCompleteExpression);
919
+ if (!item.column || !item.operator) return false;
920
+ let arity = getOperatorArity(normalizeOperator(item.operator));
921
+ if (arity === "none") return true;
922
+ if (item.value === null || item.value === void 0 || item.value === "") return false;
923
+ if (arity === "pair") return Array.isArray(item.value) && item.value.length === 2 && item.value.every((v) => v !== "" && v != null);
924
+ if (arity === "list") return Array.isArray(item.value) && item.value.length > 0;
925
+ return true;
926
+ }
927
+ /**
928
+ * Creates an expression for a field, using the field's default operator and an
929
+ * empty value of the right shape.
930
+ */
931
+ function createExpression(field, operator) {
932
+ let op = operator ?? getDefaultOperator(field);
933
+ return {
934
+ type: "expression",
935
+ column: field.name,
936
+ operator: op,
937
+ value: createEmptyValue(op),
938
+ valueType: getValueType(field, op)
939
+ };
940
+ }
941
+ function createEmptyValue(operator) {
942
+ switch (getOperatorArity(operator)) {
943
+ case "none": return null;
944
+ case "pair": return ["", ""];
945
+ case "list": return [];
946
+ default: return "";
947
+ }
948
+ }
949
+ /**
950
+ * Returns a copy of the expression with a new operator, adjusting the value to
951
+ * the new operator's arity and the value type accordingly.
952
+ */
953
+ function changeOperator(expression, operator, field) {
954
+ let previousArity = getOperatorArity(normalizeOperator(expression.operator));
955
+ let arity = getOperatorArity(operator);
956
+ let value = expression.value;
957
+ if (arity !== previousArity) value = createEmptyValue(operator);
958
+ let valueType = expression.valueType === "special" && arity === previousArity ? "special" : getValueType(field, operator);
959
+ return {
960
+ ...expression,
961
+ operator,
962
+ value,
963
+ valueType
964
+ };
965
+ }
966
+ /** Returns the node at `path`, or null when the path does not exist. */
967
+ function getNodeAtPath(filter, path) {
968
+ let node = filter;
969
+ for (let index of path) {
970
+ if (!node || !isGroup(node)) return null;
971
+ node = node.items[index];
972
+ }
973
+ return node ?? null;
974
+ }
975
+ /**
976
+ * Returns a copy of the tree with `updater` applied to the node at `path`.
977
+ * Returning null removes the node. An unknown path leaves the tree untouched.
978
+ */
979
+ function updateNodeAtPath(filter, path, updater) {
980
+ if (path.length === 0) return updater(filter) ?? filter;
981
+ if (!isGroup(filter)) return filter;
982
+ let [index, ...rest] = path;
983
+ let child = filter.items[index];
984
+ if (!child) return filter;
985
+ let items = [...filter.items];
986
+ if (rest.length === 0) {
987
+ let updated = updater(child);
988
+ if (updated === null) items.splice(index, 1);
989
+ else items[index] = updated;
990
+ } else items[index] = updateNodeAtPath(child, rest, updater);
991
+ return {
992
+ ...filter,
993
+ items
994
+ };
995
+ }
996
+ /** Returns a copy of the tree with `node` appended to the group at `path`. */
997
+ function insertNodeAtPath(filter, path, node) {
998
+ return updateNodeAtPath(filter, path, (target) => isGroup(target) ? {
999
+ ...target,
1000
+ items: [...target.items, node]
1001
+ } : target);
1002
+ }
1003
+ /**
1004
+ * Returns a copy of the tree with the node at `path` removed. The root is never
1005
+ * removed; it is reset to the default layout instead.
1006
+ */
1007
+ function removeNodeAtPath(filter, path) {
1008
+ if (path.length === 0) return createEmptyFilter();
1009
+ return updateNodeAtPath(filter, path, () => null);
1010
+ }
1011
+ /** Returns a copy of the tree with the mode of the group at `path` changed. */
1012
+ function setGroupMode(filter, path, mode) {
1013
+ return updateNodeAtPath(filter, path, (node) => isGroup(node) ? {
1014
+ ...node,
1015
+ mode
1016
+ } : node);
1017
+ }
1018
+ /** Returns a copy of the tree with an empty group appended to the group at `path`. */
1019
+ function addGroupAtPath(filter, path = []) {
1020
+ let parent = getNodeAtPath(filter, path);
1021
+ return insertNodeAtPath(filter, path, createEmptyGroup(parent && isGroup(parent) && parent.mode === "and" ? "or" : "and"));
1022
+ }
1023
+
1024
+ //#endregion
1025
+ //#region src/filter/convertFilter.ts
1026
+ const CONVERT_URL = "/api/filter/convert";
1027
+ /**
1028
+ * Converts between a structured filter and a DevExpress filter string.
1029
+ *
1030
+ * The conversion is done server-side by `api/filter/convert`, because the
1031
+ * criteria string grammar is implemented by the licensed DevExpress parser that
1032
+ * the Windows client and the report engine use. Doing it in the browser would
1033
+ * risk producing strings the server cannot parse back.
1034
+ */
1035
+ async function convertFilter(request, signal) {
1036
+ let response = await fetch(CONVERT_URL, {
1037
+ method: "POST",
1038
+ headers: { "Content-Type": "application/json" },
1039
+ body: JSON.stringify(request),
1040
+ signal
1041
+ });
1042
+ if (!response.ok) throw new Error(`Failed to convert filter: ${response.status} ${response.statusText}`);
1043
+ let result = await response.json();
1044
+ return {
1045
+ ...result,
1046
+ filterObject: result.filterObject ? toFilterTree(result.filterObject) : null
1047
+ };
1048
+ }
1049
+
1050
+ //#endregion
1051
+ //#region src/filter/describeFilter.ts
1052
+ /**
1053
+ * Builds a human-readable description of a filter, without contacting the
1054
+ * server. Use this for read-only summaries; the authoritative filter string is
1055
+ * produced by `api/filter/convert`, since only the server can generate the
1056
+ * DevExpress criteria syntax.
1057
+ */
1058
+ function describeFilter(filter, options = {}) {
1059
+ if (!filter) return "";
1060
+ return describe(filter, new Map((options.fields ?? []).map((field) => [field.name.toLowerCase(), field])), 0);
1061
+ }
1062
+ function describe(item, fields, depth) {
1063
+ if (isExpression(item)) return describeExpression(item, fields);
1064
+ let parts = item.items.map((child) => describe(child, fields, depth + 1)).filter((part) => part !== "");
1065
+ if (parts.length === 0) return "";
1066
+ if (parts.length === 1) return parts[0];
1067
+ let separator = item.mode === "or" ? " OR " : " AND ";
1068
+ let joined = parts.join(separator);
1069
+ return depth === 0 ? joined : `(${joined})`;
1070
+ }
1071
+ function describeExpression(expression, fields) {
1072
+ if (!expression.column || !expression.operator) return "";
1073
+ let field = fields.get(expression.column.toLowerCase());
1074
+ let caption = field?.caption ?? expression.column;
1075
+ let operator = normalizeOperator(expression.operator);
1076
+ let label = getOperatorLabel(operator, field?.type);
1077
+ let arity = getOperatorArity(operator);
1078
+ if (arity === "none") return `[${caption}] ${label}`;
1079
+ return `[${caption}] ${label} ${formatValue(expression, arity)}`;
1080
+ }
1081
+ function formatValue(expression, arity) {
1082
+ let { value, valueType } = expression;
1083
+ if (valueType === "special" && typeof value === "string") return getDynamicValueLabel(value);
1084
+ if (Array.isArray(value)) {
1085
+ let formatted = value.map((item) => formatScalar(item, valueType));
1086
+ return arity === "pair" ? formatted.join(" - ") : `(${formatted.join(", ")})`;
1087
+ }
1088
+ return formatScalar(value, valueType);
1089
+ }
1090
+ function formatScalar(value, valueType) {
1091
+ if (value === null || value === void 0) return "";
1092
+ if (value instanceof Date) return value.toISOString().slice(0, 10);
1093
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1094
+ if (valueType === "number" || valueType === "boolean") return String(value);
1095
+ return `'${String(value)}'`;
1096
+ }
1097
+
1098
+ //#endregion
1099
+ //#region src/filter/fields.ts
1100
+ const FIELD_TYPES = [
1101
+ "string",
1102
+ "number",
1103
+ "boolean",
1104
+ "date",
1105
+ "datetime",
1106
+ "uniqueidentifier"
1107
+ ];
1108
+ /** The builder type for a normalized `DataType`. Unknown types are filtered as text. */
1109
+ function toFilterFieldType(dataType) {
1110
+ let normalized = dataType?.trim().toLowerCase();
1111
+ return FIELD_TYPES.find((type) => type === normalized) ?? "string";
1112
+ }
1113
+ function toBoolean$1(value) {
1114
+ return value === true || value === 1;
1115
+ }
1116
+ /** Maps a view field record onto the metadata the builder renders. */
1117
+ function toFieldMetadata(record) {
1118
+ return {
1119
+ name: record.FieldName ?? "",
1120
+ type: toFilterFieldType(record.DataType),
1121
+ nullable: toBoolean$1(record.Nullable),
1122
+ excludeFromFilter: toBoolean$1(record.ExcludeFromFilter),
1123
+ valueListRecordSource: record.ValueListRecordSource || void 0
1124
+ };
1125
+ }
1126
+ /**
1127
+ * Maps and sorts view field records. Fields the view marks as excluded are
1128
+ * dropped rather than hidden, since nothing else can use them.
1129
+ */
1130
+ function toFieldMetadataList(records) {
1131
+ return records.map(toFieldMetadata).filter((field) => field.name !== "" && !field.excludeFromFilter).sort((a, b) => a.name.localeCompare(b.name));
1132
+ }
1133
+
1134
+ //#endregion
1135
+ //#region src/filter/standardLayout.ts
1136
+ /**
1137
+ * The "standard layout" is the simplified shape the Windows filter editor can
1138
+ * render in its flow view: an outer `or` group whose items are `and` groups of
1139
+ * expressions. Anything else falls back to the advanced (DevExpress) editor
1140
+ * there, and to the nested tree editor on the web.
1141
+ *
1142
+ * @see `afFilterEditor.CanRenderFilter`
1143
+ */
1144
+ function isStandardLayout(filter) {
1145
+ if (!filter || isExpression(filter) || filter.mode !== "or") return false;
1146
+ return filter.items.every((item) => isGroup(item) && item.mode === "and" && item.items.every(isExpression));
1147
+ }
1148
+ /**
1149
+ * Coerces an arbitrary filter tree into the standard layout.
1150
+ *
1151
+ * An `or` group's items each become their own `and` group. Anything else is
1152
+ * flattened into a single `and` group. This loses nesting, so only use it when
1153
+ * the consumer cannot handle a nested tree.
1154
+ */
1155
+ function coerceToStandardLayout(filter) {
1156
+ if (!filter) return {
1157
+ type: "group",
1158
+ mode: "or",
1159
+ items: [{
1160
+ type: "group",
1161
+ mode: "and",
1162
+ items: []
1163
+ }]
1164
+ };
1165
+ if (isExpression(filter)) return {
1166
+ type: "group",
1167
+ mode: "or",
1168
+ items: [{
1169
+ type: "group",
1170
+ mode: "and",
1171
+ items: [filter]
1172
+ }]
1173
+ };
1174
+ if (filter.mode === "or") {
1175
+ let groups = filter.items.map((item) => {
1176
+ let expressions = [];
1177
+ collectExpressions(item, expressions);
1178
+ return {
1179
+ type: "group",
1180
+ mode: "and",
1181
+ items: expressions
1182
+ };
1183
+ });
1184
+ return {
1185
+ type: "group",
1186
+ mode: "or",
1187
+ items: groups.length > 0 ? groups : [{
1188
+ type: "group",
1189
+ mode: "and",
1190
+ items: []
1191
+ }]
1192
+ };
1193
+ }
1194
+ let expressions = [];
1195
+ collectExpressions(filter, expressions);
1196
+ return {
1197
+ type: "group",
1198
+ mode: "or",
1199
+ items: [{
1200
+ type: "group",
1201
+ mode: "and",
1202
+ items: expressions
1203
+ }]
1204
+ };
1205
+ }
1206
+ /**
1207
+ * Collects every expression in a (possibly nested) filter, in document order.
1208
+ */
1209
+ function collectExpressions(item, into) {
1210
+ if (isExpression(item)) {
1211
+ into.push(item);
1212
+ return;
1213
+ }
1214
+ for (let child of item.items) collectExpressions(child, into);
1215
+ }
1216
+
1217
+ //#endregion
1218
+ //#region src/filter/savedFilters.ts
1219
+ /**
1220
+ * `sviw_Database_MyFilters` unions in a synthetic "No Filter" row so the Windows
1221
+ * tree can render a "no filter" entry. It is not a real filter and must be
1222
+ * dropped before the list is shown.
1223
+ */
1224
+ const NO_FILTER_ID = -1;
1225
+ /**
1226
+ * Maps a database record onto a `SavedFilter`.
1227
+ *
1228
+ * `CreatedByUser` needs care: the view computes it as the *string* `'true'` or
1229
+ * `'false'` (and `'False'` on the synthetic row), not as a bit.
1230
+ */
1231
+ function toSavedFilter(record) {
1232
+ return {
1233
+ filterId: record.FilterID ?? -1,
1234
+ primKey: record.PrimKey ?? "",
1235
+ name: record.FilterName ?? "",
1236
+ criteria: record.FilterCriteria ?? "",
1237
+ dbObjectId: record.DBObjectID ?? "",
1238
+ accessLevel: toAccessLevel(record.AccessLevel),
1239
+ createdByUser: toBoolean(record.CreatedByUser),
1240
+ createdBy: record.CreatedBy ?? "",
1241
+ domain: record.Domain ?? null,
1242
+ crossDomain: toBoolean(record.CrossDomain),
1243
+ isPersonallyShared: toBoolean(record.IsPersonallyShared),
1244
+ hideCriteria: toBoolean(record.HideFilterCriteria),
1245
+ headerText: record.OptionalHeaderText || null,
1246
+ comment: record.OptionalComment || null,
1247
+ parameters: record.Parameters || null,
1248
+ reportTitle: record.ReportTitle || null,
1249
+ created: toDate(record.Created),
1250
+ updated: toDate(record.Updated)
1251
+ };
1252
+ }
1253
+ function toAccessLevel(value) {
1254
+ if (value === "Manager" || value === "Editor") return value;
1255
+ return "Reader";
1256
+ }
1257
+ function toBoolean(value) {
1258
+ if (typeof value === "string") return value.toLowerCase() === "true";
1259
+ return Boolean(value);
1260
+ }
1261
+ function toDate(value) {
1262
+ if (!value) return null;
1263
+ if (value instanceof Date) return value;
1264
+ let date = new Date(value);
1265
+ return Number.isNaN(date.getTime()) ? null : date;
1266
+ }
1267
+ /** Drops the synthetic "No Filter" row and sorts by name. */
1268
+ function toSavedFilters(records) {
1269
+ return records.filter((record) => (record.FilterID ?? -1) !== -1).map(toSavedFilter).sort((a, b) => a.name.localeCompare(b.name));
1270
+ }
1271
+ /**
1272
+ * Splits filters into the two branches the Windows tree shows: the ones the user
1273
+ * created, and the ones that have been shared with them.
1274
+ */
1275
+ function partitionSavedFilters(filters) {
1276
+ let mine = [];
1277
+ let shared = [];
1278
+ for (let filter of filters) if (filter.createdByUser) mine.push(filter);
1279
+ else shared.push(filter);
1280
+ return {
1281
+ mine,
1282
+ shared
1283
+ };
1284
+ }
1285
+ function findSavedFilter(filters, filterId) {
1286
+ if (filterId == null) return void 0;
1287
+ return filters.find((filter) => filter.filterId === filterId);
1288
+ }
1289
+ /** True when the user may overwrite the filter's criteria. */
1290
+ function canEditSavedFilter(filter) {
1291
+ return filter.accessLevel === "Editor" || filter.accessLevel === "Manager";
1292
+ }
1293
+ /** True when the user may change who the filter is shared with. */
1294
+ function canShareSavedFilter(filter) {
1295
+ return filter.accessLevel === "Manager";
1296
+ }
1297
+ /**
1298
+ * True when the user may rename or delete the filter.
1299
+ *
1300
+ * `sstp_WebSiteCMS_FilterBuilder_RenameFilter` and `…_DeleteFilter` both require
1301
+ * `CreatedBy = SUSER_SNAME()` — the manager-access branch is commented out in
1302
+ * both procedures, deliberately, because the UI only ever offers these for a
1303
+ * user's own filters.
1304
+ */
1305
+ function canRenameSavedFilter(filter) {
1306
+ return filter.createdByUser;
1307
+ }
1308
+ const canDeleteSavedFilter = canRenameSavedFilter;
1309
+ /**
1310
+ * True when the user may toggle the cross-domain flag.
1311
+ *
1312
+ * `sstp_Database_Filters_SetCrossDomain` also filters on
1313
+ * `CreatedBy = SUSER_SNAME()`.
1314
+ */
1315
+ const canSetCrossDomain = canRenameSavedFilter;
1316
+
1317
+ //#endregion
1318
+ //#region src/getUserImage.ts
1319
+ const sizeMap = {
1320
+ xs: 64,
1321
+ sm: 128,
1322
+ md: 256,
1323
+ lg: 512,
1324
+ xl: void 0
485
1325
  };
486
1326
  function getUserImage(primKeyOrOptions, login, hash, size = "xs") {
487
- if (primKeyOrOptions && typeof primKeyOrOptions === "object") {
488
- return getUserImage(primKeyOrOptions.primKey, primKeyOrOptions.login, primKeyOrOptions.hash, primKeyOrOptions.size);
489
- }
490
- if (!primKeyOrOptions || !hash) {
491
- return "";
492
- }
493
- let sizePx = sizeMap[size];
494
- return `/api/data/blob/EmployeesLookup/${primKeyOrOptions}/Image/${encodeURIComponent(login ?? "")}${login ? "." : ""}${encodeURIComponent(hash)}.jpg${sizePx ? `?width=${sizePx}` : ""}`;
1327
+ if (primKeyOrOptions && typeof primKeyOrOptions === "object") return getUserImage(primKeyOrOptions.primKey, primKeyOrOptions.login, primKeyOrOptions.hash, primKeyOrOptions.size);
1328
+ if (!primKeyOrOptions || !hash) return "";
1329
+ let sizePx = sizeMap[size];
1330
+ return `/api/data/blob/EmployeesLookup/${primKeyOrOptions}/Image/${encodeURIComponent(login ?? "")}${login ? "." : ""}${encodeURIComponent(hash)}.jpg${sizePx ? `?width=${sizePx}` : ""}`;
495
1331
  }
496
1332
 
497
- // src/localize.ts
1333
+ //#endregion
1334
+ //#region src/localize.ts
1335
+ /**
1336
+ * Localization function for tagged templates. Replaces the arguments
1337
+ * with $n, where n is the index, before asking Appframe to translate
1338
+ * the string.
1339
+ *
1340
+ * For example, if you call localize`Page ${2} or ${5}`, the string
1341
+ * "Page $0 of $1" will be sent to Appframe, and for norwegian,
1342
+ * "Side 2 av 5" will be returned.
1343
+ *
1344
+ * @param stringParts
1345
+ * @param args
1346
+ * @returns Translated string
1347
+ */
498
1348
  function localize(stringParts, ...args) {
499
- invariant(
500
- Array.isArray(stringParts) && stringParts.length === args.length + 1,
501
- "Method 'localize' must be used as a tag function"
502
- );
503
- let stringToLocalize = stringParts.map((s, i) => i === stringParts.length - 1 ? s : `${s}$${i}`).join("");
504
- let localized = getLocalizedString(stringToLocalize);
505
- args.forEach((arg, index) => {
506
- localized = localized.replace(`$${index}`, arg);
507
- });
508
- return localized;
509
- }
510
-
511
- // src/alert.ts
512
- var template = `
1349
+ invariant(Array.isArray(stringParts) && stringParts.length === args.length + 1, "Method 'localize' must be used as a tag function");
1350
+ let stringToLocalize = stringParts.map((s, i) => i === stringParts.length - 1 ? s : `${s}$${i}`).join("");
1351
+ let localized = getLocalizedString(stringToLocalize);
1352
+ args.forEach((arg, index) => {
1353
+ localized = localized.replace(`$${index}`, arg);
1354
+ });
1355
+ return localized;
1356
+ }
1357
+
1358
+ //#endregion
1359
+ //#region src/report/recordSource.ts
1360
+ const XML_ENTITIES = {
1361
+ amp: "&",
1362
+ lt: "<",
1363
+ gt: ">",
1364
+ quot: "\"",
1365
+ apos: "'"
1366
+ };
1367
+ /** Resolves the XML entities the .NET serializer emits. */
1368
+ function decodeXml(value) {
1369
+ return value.replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (match, entity) => {
1370
+ if (entity.startsWith("#x") || entity.startsWith("#X")) return String.fromCodePoint(Number.parseInt(entity.slice(2), 16));
1371
+ if (entity.startsWith("#")) return String.fromCodePoint(Number.parseInt(entity.slice(1), 10));
1372
+ return XML_ENTITIES[entity.toLowerCase()] ?? match;
1373
+ });
1374
+ }
1375
+ /** Escapes a value for use as XML text or as an attribute value. */
1376
+ function encodeXml(value) {
1377
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1378
+ }
1379
+ /**
1380
+ * The text content of the first `<name>` element, or `null` when the element is
1381
+ * missing or self-closing (`<FilterString />`, which the serializer writes for
1382
+ * an empty value).
1383
+ */
1384
+ function readElement(xml, name) {
1385
+ let match = new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)</${name}>`).exec(xml);
1386
+ if (!match) return null;
1387
+ let value = decodeXml(match[1]).trim();
1388
+ return value === "" ? null : value;
1389
+ }
1390
+ /** The text content of every `<name>` element, in document order. */
1391
+ function readElements(xml, name) {
1392
+ return [...xml.matchAll(new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)</${name}>`, "g"))].map((match) => decodeXml(match[1]).trim());
1393
+ }
1394
+ /**
1395
+ * The CLR types the designer writes on a select column. Anything else — and a
1396
+ * column with no `DataType` at all, which is what it writes for strings — is
1397
+ * treated as text.
1398
+ */
1399
+ const COLUMN_TYPES = {
1400
+ Byte: "number",
1401
+ Decimal: "number",
1402
+ Double: "number",
1403
+ Int16: "number",
1404
+ Int32: "number",
1405
+ Int64: "number",
1406
+ Single: "number",
1407
+ Boolean: "boolean",
1408
+ DateTime: "date"
1409
+ };
1410
+ /** The columns of a `<SelectColumns>` block, in document order. */
1411
+ function readSelectColumns(xml) {
1412
+ let block = /<SelectColumns>([\s\S]*?)<\/SelectColumns>/.exec(xml)?.[1] ?? "";
1413
+ let columns = [];
1414
+ for (let match of block.matchAll(/<afSelectColumn>([\s\S]*?)<\/afSelectColumn>/g)) {
1415
+ let name = readElement(match[1], "Name");
1416
+ if (!name) continue;
1417
+ columns.push({
1418
+ name,
1419
+ type: COLUMN_TYPES[readElement(match[1], "DataType") ?? ""] ?? "string"
1420
+ });
1421
+ }
1422
+ return columns;
1423
+ }
1424
+ /**
1425
+ * Reads the parts of an `afRecordSource` a web client can act on: the view, the
1426
+ * selected columns and the design-time filter.
1427
+ *
1428
+ * Returns `null` for anything that is not a record source, so a missing or
1429
+ * empty `RecordSource` column simply means "no lookup".
1430
+ */
1431
+ function parseRecordSource(xml) {
1432
+ if (!xml || !xml.includes("<afRecordSource")) return null;
1433
+ let viewName = readElement(xml, "ViewName");
1434
+ if (!viewName) return null;
1435
+ let maxRecords = readElement(xml, "MaxRecords");
1436
+ return {
1437
+ viewName,
1438
+ columns: readSelectColumns(xml),
1439
+ whereClause: readElement(xml, "WhereClause"),
1440
+ filterString: readElement(xml, "FilterString"),
1441
+ maxRecords: maxRecords === null || maxRecords === "0" ? null : Number(maxRecords)
1442
+ };
1443
+ }
1444
+
1445
+ //#endregion
1446
+ //#region src/report/parameters.ts
1447
+ /**
1448
+ * Report parameters: mapping the metadata records onto something renderable,
1449
+ * and the XML the parameter values are stored as on a saved filter.
1450
+ */
1451
+ const PARAMETER_TYPES = [
1452
+ "String",
1453
+ "Integer",
1454
+ "Double",
1455
+ "Date",
1456
+ "Boolean"
1457
+ ];
1458
+ /**
1459
+ * A default value naming a stored procedure, e.g. `astp_Reports_CurrentPeriod`.
1460
+ *
1461
+ * The Windows launcher executes the procedure and uses the first column of the
1462
+ * first row. The web client cannot execute an arbitrary procedure, so these are
1463
+ * resolved through the report endpoint instead.
1464
+ */
1465
+ const PROCEDURE_DEFAULT = /^[a-z]stp_/i;
1466
+ /** True when a `DefaultValue` names a stored procedure rather than a literal. */
1467
+ function isProcedureDefault(defaultValue) {
1468
+ return typeof defaultValue === "string" && PROCEDURE_DEFAULT.test(defaultValue.trim());
1469
+ }
1470
+ /** The choices of a parameter, one per line of its `Items` column. */
1471
+ function parseParameterItems(items) {
1472
+ if (!items) return [];
1473
+ return items.split(/\r\n|\r|\n/).map((item) => item.trim()).filter((item) => item !== "");
1474
+ }
1475
+ function toParameterType(dataType) {
1476
+ return PARAMETER_TYPES.find((type) => type.toLowerCase() === dataType?.trim().toLowerCase()) ?? "String";
1477
+ }
1478
+ /**
1479
+ * The editor a parameter should use. A lookup or a fixed item list wins over the
1480
+ * data type, which is what the Windows launcher does as well.
1481
+ */
1482
+ function toParameterEditor(type, hasLookup, hasItems) {
1483
+ if (hasLookup) return "lookup";
1484
+ if (hasItems) return "select";
1485
+ switch (type) {
1486
+ case "Integer":
1487
+ case "Double": return "number";
1488
+ case "Date": return "date";
1489
+ case "Boolean": return "boolean";
1490
+ default: return "text";
1491
+ }
1492
+ }
1493
+ /** Maps a `sviw_WinClient_ReportsParameters` record onto a `ReportParameter`. */
1494
+ function toReportParameter(record) {
1495
+ let name = record.Name ?? "";
1496
+ let type = toParameterType(record.DataType);
1497
+ let items = parseParameterItems(record.Items);
1498
+ let recordSource = parseRecordSource(record.RecordSource);
1499
+ let valueMember = record.ValueMember ?? null;
1500
+ if (recordSource && !valueMember) valueMember = recordSource.columns[0]?.name ?? null;
1501
+ let displayMember = recordSource?.columns.find((column) => column.name !== valueMember)?.name ?? null;
1502
+ let hasLookup = Boolean(recordSource && valueMember);
1503
+ return {
1504
+ name,
1505
+ label: record.Label?.trim() || name,
1506
+ description: record.Description?.trim() || null,
1507
+ type,
1508
+ editor: toParameterEditor(type, hasLookup, items.length > 0),
1509
+ defaultValue: record.DefaultValue ?? null,
1510
+ items,
1511
+ recordSource: hasLookup ? recordSource : null,
1512
+ valueMember: hasLookup ? valueMember : null,
1513
+ displayMember: hasLookup ? displayMember : null,
1514
+ sortOrder: record.SortOrder ?? 0,
1515
+ lookupWidth: record.LookupWidth ?? null,
1516
+ lookupHeight: record.LookupHeight ?? null
1517
+ };
1518
+ }
1519
+ /** Maps and sorts a report's parameter records. */
1520
+ function toReportParameters(records) {
1521
+ return records.filter((record) => record.Name).map(toReportParameter).sort((a, b) => a.sortOrder - b.sortOrder || a.label.localeCompare(b.label));
1522
+ }
1523
+ /** Converts a raw value to the type a parameter expects. */
1524
+ function coerceParameterValue(parameter, value) {
1525
+ if (value === null || value === void 0 || value === "") return parameter.type === "Boolean" ? false : null;
1526
+ switch (parameter.type) {
1527
+ case "Boolean": return typeof value === "boolean" ? value : /^(true|1|ja|yes)$/i.test(String(value));
1528
+ case "Integer": {
1529
+ let parsed = Number.parseInt(String(value), 10);
1530
+ return Number.isNaN(parsed) ? null : parsed;
1531
+ }
1532
+ case "Double": {
1533
+ let parsed = Number(String(value).replace(",", "."));
1534
+ return Number.isNaN(parsed) ? null : parsed;
1535
+ }
1536
+ default: return String(value);
1537
+ }
1538
+ }
1539
+ /**
1540
+ * The initial values for a set of parameters.
1541
+ *
1542
+ * Defaults naming a stored procedure are left unset: they have to be resolved
1543
+ * server-side, and the caller fills them in once they are.
1544
+ */
1545
+ function getDefaultParameterValues(parameters) {
1546
+ let values = {};
1547
+ for (let parameter of parameters) values[parameter.name] = isProcedureDefault(parameter.defaultValue) ? coerceParameterValue(parameter, null) : coerceParameterValue(parameter, parameter.defaultValue);
1548
+ return values;
1549
+ }
1550
+ function toXmlValue(parameter, value) {
1551
+ if (value === null || value === void 0) return "";
1552
+ if (typeof value === "boolean") return value ? "True" : "False";
1553
+ return String(value);
1554
+ }
1555
+ /**
1556
+ * Serializes parameter values the way the Windows filter builder does, so that
1557
+ * a filter saved on the web is readable in the Windows client and the other way
1558
+ * around.
1559
+ *
1560
+ * ```xml
1561
+ * <Parameters Version="1">
1562
+ * <Parameter Name="Period" Type="Integer">202601</Parameter>
1563
+ * </Parameters>
1564
+ * ```
1565
+ */
1566
+ function serializeParameters(parameters, values) {
1567
+ return `<Parameters Version="1">\n${parameters.map((parameter) => {
1568
+ let value = toXmlValue(parameter, values[parameter.name] ?? null);
1569
+ return ` <Parameter Name="${encodeXml(parameter.name)}" Type="${parameter.type}">${encodeXml(value)}</Parameter>`;
1570
+ }).join("\n")}\n</Parameters>`;
1571
+ }
1572
+ /**
1573
+ * Reads the values back out of the XML stored on a saved filter. Values are
1574
+ * returned as strings and coerced against the report's own parameters by
1575
+ * `restoreParameterValues`, since the XML may name parameters the report no
1576
+ * longer has.
1577
+ */
1578
+ function parseParameters(xml) {
1579
+ if (!xml) return {};
1580
+ let values = {};
1581
+ for (let match of xml.matchAll(/<Parameter\s+([^>]*?)\/?>(?:([\s\S]*?)<\/Parameter>)?/g)) {
1582
+ let name = /Name\s*=\s*"([^"]*)"/.exec(match[1])?.[1];
1583
+ if (!name) continue;
1584
+ values[name] = readElement(match[0], "Parameter") ?? "";
1585
+ }
1586
+ return values;
1587
+ }
1588
+ /**
1589
+ * Applies the values stored on a saved filter to a report's parameters, keeping
1590
+ * the defaults for anything the filter does not mention.
1591
+ */
1592
+ function restoreParameterValues(parameters, xml) {
1593
+ let stored = parseParameters(xml);
1594
+ let values = getDefaultParameterValues(parameters);
1595
+ for (let parameter of parameters) if (parameter.name in stored) values[parameter.name] = coerceParameterValue(parameter, stored[parameter.name]);
1596
+ return values;
1597
+ }
1598
+
1599
+ //#endregion
1600
+ //#region src/report/parameterDefaults.ts
1601
+ /**
1602
+ * Resolving report parameter defaults that name a stored procedure.
1603
+ *
1604
+ * A `DefaultValue` matching `^[a-z]stp_` names a procedure that produces the
1605
+ * default rather than being the default itself. Executing it is a server
1606
+ * concern, and the framework already exposes it through the `WebsiteCMS`
1607
+ * `api/reporting/filters` route.
1608
+ */
1609
+ /**
1610
+ * Runs the stored procedure a parameter's default names and returns the value
1611
+ * it produces — the first column of the first row, the way the Windows launcher
1612
+ * reads it.
1613
+ *
1614
+ * Returns `null` when the parameter has no procedure default or the procedure
1615
+ * produced no rows.
1616
+ */
1617
+ async function fetchParameterDefault(reportId, parameter, signal) {
1618
+ if (!parameter.defaultValue || !isProcedureDefault(parameter.defaultValue)) return null;
1619
+ let response = await fetch(`/api/reporting/filters/${encodeURIComponent(reportId)}/GetParameterDefaultValue`, {
1620
+ body: JSON.stringify({ parameterName: parameter.name }),
1621
+ credentials: "same-origin",
1622
+ headers: {
1623
+ "Content-Type": "application/json",
1624
+ "X-Requested-With": "XMLHttpRequest"
1625
+ },
1626
+ method: "POST",
1627
+ signal
1628
+ });
1629
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
1630
+ return firstValue(await response.json());
1631
+ }
1632
+ /**
1633
+ * Resolves every procedure default of a report in parallel and merges the
1634
+ * results over the literal defaults.
1635
+ *
1636
+ * A parameter whose procedure fails is left at its literal default rather than
1637
+ * failing the whole form — the user can still type a value.
1638
+ */
1639
+ async function resolveParameterDefaults(reportId, parameters, literalDefaults, signal) {
1640
+ let dynamic = parameters.filter((parameter) => isProcedureDefault(parameter.defaultValue ?? ""));
1641
+ if (dynamic.length === 0) return literalDefaults;
1642
+ let resolved = await Promise.all(dynamic.map(async (parameter) => {
1643
+ try {
1644
+ return [parameter.name, await fetchParameterDefault(reportId, parameter, signal)];
1645
+ } catch {
1646
+ return [parameter.name, null];
1647
+ }
1648
+ }));
1649
+ let values = { ...literalDefaults };
1650
+ for (let [name, value] of resolved) if (value !== null) values[name] = value;
1651
+ return values;
1652
+ }
1653
+ /** The first column of the first row of whichever result set came back. */
1654
+ function firstValue(result) {
1655
+ let row = (Array.isArray(result) ? result : Object.values(result).find((value) => Array.isArray(value)))?.[0];
1656
+ if (row === void 0 || row === null) return null;
1657
+ if (Array.isArray(row)) return row[0] ?? null;
1658
+ if (typeof row === "object") return Object.values(row)[0] ?? null;
1659
+ return row;
1660
+ }
1661
+
1662
+ //#endregion
1663
+ //#region src/report/render.ts
1664
+ /**
1665
+ * Rendering a report through the framework's report route.
1666
+ *
1667
+ * The route is a CMS code module owned by the Appframe framework
1668
+ * (`WebsiteCMS.Reports`), registered on
1669
+ * `api/report/{ReportID}/{FileName}.{Extension}`. Everything here builds
1670
+ * requests for it — there is no report endpoint of our own.
1671
+ */
1672
+ /**
1673
+ * The file extension each format is requested with. The route only accepts
1674
+ * `(pdf|csv|xlsx?|html|xbm|mht|rtf|txt)`, which is why `TEXT` is `txt` and
1675
+ * `IMAGE` is `xbm` rather than the format name.
1676
+ */
1677
+ const REPORT_EXTENSIONS = {
1678
+ CSV: "csv",
1679
+ HTML: "html",
1680
+ IMAGE: "xbm",
1681
+ MHT: "mht",
1682
+ PDF: "pdf",
1683
+ RTF: "rtf",
1684
+ TEXT: "txt",
1685
+ XLS: "xls",
1686
+ XLSX: "xlsx"
1687
+ };
1688
+ /** The media type each format is served as, for previewing a rendered report. */
1689
+ const REPORT_MEDIA_TYPES = {
1690
+ CSV: "text/csv",
1691
+ HTML: "text/html",
1692
+ IMAGE: "image/x-xbitmap",
1693
+ MHT: "message/rfc822",
1694
+ PDF: "application/pdf",
1695
+ RTF: "text/enriched",
1696
+ TEXT: "text/plain",
1697
+ XLS: "application/vnd.ms-excel",
1698
+ XLSX: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1699
+ };
1700
+ /** The extension a format is requested with. */
1701
+ function getReportExtension(format) {
1702
+ return REPORT_EXTENSIONS[format];
1703
+ }
1704
+ /** The media type a format is served as. */
1705
+ function getReportMediaType(format) {
1706
+ return REPORT_MEDIA_TYPES[format];
1707
+ }
1708
+ /**
1709
+ * Characters that must not reach the file name, because it is a path segment of
1710
+ * the route: separators, the extension delimiter, the query and fragment
1711
+ * delimiters, and control characters.
1712
+ */
1713
+ const UNSAFE_FILE_NAME_CHARACTERS = /[\\/:*?"<>|.#&+%\u0000-\u001f]/g;
1714
+ /**
1715
+ * The name a rendered report is downloaded as, including its extension.
1716
+ *
1717
+ * The file name is part of the route rather than a query parameter, so anything
1718
+ * that would change the path is replaced.
1719
+ */
1720
+ function getReportFileName(options) {
1721
+ let safe = (options.fileName ?? options.reportId).trim().replace(UNSAFE_FILE_NAME_CHARACTERS, "-").replace(/-{2,}/g, "-").replace(/^-|-$/g, "").trim();
1722
+ return `${safe === "" ? options.reportId : safe}.${getReportExtension(options.format)}`;
1723
+ }
1724
+ /**
1725
+ * The route is always on the same origin, but a `Request` needs an absolute
1726
+ * URL, so the path is resolved against the document when there is one.
1727
+ */
1728
+ function toRequestUrl(path) {
1729
+ let base = window.location?.href;
1730
+ return base ? new URL(path, base).toString() : path;
1731
+ }
1732
+ /**
1733
+ * The request that renders a report.
1734
+ *
1735
+ * A report without parameters is a plain `GET`, so it can be opened directly in
1736
+ * a new tab. As soon as there are parameters or a header the options go in a
1737
+ * JSON body, which the route only reads from a `POST`.
1738
+ *
1739
+ * `filter` is always sent alongside `parameters`: the route reads the filter out
1740
+ * of the body *guarded by the presence of `parameters`*, and reads it with an
1741
+ * indexer that throws when the key is missing.
1742
+ */
1743
+ function getReportRequest(options) {
1744
+ let { domain, filter, headerText, hideFilterString, parameters, reportId, signal, timezone } = options;
1745
+ let fileName = getReportFileName(options);
1746
+ let url = `/api/report/${encodeURIComponent(reportId)}/${encodeURIComponent(fileName)}`;
1747
+ let query = new URLSearchParams();
1748
+ let entries = toParameterEntries(parameters);
1749
+ let needsBody = entries.length > 0 || Boolean(headerText) || hideFilterString === true;
1750
+ if (domain) query.set("Domain", domain);
1751
+ query.set("timezone", String(timezone ?? -(/* @__PURE__ */ new Date()).getTimezoneOffset() / 60));
1752
+ if (!needsBody) {
1753
+ if (filter) query.set("Filter", filter);
1754
+ return new Request(toRequestUrl(`${url}?${query}`), {
1755
+ credentials: "same-origin",
1756
+ signal
1757
+ });
1758
+ }
1759
+ let body = {
1760
+ filter: filter ?? "",
1761
+ parameters: entries
1762
+ };
1763
+ if (headerText) body.optionalheader = headerText;
1764
+ if (hideFilterString === true) body.showfiltercriteria = "true";
1765
+ return new Request(toRequestUrl(`${url}?${query}`), {
1766
+ body: JSON.stringify(body),
1767
+ credentials: "same-origin",
1768
+ headers: {
1769
+ "Content-Type": "application/json",
1770
+ "X-Requested-With": "XMLHttpRequest"
1771
+ },
1772
+ method: "POST",
1773
+ signal
1774
+ });
1775
+ }
1776
+ /**
1777
+ * Renders a report and resolves with the rendered file.
1778
+ *
1779
+ * The route answers with a JSON body carrying an `error` when rendering fails,
1780
+ * rather than with a failing status, so a JSON response is turned into an error
1781
+ * here.
1782
+ */
1783
+ async function renderReport(options) {
1784
+ let response = await fetch(getReportRequest(options));
1785
+ if ((response.headers.get("content-type") ?? "").includes("application/json")) {
1786
+ let data = await response.json();
1787
+ throw new Error(data.error ?? "Failed to render report");
1788
+ }
1789
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
1790
+ return response.blob();
1791
+ }
1792
+ /** Renders a report and saves it, reporting progress as it downloads. */
1793
+ function downloadReport(options) {
1794
+ return downloadRequest(getReportRequest(options), {
1795
+ fileName: getReportFileName(options),
1796
+ onProgress: options.onProgress,
1797
+ signal: options.signal
1798
+ });
1799
+ }
1800
+ /**
1801
+ * Renders a report and opens it in a new tab.
1802
+ *
1803
+ * The blob is rendered first rather than pointing a tab at the route, so a
1804
+ * failure surfaces as an error here instead of as a tab showing JSON, and so
1805
+ * reports with parameters — which have to be posted — can be previewed too.
1806
+ */
1807
+ async function openReport(options) {
1808
+ let blob = await renderReport(options);
1809
+ let url = URL.createObjectURL(blob.type ? blob : new Blob([blob], { type: getReportMediaType(options.format) }));
1810
+ if (!window.open(url, "_blank", "noopener")) {
1811
+ URL.revokeObjectURL(url);
1812
+ throw new Error("The report could not be opened. Allow pop-ups for this site and try again.");
1813
+ }
1814
+ window.setTimeout(() => URL.revokeObjectURL(url), 6e4);
1815
+ }
1816
+ /**
1817
+ * Renders a report and opens the browser's print dialog for it.
1818
+ *
1819
+ * The report is loaded into an offscreen iframe rather than a new tab, so the
1820
+ * print dialog opens over the launcher and the user is not left with a stray
1821
+ * tab afterwards. Browsers that will not print an embedded document fall back
1822
+ * to opening it, which leaves the user one keystroke from printing.
1823
+ */
1824
+ async function printReport(options) {
1825
+ let document_ = window.document;
1826
+ if (!document_?.body) return openReport(options);
1827
+ let blob = await renderReport(options);
1828
+ let url = URL.createObjectURL(blob.type ? blob : new Blob([blob], { type: getReportMediaType(options.format) }));
1829
+ let frame = document_.createElement("iframe");
1830
+ frame.setAttribute("aria-hidden", "true");
1831
+ frame.style.cssText = "position:fixed;inset-block-start:0;inset-inline-start:0;inline-size:1px;block-size:1px;border:0;visibility:hidden";
1832
+ let cleanUp = () => {
1833
+ frame.remove();
1834
+ URL.revokeObjectURL(url);
1835
+ };
1836
+ try {
1837
+ await new Promise((resolve, reject) => {
1838
+ frame.addEventListener("load", () => resolve(), { once: true });
1839
+ frame.addEventListener("error", () => reject(/* @__PURE__ */ new Error("The report could not be loaded for printing")), { once: true });
1840
+ frame.src = url;
1841
+ document_.body.append(frame);
1842
+ });
1843
+ frame.contentWindow?.focus();
1844
+ frame.contentWindow?.print();
1845
+ } catch {
1846
+ cleanUp();
1847
+ return openReport(options);
1848
+ }
1849
+ window.setTimeout(cleanUp, 6e4);
1850
+ }
1851
+ /**
1852
+ * Parameters in the shape the route expects — `{ name, value }` objects.
1853
+ *
1854
+ * Empty values are dropped: the route skips them anyway, and a report falls back
1855
+ * to its own default when a parameter is not sent.
1856
+ */
1857
+ function toParameterEntries(parameters) {
1858
+ if (!parameters) return [];
1859
+ return Object.entries(parameters).filter(([, value]) => value !== null && value !== void 0 && value !== "").map(([name, value]) => ({
1860
+ name,
1861
+ value: typeof value === "boolean" ? String(value) : value
1862
+ }));
1863
+ }
1864
+
1865
+ //#endregion
1866
+ //#region src/report/report.ts
1867
+ /**
1868
+ * Mapping a `sviw_WinClient_MyReports` record onto the report model, including
1869
+ * which output formats the report offers.
1870
+ */
1871
+ function isSet(value) {
1872
+ return value === true || value === 1;
1873
+ }
1874
+ /**
1875
+ * The formats a report may be rendered to, in the order the launcher offers
1876
+ * them.
1877
+ *
1878
+ * `FormatCSV` covers the whole spreadsheet family: the Windows launcher enables
1879
+ * "save as XLS" and "save as XLSX" from the same flag, because they all come out
1880
+ * of the same DevExpress export.
1881
+ */
1882
+ function getReportFormats(record) {
1883
+ let formats = [];
1884
+ if (isSet(record.FormatPDF)) formats.push("PDF");
1885
+ if (isSet(record.FormatCSV)) formats.push("XLSX", "XLS", "CSV");
1886
+ if (isSet(record.FormatHTML)) formats.push("HTML");
1887
+ if (isSet(record.FormatRTF)) formats.push("RTF");
1888
+ if (isSet(record.FormatMHT)) formats.push("MHT");
1889
+ if (isSet(record.FormatTEXT)) formats.push("TEXT");
1890
+ if (isSet(record.FormatIMAGE)) formats.push("IMAGE");
1891
+ return formats;
1892
+ }
1893
+ /** Maps a report record onto the model the launcher renders. */
1894
+ function toReport(record) {
1895
+ let recordSource = parseRecordSource(record.RecordSource);
1896
+ return {
1897
+ reportId: record.ReportID ?? "",
1898
+ shortId: record.ShortID ?? null,
1899
+ title: record.Title?.trim() || null,
1900
+ description: record.Description?.trim() || null,
1901
+ viewName: recordSource?.viewName ?? null,
1902
+ initialFilter: recordSource?.filterString ?? null,
1903
+ hasTitle: isSet(record.HasTitle),
1904
+ hasHeader: isSet(record.HasHeader),
1905
+ formats: getReportFormats(record),
1906
+ timeout: record.Timeout ?? null
1907
+ };
1908
+ }
1909
+
1910
+ //#endregion
1911
+ //#region src/alert.ts
1912
+ const template = `
513
1913
  <dialog class="alert-dialog">
514
1914
  <form method="dialog">
515
1915
  <article></article>
@@ -519,160 +1919,130 @@ var template = `
519
1919
  </form>
520
1920
  </dialog>
521
1921
  `;
522
- if (window.document && !document.querySelector("#AlertDialogTemplate")) {
523
- let $template = document.createElement("template");
524
- $template.id = "AlertDialogTemplate";
525
- $template.innerHTML = template;
526
- document.body.append($template);
1922
+ function addDialogTemplate() {
1923
+ if (document.querySelector("#AlertDialogTemplate")) return;
1924
+ let $template = document.createElement("template");
1925
+ $template.id = "AlertDialogTemplate";
1926
+ $template.innerHTML = template;
1927
+ document.body.append($template);
1928
+ }
1929
+ if (window.document) {
1930
+ if (document.body) addDialogTemplate();
1931
+ else document.addEventListener("DOMContentLoaded", addDialogTemplate, { once: true });
527
1932
  }
528
1933
  function waitForDialog(dialog, cancelValue = "No") {
529
- return new Promise((resolve) => {
530
- let controller = new AbortController();
531
- dialog.addEventListener(
532
- "close",
533
- () => {
534
- resolve(dialog.returnValue);
535
- controller.abort();
536
- },
537
- { signal: controller.signal }
538
- );
539
- dialog.addEventListener(
540
- "cancel",
541
- () => {
542
- resolve(cancelValue);
543
- controller.abort();
544
- },
545
- { signal: controller.signal }
546
- );
547
- });
548
- }
549
- var alertDialogPromiseMap = /* @__PURE__ */ new Map();
1934
+ return new Promise((resolve) => {
1935
+ let controller = new AbortController();
1936
+ dialog.addEventListener("close", () => {
1937
+ resolve(dialog.returnValue);
1938
+ controller.abort();
1939
+ }, { signal: controller.signal });
1940
+ dialog.addEventListener("cancel", () => {
1941
+ resolve(cancelValue);
1942
+ controller.abort();
1943
+ }, { signal: controller.signal });
1944
+ });
1945
+ }
1946
+ const alertDialogPromiseMap = /* @__PURE__ */ new Map();
550
1947
  async function openAlertDialog({ buttons, content, className, id, title }) {
551
- if (id && alertDialogPromiseMap.has(id)) {
552
- return await alertDialogPromiseMap.get(id);
553
- }
554
- let $template = document.querySelector("#AlertDialogTemplate");
555
- if (!$template) throw Error("No alert dialog template found");
556
- let $dialog = $template.content.firstElementChild?.cloneNode(true);
557
- let $content = $dialog?.querySelector("article");
558
- let $menu = $dialog?.querySelector("footer menu");
559
- if (!$dialog || !$content || !$menu) throw Error("Invalid alert dialog template");
560
- if (className) {
561
- for (const className_ of className.split(/\s+/)) {
562
- $dialog?.classList.add(className_);
563
- }
564
- }
565
- if (title) {
566
- let $header = document.createElement("header");
567
- $header.append(title);
568
- $content.parentNode?.insertBefore($header, $content);
569
- }
570
- $content.appendChild(typeof content === "string" ? document.createTextNode(content) : content);
571
- for (let { label, value, primary } of buttons) {
572
- let listItem = document.createElement("li");
573
- let buttonElem = document.createElement("button");
574
- buttonElem.value = value;
575
- if (primary) {
576
- buttonElem.classList.add("primary");
577
- }
578
- buttonElem.textContent = label;
579
- listItem.appendChild(buttonElem);
580
- $menu.appendChild(buttonElem);
581
- }
582
- document.body.appendChild($dialog);
583
- $dialog.showModal();
584
- let dialogPromise = waitForDialog($dialog).then((returnValue) => {
585
- if (id && alertDialogPromiseMap.has(id)) {
586
- alertDialogPromiseMap.delete(id);
587
- }
588
- if ($dialog) document.body.removeChild($dialog);
589
- return returnValue;
590
- });
591
- if (id) {
592
- alertDialogPromiseMap.set(id, dialogPromise);
593
- }
594
- return await dialogPromise;
595
- }
596
- var ConfirmButtons = /* @__PURE__ */ ((ConfirmButtons2) => {
597
- ConfirmButtons2[ConfirmButtons2["YesNo"] = 0] = "YesNo";
598
- ConfirmButtons2[ConfirmButtons2["OkCancel"] = 1] = "OkCancel";
599
- return ConfirmButtons2;
600
- })(ConfirmButtons || {});
1948
+ if (id && alertDialogPromiseMap.has(id)) return await alertDialogPromiseMap.get(id);
1949
+ let $template = document.querySelector("#AlertDialogTemplate");
1950
+ if (!$template) throw Error("No alert dialog template found");
1951
+ let $dialog = $template.content.firstElementChild?.cloneNode(true);
1952
+ let $content = $dialog?.querySelector("article");
1953
+ let $menu = $dialog?.querySelector("footer menu");
1954
+ if (!$dialog || !$content || !$menu) throw Error("Invalid alert dialog template");
1955
+ if (className) for (const className_ of className.split(/\s+/)) $dialog?.classList.add(className_);
1956
+ if (title) {
1957
+ let $header = document.createElement("header");
1958
+ $header.append(title);
1959
+ $content.parentNode?.insertBefore($header, $content);
1960
+ }
1961
+ $content.appendChild(typeof content === "string" ? document.createTextNode(content) : content);
1962
+ for (let { label, value, primary } of buttons) {
1963
+ let listItem = document.createElement("li");
1964
+ let buttonElem = document.createElement("button");
1965
+ buttonElem.value = value;
1966
+ if (primary) buttonElem.classList.add("primary");
1967
+ buttonElem.textContent = label;
1968
+ listItem.appendChild(buttonElem);
1969
+ $menu.appendChild(buttonElem);
1970
+ }
1971
+ document.body.appendChild($dialog);
1972
+ $dialog.showModal();
1973
+ let dialogPromise = waitForDialog($dialog).then((returnValue) => {
1974
+ if (id && alertDialogPromiseMap.has(id)) alertDialogPromiseMap.delete(id);
1975
+ if ($dialog) document.body.removeChild($dialog);
1976
+ return returnValue;
1977
+ });
1978
+ if (id) alertDialogPromiseMap.set(id, dialogPromise);
1979
+ return await dialogPromise;
1980
+ }
1981
+ let ConfirmButtons = /* @__PURE__ */ function(ConfirmButtons) {
1982
+ ConfirmButtons[ConfirmButtons["YesNo"] = 0] = "YesNo";
1983
+ ConfirmButtons[ConfirmButtons["OkCancel"] = 1] = "OkCancel";
1984
+ return ConfirmButtons;
1985
+ }({});
601
1986
  async function confirm(prompt, options = {}) {
602
- let { buttons: optionButtons = 0 /* YesNo */, title } = options;
603
- let buttons = optionButtons === 1 /* OkCancel */ ? [
604
- { label: getLocalizedString("OK"), value: "yes", primary: true },
605
- { label: getLocalizedString("Cancel"), value: "no" }
606
- ] : [
607
- { label: getLocalizedString("Yes"), value: "yes", primary: true },
608
- { label: getLocalizedString("No"), value: "no" }
609
- ];
610
- let result = await openAlertDialog({ content: prompt, buttons, className: "alert-dialog-confirm", title });
611
- return result === "yes";
1987
+ let { buttons: optionButtons = 0, title } = options;
1988
+ return await openAlertDialog({
1989
+ content: prompt,
1990
+ buttons: optionButtons === 1 ? [{
1991
+ label: getLocalizedString("OK"),
1992
+ value: "yes",
1993
+ primary: true
1994
+ }, {
1995
+ label: getLocalizedString("Cancel"),
1996
+ value: "no"
1997
+ }] : [{
1998
+ label: getLocalizedString("Yes"),
1999
+ value: "yes",
2000
+ primary: true
2001
+ }, {
2002
+ label: getLocalizedString("No"),
2003
+ value: "no"
2004
+ }],
2005
+ className: "alert-dialog-confirm",
2006
+ title
2007
+ }) === "yes";
612
2008
  }
613
2009
  async function alert(prompt, options = {}) {
614
- await openAlertDialog({
615
- content: prompt,
616
- className: "alert-dialog-alert",
617
- buttons: [{ label: getLocalizedString("OK"), value: "ok", primary: true }],
618
- ...options
619
- });
620
- }
621
-
622
- // src/settings.ts
623
- function getKey(article2) {
624
- const articleKey = article2 ?? window.af?.article?.id ?? window.window?.location.pathname.substring(1).split("/")[0];
625
- return `${articleKey}.${window.af?.userSession.login ?? "anonymous"}`;
626
- }
627
- function getSettings(setting, article2) {
628
- if (!window.af?.userSession) return null;
629
- const key = getKey(article2);
630
- const settings = JSON.parse(localStorage.getItem(key) || "{}");
631
- if (setting) {
632
- return settings[setting] || null;
633
- }
634
- return settings;
635
- }
636
- function saveSettings(setting, value, article2) {
637
- if (!window.af?.userSession) return;
638
- const key = getKey(article2);
639
- let userSettings = JSON.parse(localStorage.getItem(key) || "{}");
640
- if (typeof value !== "undefined") {
641
- userSettings[setting] = value;
642
- } else {
643
- userSettings = setting;
644
- }
645
- localStorage.setItem(key, JSON.stringify(userSettings));
646
- }
647
-
648
- // src/index.ts
649
- var version = "2.11.9";
650
- export {
651
- ConfirmButtons,
652
- SessionHandler,
653
- UserSession,
654
- alert,
655
- confirm,
656
- downloadBlob,
657
- downloadRequest,
658
- expose,
659
- getLocalizedString,
660
- getSessionData,
661
- getSettings,
662
- getUserImage,
663
- invariant,
664
- localStorage_default as localStorage,
665
- localize,
666
- logActivity,
667
- logError,
668
- mitt_default as mitt,
669
- openAlertDialog,
670
- saveSettings,
671
- startActivity,
672
- time,
673
- toLocalDateTime,
674
- toLocalISODate,
675
- toLocalISODateTime,
676
- version,
677
- waitForDialog
678
- };
2010
+ await openAlertDialog({
2011
+ content: prompt,
2012
+ className: "alert-dialog-alert",
2013
+ buttons: [{
2014
+ label: getLocalizedString("OK"),
2015
+ value: "ok",
2016
+ primary: true
2017
+ }],
2018
+ ...options
2019
+ });
2020
+ }
2021
+
2022
+ //#endregion
2023
+ //#region src/settings.ts
2024
+ function getKey(article) {
2025
+ return `${article ?? window.af?.article?.id ?? window.window?.location.pathname.substring(1).split("/")[0]}.${window.af?.userSession.login ?? "anonymous"}`;
2026
+ }
2027
+ function getSettings(setting, article) {
2028
+ if (!window.af?.userSession) return null;
2029
+ const key = getKey(article);
2030
+ const settings = JSON.parse(localStorage.getItem(key) || "{}");
2031
+ if (setting) return settings[setting] || null;
2032
+ return settings;
2033
+ }
2034
+ function saveSettings(setting, value, article) {
2035
+ if (!window.af?.userSession) return;
2036
+ const key = getKey(article);
2037
+ let userSettings = JSON.parse(localStorage.getItem(key) || "{}");
2038
+ if (typeof value !== "undefined") userSettings[setting] = value;
2039
+ else userSettings = setting;
2040
+ localStorage.setItem(key, JSON.stringify(userSettings));
2041
+ }
2042
+
2043
+ //#endregion
2044
+ //#region src/index.ts
2045
+ const version = "2.11.10";
2046
+
2047
+ //#endregion
2048
+ export { ConfirmButtons, NO_FILTER_ID, RELATIVE_DATE_VALUES, SessionHandler, UserSession, addGroupAtPath, alert, canDeleteSavedFilter, canEditSavedFilter, canRenameSavedFilter, canSetCrossDomain, canShareSavedFilter, changeOperator, coerceParameterValue, coerceToStandardLayout, confirm, convertFilter, countExpressions, createEmptyFilter, createEmptyGroup, createExpression, decodeXml, describeFilter, downloadBlob, downloadReport, downloadRequest, encodeXml, expose, fetchParameterDefault, findSavedFilter, getDefaultOperator, getDefaultParameterValues, getDynamicValueLabel, getDynamicValuesForField, getLocalizedString, getNodeAtPath, getOperatorArity, getOperatorLabel, getOperatorsForField, getReportExtension, getReportFileName, getReportFormats, getReportMediaType, getReportRequest, getSessionData, getSettings, getUserImage, getValueType, insertNodeAtPath, invariant, isCompleteExpression, isEmptyFilter, isExpression, isGroup, isProcedureDefault, isStandardLayout, localStorage_default as localStorage, localize, logActivity, logError, mitt_default as mitt, normalizeOperator, openAlertDialog, openReport, parseParameterItems, parseParameters, parseRecordSource, partitionSavedFilters, printReport, pruneFilter, readElement, readElements, removeNodeAtPath, renderReport, resolveParameterDefaults, restoreParameterValues, saveSettings, serializeParameters, setGroupMode, startActivity, time, toFieldMetadata, toFieldMetadataList, toFilterFieldType, toFilterTree, toLocalDateTime, toLocalISODate, toLocalISODateTime, toReport, toReportParameter, toReportParameters, toSavedFilter, toSavedFilters, updateNodeAtPath, version, waitForDialog };