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