dsh-artifact-studio 0.7.3 → 0.9.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.
@@ -0,0 +1,463 @@
1
+ /**
2
+ * The handful of common spreadsheet functions the bundled parser leaves as
3
+ * stubs or does not register. fast-formula-parser ships 343 names, but MAX,
4
+ * MIN, MEDIAN, MATCH, SUMIFS and several others are empty placeholders in
5
+ * 1.0.19. These implementations fill the gaps that a real sheet hits, using
6
+ * the parser's evaluated argument shape and its FormulaError instances.
7
+ */
8
+ function isErrorValue(value) {
9
+ if (value === null || typeof value !== 'object')
10
+ return false;
11
+ const record = { ...value };
12
+ return typeof record._error === 'string';
13
+ }
14
+ function argOf(raw) {
15
+ if (raw !== null && typeof raw === 'object')
16
+ return { ...raw };
17
+ return { value: raw };
18
+ }
19
+ /**
20
+ * The scalar values of one argument. A range becomes a flat list; a cell or
21
+ * literal stays one value.
22
+ * @param raw the parser argument.
23
+ * @returns the values and whether the argument was a range.
24
+ */
25
+ function valuesOf(raw) {
26
+ const arg = argOf(raw);
27
+ const value = arg.value;
28
+ if (Array.isArray(value))
29
+ return { values: value.flat(Infinity), range: true };
30
+ return { values: [value], range: arg.isRangeRef === true || arg.isArray === true };
31
+ }
32
+ function throwIfError(value) {
33
+ if (isErrorValue(value))
34
+ throw value;
35
+ }
36
+ function firstValue(raw) {
37
+ const { values } = valuesOf(raw);
38
+ return values[0];
39
+ }
40
+ function textOf(value) {
41
+ if (value === null || value === undefined)
42
+ return '';
43
+ if (typeof value === 'boolean')
44
+ return value ? 'TRUE' : 'FALSE';
45
+ if (typeof value === 'number')
46
+ return String(value);
47
+ return String(value);
48
+ }
49
+ function numberOf(raw, fallback) {
50
+ const value = firstValue(raw);
51
+ if (value === null || value === undefined || value === '')
52
+ return fallback;
53
+ if (typeof value === 'number')
54
+ return value;
55
+ if (typeof value === 'boolean')
56
+ return value ? 1 : 0;
57
+ const number = Number(String(value).trim());
58
+ return Number.isFinite(number) ? number : undefined;
59
+ }
60
+ /**
61
+ * Collect numbers with Excel's range rules: booleans and text inside a range
62
+ * are ignored, a direct boolean becomes 1 or 0, and a numeric string becomes a
63
+ * number. An error value propagates.
64
+ * @param raws the arguments.
65
+ * @returns the numbers.
66
+ */
67
+ function numbersOf(raws) {
68
+ const numbers = [];
69
+ for (const raw of raws) {
70
+ const { values, range } = valuesOf(raw);
71
+ for (const value of values) {
72
+ throwIfError(value);
73
+ if (typeof value === 'number') {
74
+ if (Number.isFinite(value))
75
+ numbers.push(value);
76
+ }
77
+ else if (!range && typeof value === 'boolean') {
78
+ numbers.push(value ? 1 : 0);
79
+ }
80
+ else if (!range && typeof value === 'string' && value.trim() !== '') {
81
+ const number = Number(value.trim());
82
+ if (Number.isFinite(number))
83
+ numbers.push(number);
84
+ }
85
+ }
86
+ }
87
+ return numbers;
88
+ }
89
+ function maximum(values) {
90
+ let result = Number.NEGATIVE_INFINITY;
91
+ for (const value of values)
92
+ result = Math.max(result, value);
93
+ return result;
94
+ }
95
+ function minimum(values) {
96
+ let result = Number.POSITIVE_INFINITY;
97
+ for (const value of values)
98
+ result = Math.min(result, value);
99
+ return result;
100
+ }
101
+ function wildcard(text, pattern) {
102
+ const source = '^' + pattern
103
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
104
+ .replace(/\*/g, '.*')
105
+ .replace(/\?/g, '.') + '$';
106
+ return new RegExp(source, 'i').test(text);
107
+ }
108
+ function looseEqual(left, right) {
109
+ throwIfError(left);
110
+ throwIfError(right);
111
+ if (typeof left === 'number' && typeof right === 'number')
112
+ return left === right;
113
+ const leftNumber = typeof left === 'number' ? left : Number(String(left ?? '').trim());
114
+ const rightNumber = typeof right === 'number' ? right : Number(String(right ?? '').trim());
115
+ const leftNumeric = typeof left === 'number' || (typeof left === 'string' && left.trim() !== '' && /^[+\-]?\d/.test(left.trim()));
116
+ const rightNumeric = typeof right === 'number' || (typeof right === 'string' && right.trim() !== '' && /^[+\-]?\d/.test(right.trim()));
117
+ if (leftNumeric && rightNumeric && Number.isFinite(leftNumber) && Number.isFinite(rightNumber))
118
+ return leftNumber === rightNumber;
119
+ const pattern = textOf(right);
120
+ if (/[*?]/.test(pattern))
121
+ return wildcard(textOf(left), pattern);
122
+ return textOf(left).toLowerCase() === pattern.toLowerCase();
123
+ }
124
+ function criteriaMatches(value, criteria) {
125
+ throwIfError(value);
126
+ throwIfError(criteria);
127
+ let operation = '=';
128
+ let target = criteria;
129
+ if (typeof criteria === 'string') {
130
+ const match = /^(<=|>=|<>|<|>|=)([\s\S]*)$/.exec(criteria);
131
+ if (match !== null) {
132
+ operation = match[1] ?? '=';
133
+ target = (match[2] ?? '').trim();
134
+ }
135
+ }
136
+ if (operation === '=' || operation === '<>') {
137
+ const equal = looseEqual(value, target);
138
+ return operation === '=' ? equal : !equal;
139
+ }
140
+ const leftText = typeof value === 'number' ? value : Number(textOf(value));
141
+ const rightText = typeof target === 'number' ? target : Number(textOf(target));
142
+ if (!Number.isFinite(leftText) || !Number.isFinite(rightText)) {
143
+ const a = textOf(value).toLowerCase();
144
+ const b = textOf(target).toLowerCase();
145
+ switch (operation) {
146
+ case '<': return a < b;
147
+ case '>': return a > b;
148
+ case '<=': return a <= b;
149
+ case '>=': return a >= b;
150
+ default: return false;
151
+ }
152
+ }
153
+ switch (operation) {
154
+ case '<': return leftText < rightText;
155
+ case '>': return leftText > rightText;
156
+ case '<=': return leftText <= rightText;
157
+ case '>=': return leftText >= rightText;
158
+ default: return false;
159
+ }
160
+ }
161
+ /**
162
+ * Walk criteria range and criteria value pairs, keeping the positions where
163
+ * every pair matches.
164
+ * @param raws the raw arguments starting at the first criteria range.
165
+ * @param valueCount how many positions the target range has.
166
+ * @returns matching zero-based positions, or undefined when the ranges differ.
167
+ */
168
+ function matchingIndices(raws, valueCount) {
169
+ if (raws.length === 0 || raws.length % 2 !== 0)
170
+ return undefined;
171
+ const indices = [];
172
+ for (let index = 0; index < valueCount; index += 1)
173
+ indices.push(index);
174
+ for (let pair = 0; pair < raws.length; pair += 2) {
175
+ const values = valuesOf(raws[pair]).values;
176
+ const criteria = firstValue(raws[pair + 1]);
177
+ if (values.length !== valueCount)
178
+ return undefined;
179
+ for (let index = indices.length - 1; index >= 0; index -= 1) {
180
+ const position = indices[index];
181
+ if (position === undefined)
182
+ continue;
183
+ if (!criteriaMatches(values[position], criteria))
184
+ indices.splice(index, 1);
185
+ }
186
+ }
187
+ return indices;
188
+ }
189
+ function sampleVariance(raws, sample, errors) {
190
+ const values = numbersOf(raws);
191
+ if (values.length === 0 || (sample && values.length < 2))
192
+ throw errors.div0;
193
+ const mean = values.reduce((sum, value) => sum + value, 0) / values.length;
194
+ const squares = values.reduce((sum, value) => sum + (value - mean) ** 2, 0);
195
+ return squares / (sample ? values.length - 1 : values.length);
196
+ }
197
+ function sampleDeviation(raws, sample, errors) {
198
+ return Math.sqrt(sampleVariance(raws, sample, errors));
199
+ }
200
+ /**
201
+ * Read an argument that the parser passed as a raw reference for a context
202
+ * function. Literals and already-extracted values pass through.
203
+ * @param raw the raw argument.
204
+ * @param context the parser context, when present.
205
+ * @returns the value.
206
+ */
207
+ function extractArgument(raw, context) {
208
+ if (context !== undefined) {
209
+ try {
210
+ return context.utils.extractRefValue(raw).val;
211
+ }
212
+ catch {
213
+ return raw;
214
+ }
215
+ }
216
+ return argOf(raw).value;
217
+ }
218
+ /**
219
+ * Build the custom functions for one parser.
220
+ * @param errors the parser's error singletons.
221
+ * @returns the function map.
222
+ */
223
+ export function createSheetFunctions(errors) {
224
+ const aggregate = (raws, pick) => {
225
+ const values = numbersOf(raws);
226
+ return values.length === 0 ? 0 : pick(values);
227
+ };
228
+ const filteredNumbers = (raws) => {
229
+ const target = valuesOf(raws[0]).values;
230
+ const positions = matchingIndices(raws.slice(1), target.length);
231
+ if (positions === undefined)
232
+ return undefined;
233
+ const result = [];
234
+ for (const position of positions) {
235
+ const value = target[position];
236
+ throwIfError(value);
237
+ if (typeof value === 'number')
238
+ result.push(value);
239
+ }
240
+ return result;
241
+ };
242
+ return {
243
+ MAX: (...raws) => aggregate(raws, maximum),
244
+ MIN: (...raws) => aggregate(raws, minimum),
245
+ MEDIAN: (...raws) => {
246
+ const values = [...numbersOf(raws)].sort((left, right) => left - right);
247
+ if (values.length === 0)
248
+ throw errors.num;
249
+ const middle = Math.floor(values.length / 2);
250
+ if (values.length % 2 === 1)
251
+ return values[middle];
252
+ return ((values[middle - 1] ?? 0) + (values[middle] ?? 0)) / 2;
253
+ },
254
+ LARGE: (...raws) => {
255
+ const values = [...numbersOf([raws[0]])].sort((left, right) => right - left);
256
+ const rank = numberOf(raws[1], undefined);
257
+ if (rank === undefined || !Number.isInteger(rank) || rank < 1 || rank > values.length)
258
+ throw errors.num;
259
+ return values[rank - 1];
260
+ },
261
+ SMALL: (...raws) => {
262
+ const values = [...numbersOf([raws[0]])].sort((left, right) => left - right);
263
+ const rank = numberOf(raws[1], undefined);
264
+ if (rank === undefined || !Number.isInteger(rank) || rank < 1 || rank > values.length)
265
+ throw errors.num;
266
+ return values[rank - 1];
267
+ },
268
+ COUNTA: (...raws) => {
269
+ let count = 0;
270
+ for (const raw of raws) {
271
+ const { values } = valuesOf(raw);
272
+ for (const value of values) {
273
+ if (isErrorValue(value)) {
274
+ count += 1;
275
+ continue;
276
+ }
277
+ if (value !== null && value !== undefined && value !== '')
278
+ count += 1;
279
+ }
280
+ }
281
+ return count;
282
+ },
283
+ COUNTBLANK: (...raws) => {
284
+ let count = 0;
285
+ for (const raw of raws) {
286
+ const { values } = valuesOf(raw);
287
+ for (const value of values) {
288
+ if (value === null || value === undefined || value === '')
289
+ count += 1;
290
+ }
291
+ }
292
+ return count;
293
+ },
294
+ MATCH: (...raws) => {
295
+ const lookup = firstValue(raws[0]);
296
+ const values = valuesOf(raws[1]).values;
297
+ const type = (raws[2] === undefined ? 1 : numberOf(raws[2], 1)) ?? 1;
298
+ for (let index = 0; index < values.length; index += 1) {
299
+ if (looseEqual(values[index], lookup))
300
+ return index + 1;
301
+ }
302
+ if (type === 0)
303
+ throw errors.na;
304
+ let best = -1;
305
+ for (let index = 0; index < values.length; index += 1) {
306
+ const value = values[index];
307
+ throwIfError(value);
308
+ const left = Number(textOf(value));
309
+ const right = Number(textOf(lookup));
310
+ if (!Number.isFinite(left) || !Number.isFinite(right))
311
+ continue;
312
+ if (type > 0 ? left <= right : left >= right)
313
+ best = index;
314
+ }
315
+ if (best < 0)
316
+ throw errors.na;
317
+ return best + 1;
318
+ },
319
+ INDEX: (...raws) => {
320
+ // INDEX is one of the parser's context functions: it receives the parser
321
+ // context first and raw references, not the usual { value } envelopes.
322
+ const first = raws[0];
323
+ const context = first !== null && typeof first === 'object' && 'utils' in first ? first : undefined;
324
+ const args = context === undefined ? raws : raws.slice(1);
325
+ const extracted = extractArgument(args[0], context);
326
+ const rowRaw = extractArgument(args[1], context);
327
+ const row = Number(rowRaw);
328
+ if (!Number.isInteger(row) || row < 1)
329
+ throw errors.value;
330
+ let matrix;
331
+ if (Array.isArray(extracted) && extracted.length > 0 && Array.isArray(extracted[0])) {
332
+ matrix = extracted;
333
+ }
334
+ else if (Array.isArray(extracted)) {
335
+ matrix = [extracted];
336
+ }
337
+ else {
338
+ matrix = [[extracted]];
339
+ }
340
+ if (matrix.length === 1 || (matrix[0]?.length ?? 0) === 1) {
341
+ const line = matrix.length === 1 ? matrix[0] ?? [] : matrix.map((entries) => entries[0]);
342
+ const item = line[row - 1];
343
+ if (item === undefined)
344
+ throw errors.ref;
345
+ throwIfError(item);
346
+ return item;
347
+ }
348
+ const columnRaw = args[2] === undefined ? 1 : Number(extractArgument(args[2], context));
349
+ if (!Number.isInteger(columnRaw) || columnRaw < 1)
350
+ throw errors.value;
351
+ const line = matrix[row - 1];
352
+ const item = line?.[columnRaw - 1];
353
+ if (item === undefined)
354
+ throw errors.ref;
355
+ throwIfError(item);
356
+ return item;
357
+ },
358
+ LOOKUP: (...raws) => {
359
+ const lookup = firstValue(raws[0]);
360
+ const lookupValues = valuesOf(raws[1]).values;
361
+ const resultValues = raws[2] === undefined ? lookupValues : valuesOf(raws[2]).values;
362
+ let best = -1;
363
+ for (let index = 0; index < lookupValues.length; index += 1) {
364
+ const value = lookupValues[index];
365
+ throwIfError(value);
366
+ const left = Number(textOf(value));
367
+ const right = Number(textOf(lookup));
368
+ if (!Number.isFinite(left) || !Number.isFinite(right))
369
+ continue;
370
+ if (left <= right)
371
+ best = index;
372
+ }
373
+ if (best < 0 || resultValues[best] === undefined)
374
+ throw errors.na;
375
+ return resultValues[best];
376
+ },
377
+ RANK: (...raws) => {
378
+ const target = numberOf(raws[0], undefined);
379
+ if (target === undefined)
380
+ throw errors.value;
381
+ const values = numbersOf([raws[1]]);
382
+ const ascending = numberOf(raws[2], 0) === 1;
383
+ if (!values.includes(target))
384
+ throw errors.na;
385
+ const better = values.filter((value) => (ascending ? value < target : value > target)).length;
386
+ return better + 1;
387
+ },
388
+ STDEV: (...raws) => sampleDeviation(raws, true, errors),
389
+ STDEVP: (...raws) => sampleDeviation(raws, false, errors),
390
+ VAR: (...raws) => sampleVariance(raws, true, errors),
391
+ VARP: (...raws) => sampleVariance(raws, false, errors),
392
+ SUMIFS: (...raws) => {
393
+ const values = filteredNumbers(raws);
394
+ if (values === undefined)
395
+ throw errors.value;
396
+ return values.reduce((sum, value) => sum + value, 0);
397
+ },
398
+ COUNTIFS: (...raws) => {
399
+ const positions = matchingIndices(raws, valuesOf(raws[0]).values.length);
400
+ if (positions === undefined)
401
+ throw errors.value;
402
+ return positions.length;
403
+ },
404
+ AVERAGEIFS: (...raws) => {
405
+ const values = filteredNumbers(raws);
406
+ if (values === undefined)
407
+ throw errors.value;
408
+ if (values.length === 0)
409
+ throw errors.div0;
410
+ return values.reduce((sum, value) => sum + value, 0) / values.length;
411
+ },
412
+ MAXIFS: (...raws) => {
413
+ const values = filteredNumbers(raws);
414
+ if (values === undefined || values.length === 0)
415
+ throw errors.value;
416
+ return maximum(values);
417
+ },
418
+ MINIFS: (...raws) => {
419
+ const values = filteredNumbers(raws);
420
+ if (values === undefined || values.length === 0)
421
+ throw errors.value;
422
+ return minimum(values);
423
+ },
424
+ UPPER: (raw) => textOf(firstValue(raw)).toUpperCase(),
425
+ VALUE: (raw) => {
426
+ const text = textOf(firstValue(raw)).trim();
427
+ const number = Number(text);
428
+ if (text === '' || !Number.isFinite(number))
429
+ throw errors.value;
430
+ return number;
431
+ },
432
+ TEXTJOIN: (...raws) => {
433
+ const separator = textOf(firstValue(raws[0]));
434
+ const ignoreEmpty = firstValue(raws[1]) === true || textOf(firstValue(raws[1])).toUpperCase() === 'TRUE';
435
+ const parts = [];
436
+ for (const raw of raws.slice(2)) {
437
+ const { values } = valuesOf(raw);
438
+ for (const value of values) {
439
+ throwIfError(value);
440
+ if (ignoreEmpty && (value === null || value === undefined || value === ''))
441
+ continue;
442
+ parts.push(textOf(value));
443
+ }
444
+ }
445
+ return parts.join(separator);
446
+ },
447
+ XLOOKUP: (...raws) => {
448
+ const lookup = firstValue(raws[0]);
449
+ const lookupValues = valuesOf(raws[1]).values;
450
+ const resultValues = valuesOf(raws[2]).values;
451
+ for (let index = 0; index < lookupValues.length; index += 1) {
452
+ if (looseEqual(lookupValues[index], lookup)) {
453
+ const result = resultValues[index];
454
+ throwIfError(result);
455
+ return result;
456
+ }
457
+ }
458
+ if (raws[3] !== undefined)
459
+ return firstValue(raws[3]);
460
+ throw errors.na;
461
+ },
462
+ };
463
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The shared sheet toolkit: model, formula evaluation, structural operations,
3
+ * and read-only views. The host and the panel import this same entry, so a
4
+ * saved sheet, a gallery cover, a print copy, and an XLSX export agree.
5
+ */
6
+ export * from './model.js';
7
+ export * from './formula.js';
8
+ export * from './operations.js';
9
+ export * from './output.js';