@blackbelt-technology/pi-dashboard-cost-estimator 0.7.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.
- package/.pi/skills/software-cost-estimator/SKILL.md +200 -0
- package/.pi/skills/software-cost-estimator/assets/calibration/reference-classes.md +126 -0
- package/.pi/skills/software-cost-estimator/assets/calibration/wms-reference.yaml +217 -0
- package/.pi/skills/software-cost-estimator/assets/example-quality-hub.yaml +230 -0
- package/.pi/skills/software-cost-estimator/assets/rates.default.yaml +106 -0
- package/.pi/skills/software-cost-estimator/assets/templates/architecture-plan.md +115 -0
- package/.pi/skills/software-cost-estimator/assets/templates/offer-summary.md +99 -0
- package/.pi/skills/software-cost-estimator/references/ai-delivery-modes.md +276 -0
- package/.pi/skills/software-cost-estimator/references/business-case.md +134 -0
- package/.pi/skills/software-cost-estimator/references/nfr-catalog.md +112 -0
- package/.pi/skills/software-cost-estimator/references/rates.md +84 -0
- package/.pi/skills/software-cost-estimator/references/role-model.md +109 -0
- package/.pi/skills/software-cost-estimator/references/sizing-methods.md +147 -0
- package/README.md +113 -0
- package/bin/calibrate-sessions.mjs +12 -0
- package/bin/calibrate.mjs +12 -0
- package/bin/estimate.mjs +12 -0
- package/package.json +96 -0
- package/src/bin/calibrate-sessions.ts +247 -0
- package/src/bin/calibrate.ts +77 -0
- package/src/bin/estimate.ts +129 -0
- package/src/client/index.tsx +300 -0
- package/src/configSchema.json +56 -0
- package/src/engine/businesscase.ts +139 -0
- package/src/engine/defaults.ts +354 -0
- package/src/engine/effort.ts +119 -0
- package/src/engine/estimate.ts +135 -0
- package/src/engine/modes.ts +312 -0
- package/src/engine/report.ts +239 -0
- package/src/engine/roles.ts +82 -0
- package/src/engine/simulate.ts +114 -0
- package/src/engine/sizing.ts +108 -0
- package/src/engine/types.ts +288 -0
- package/src/engine/workbook.ts +143 -0
- package/src/engine/xlsx.ts +228 -0
- package/src/engine/yaml.ts +205 -0
- package/src/server/index.ts +123 -0
- package/src/telemetry/sessions.ts +380 -0
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal zero-dependency XLSX writer.
|
|
3
|
+
*
|
|
4
|
+
* Produces a valid OOXML workbook by emitting the required parts and storing
|
|
5
|
+
* them with a hand-rolled ZIP (stored/no-compression entries + CRC32). No
|
|
6
|
+
* external library, no `zip` binary needed.
|
|
7
|
+
*
|
|
8
|
+
* Scope: multiple sheets, string/number cells, bold header row. That is all the
|
|
9
|
+
* estimator needs — a client-pokeable model, not a formatting exercise.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export type Cell = string | number | null;
|
|
13
|
+
export interface Sheet {
|
|
14
|
+
name: string;
|
|
15
|
+
rows: Cell[][];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const CRC_TABLE = (() => {
|
|
19
|
+
const table = new Uint32Array(256);
|
|
20
|
+
for (let i = 0; i < 256; i++) {
|
|
21
|
+
let c = i;
|
|
22
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
23
|
+
table[i] = c >>> 0;
|
|
24
|
+
}
|
|
25
|
+
return table;
|
|
26
|
+
})();
|
|
27
|
+
|
|
28
|
+
function crc32(data: Uint8Array): number {
|
|
29
|
+
let c = 0xffffffff;
|
|
30
|
+
for (let i = 0; i < data.length; i++) c = CRC_TABLE[(c ^ data[i]) & 0xff] ^ (c >>> 8);
|
|
31
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function escapeXml(value: string): string {
|
|
35
|
+
return value
|
|
36
|
+
.replace(/&/g, '&')
|
|
37
|
+
.replace(/</g, '<')
|
|
38
|
+
.replace(/>/g, '>')
|
|
39
|
+
.replace(/"/g, '"')
|
|
40
|
+
.replace(/'/g, ''')
|
|
41
|
+
// Strip control chars XML forbids.
|
|
42
|
+
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, '');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Convert a zero-based column index to an A1 column name. */
|
|
46
|
+
function columnName(index: number): string {
|
|
47
|
+
let name = '';
|
|
48
|
+
let n = index;
|
|
49
|
+
do {
|
|
50
|
+
name = String.fromCharCode(65 + (n % 26)) + name;
|
|
51
|
+
n = Math.floor(n / 26) - 1;
|
|
52
|
+
} while (n >= 0);
|
|
53
|
+
return name;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function sheetXml(sheet: Sheet): string {
|
|
57
|
+
const rows = sheet.rows
|
|
58
|
+
.map((row, rowIndex) => {
|
|
59
|
+
const cells = row
|
|
60
|
+
.map((cell, colIndex) => {
|
|
61
|
+
if (cell === null || cell === undefined || cell === '') return '';
|
|
62
|
+
const ref = `${columnName(colIndex)}${rowIndex + 1}`;
|
|
63
|
+
const style = rowIndex === 0 ? ' s="1"' : '';
|
|
64
|
+
if (typeof cell === 'number' && Number.isFinite(cell)) {
|
|
65
|
+
return `<c r="${ref}"${style}><v>${cell}</v></c>`;
|
|
66
|
+
}
|
|
67
|
+
return `<c r="${ref}"${style} t="inlineStr"><is><t xml:space="preserve">${escapeXml(String(cell))}</t></is></c>`;
|
|
68
|
+
})
|
|
69
|
+
.join('');
|
|
70
|
+
return `<row r="${rowIndex + 1}">${cells}</row>`;
|
|
71
|
+
})
|
|
72
|
+
.join('');
|
|
73
|
+
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${rows}</sheetData></worksheet>`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Excel forbids : \\ / ? * [ ] in sheet names and caps them at 31 chars. */
|
|
77
|
+
function safeSheetName(name: string, index: number): string {
|
|
78
|
+
const cleaned = name.replace(/[:\\/?*[\]]/g, '-').slice(0, 31);
|
|
79
|
+
return cleaned || `Sheet${index + 1}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Build an .xlsx file as bytes. */
|
|
83
|
+
export function buildXlsx(sheets: Sheet[]): Uint8Array {
|
|
84
|
+
const names = sheets.map((s, i) => safeSheetName(s.name, i));
|
|
85
|
+
const files: Array<{ path: string; content: string }> = [];
|
|
86
|
+
|
|
87
|
+
files.push({
|
|
88
|
+
path: '[Content_Types].xml',
|
|
89
|
+
content:
|
|
90
|
+
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
91
|
+
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
|
|
92
|
+
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
|
|
93
|
+
'<Default Extension="xml" ContentType="application/xml"/>' +
|
|
94
|
+
'<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' +
|
|
95
|
+
'<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>' +
|
|
96
|
+
sheets
|
|
97
|
+
.map(
|
|
98
|
+
(_, i) =>
|
|
99
|
+
`<Override PartName="/xl/worksheets/sheet${i + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`,
|
|
100
|
+
)
|
|
101
|
+
.join('') +
|
|
102
|
+
'</Types>',
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
files.push({
|
|
106
|
+
path: '_rels/.rels',
|
|
107
|
+
content:
|
|
108
|
+
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
109
|
+
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
|
110
|
+
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>' +
|
|
111
|
+
'</Relationships>',
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
files.push({
|
|
115
|
+
path: 'xl/workbook.xml',
|
|
116
|
+
content:
|
|
117
|
+
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
118
|
+
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ' +
|
|
119
|
+
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets>' +
|
|
120
|
+
names.map((n, i) => `<sheet name="${escapeXml(n)}" sheetId="${i + 1}" r:id="rId${i + 1}"/>`).join('') +
|
|
121
|
+
'</sheets></workbook>',
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
files.push({
|
|
125
|
+
path: 'xl/_rels/workbook.xml.rels',
|
|
126
|
+
content:
|
|
127
|
+
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
128
|
+
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
|
|
129
|
+
sheets
|
|
130
|
+
.map(
|
|
131
|
+
(_, i) =>
|
|
132
|
+
`<Relationship Id="rId${i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${i + 1}.xml"/>`,
|
|
133
|
+
)
|
|
134
|
+
.join('') +
|
|
135
|
+
`<Relationship Id="rId${sheets.length + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>` +
|
|
136
|
+
'</Relationships>',
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
files.push({
|
|
140
|
+
path: 'xl/styles.xml',
|
|
141
|
+
content:
|
|
142
|
+
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
|
|
143
|
+
'<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">' +
|
|
144
|
+
'<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font>' +
|
|
145
|
+
'<font><b/><sz val="11"/><name val="Calibri"/></font></fonts>' +
|
|
146
|
+
'<fills count="1"><fill><patternFill patternType="none"/></fill></fills>' +
|
|
147
|
+
'<borders count="1"><border/></borders>' +
|
|
148
|
+
'<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' +
|
|
149
|
+
'<cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' +
|
|
150
|
+
'<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/></cellXfs>' +
|
|
151
|
+
'<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>' +
|
|
152
|
+
'</styleSheet>',
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
sheets.forEach((sheet, i) => {
|
|
156
|
+
files.push({ path: `xl/worksheets/sheet${i + 1}.xml`, content: sheetXml(sheet) });
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
return zip(files);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Build a ZIP archive with stored (uncompressed) entries. */
|
|
163
|
+
function zip(files: Array<{ path: string; content: string }>): Uint8Array {
|
|
164
|
+
const encoder = new TextEncoder();
|
|
165
|
+
const locals: Uint8Array[] = [];
|
|
166
|
+
const centrals: Uint8Array[] = [];
|
|
167
|
+
let offset = 0;
|
|
168
|
+
|
|
169
|
+
for (const file of files) {
|
|
170
|
+
const nameBytes = encoder.encode(file.path);
|
|
171
|
+
const data = encoder.encode(file.content);
|
|
172
|
+
const crc = crc32(data);
|
|
173
|
+
|
|
174
|
+
const local = new Uint8Array(30 + nameBytes.length + data.length);
|
|
175
|
+
const lv = new DataView(local.buffer);
|
|
176
|
+
lv.setUint32(0, 0x04034b50, true);
|
|
177
|
+
lv.setUint16(4, 20, true); // version needed
|
|
178
|
+
lv.setUint16(6, 0, true); // flags
|
|
179
|
+
lv.setUint16(8, 0, true); // stored
|
|
180
|
+
lv.setUint16(10, 0, true); // time
|
|
181
|
+
lv.setUint16(12, 0x21, true); // date (1996-01-01)
|
|
182
|
+
lv.setUint32(14, crc, true);
|
|
183
|
+
lv.setUint32(18, data.length, true);
|
|
184
|
+
lv.setUint32(22, data.length, true);
|
|
185
|
+
lv.setUint16(26, nameBytes.length, true);
|
|
186
|
+
lv.setUint16(28, 0, true);
|
|
187
|
+
local.set(nameBytes, 30);
|
|
188
|
+
local.set(data, 30 + nameBytes.length);
|
|
189
|
+
locals.push(local);
|
|
190
|
+
|
|
191
|
+
const central = new Uint8Array(46 + nameBytes.length);
|
|
192
|
+
const cv = new DataView(central.buffer);
|
|
193
|
+
cv.setUint32(0, 0x02014b50, true);
|
|
194
|
+
cv.setUint16(4, 20, true);
|
|
195
|
+
cv.setUint16(6, 20, true);
|
|
196
|
+
cv.setUint16(8, 0, true);
|
|
197
|
+
cv.setUint16(10, 0, true);
|
|
198
|
+
cv.setUint16(12, 0, true);
|
|
199
|
+
cv.setUint16(14, 0x21, true);
|
|
200
|
+
cv.setUint32(16, crc, true);
|
|
201
|
+
cv.setUint32(20, data.length, true);
|
|
202
|
+
cv.setUint32(24, data.length, true);
|
|
203
|
+
cv.setUint16(28, nameBytes.length, true);
|
|
204
|
+
cv.setUint32(42, offset, true);
|
|
205
|
+
central.set(nameBytes, 46);
|
|
206
|
+
centrals.push(central);
|
|
207
|
+
|
|
208
|
+
offset += local.length;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const centralSize = centrals.reduce((s, c) => s + c.length, 0);
|
|
212
|
+
const end = new Uint8Array(22);
|
|
213
|
+
const ev = new DataView(end.buffer);
|
|
214
|
+
ev.setUint32(0, 0x06054b50, true);
|
|
215
|
+
ev.setUint16(8, files.length, true);
|
|
216
|
+
ev.setUint16(10, files.length, true);
|
|
217
|
+
ev.setUint32(12, centralSize, true);
|
|
218
|
+
ev.setUint32(16, offset, true);
|
|
219
|
+
|
|
220
|
+
const total = offset + centralSize + end.length;
|
|
221
|
+
const out = new Uint8Array(total);
|
|
222
|
+
let pos = 0;
|
|
223
|
+
for (const chunk of [...locals, ...centrals, end]) {
|
|
224
|
+
out.set(chunk, pos);
|
|
225
|
+
pos += chunk.length;
|
|
226
|
+
}
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal zero-dependency YAML-subset parser.
|
|
3
|
+
*
|
|
4
|
+
* Supports exactly what the estimator input contract needs:
|
|
5
|
+
* - nested mappings by indentation
|
|
6
|
+
* - block sequences (`- item`, `- key: value` inline-start)
|
|
7
|
+
* - scalars: string, number, boolean, null
|
|
8
|
+
* - flow sequences on one line: `[a, b, c]`
|
|
9
|
+
* - quoted strings ('single' and "double")
|
|
10
|
+
* - `#` comments and blank lines
|
|
11
|
+
*
|
|
12
|
+
* Deliberately NOT supported: anchors, aliases, multi-line block scalars,
|
|
13
|
+
* flow mappings, multiple documents. Throws with a line number on anything else.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export type YamlValue = string | number | boolean | null | YamlValue[] | { [k: string]: YamlValue };
|
|
17
|
+
|
|
18
|
+
interface Line {
|
|
19
|
+
indent: number;
|
|
20
|
+
text: string;
|
|
21
|
+
no: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Parse a YAML-subset document into a plain JS value. */
|
|
25
|
+
export function parseYaml(source: string): YamlValue {
|
|
26
|
+
const lines = tokenize(source);
|
|
27
|
+
if (lines.length === 0) return {};
|
|
28
|
+
const [value] = parseBlock(lines, 0, lines[0].indent);
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Parse a JSON or YAML file body, dispatching on the file extension. */
|
|
33
|
+
export function parseDataFile(path: string, body: string): YamlValue {
|
|
34
|
+
if (/\.json$/i.test(path)) return JSON.parse(body) as YamlValue;
|
|
35
|
+
return parseYaml(body);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function tokenize(source: string): Line[] {
|
|
39
|
+
const out: Line[] = [];
|
|
40
|
+
source.split(/\r?\n/).forEach((raw, i) => {
|
|
41
|
+
if (raw.includes('\t')) throw new Error(`YAML line ${i + 1}: tabs are not allowed for indentation`);
|
|
42
|
+
const stripped = stripComment(raw);
|
|
43
|
+
if (stripped.trim() === '') return;
|
|
44
|
+
out.push({ indent: stripped.length - stripped.trimStart().length, text: stripped.trim(), no: i + 1 });
|
|
45
|
+
});
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Remove a trailing `#` comment, honouring quotes. */
|
|
50
|
+
function stripComment(raw: string): string {
|
|
51
|
+
let quote: string | null = null;
|
|
52
|
+
for (let i = 0; i < raw.length; i++) {
|
|
53
|
+
const c = raw[i];
|
|
54
|
+
if (quote) {
|
|
55
|
+
if (c === quote) quote = null;
|
|
56
|
+
} else if (c === '"' || c === "'") {
|
|
57
|
+
quote = c;
|
|
58
|
+
} else if (c === '#' && (i === 0 || /\s/.test(raw[i - 1]))) {
|
|
59
|
+
return raw.slice(0, i);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return raw;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Parse consecutive lines at `indent` starting at `i`. Returns [value, nextIndex]. */
|
|
66
|
+
function parseBlock(lines: Line[], i: number, indent: number): [YamlValue, number] {
|
|
67
|
+
if (i >= lines.length) return [null, i];
|
|
68
|
+
return lines[i].text.startsWith('- ') || lines[i].text === '-'
|
|
69
|
+
? parseSequence(lines, i, indent)
|
|
70
|
+
: parseMapping(lines, i, indent);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function parseSequence(lines: Line[], i: number, indent: number): [YamlValue[], number] {
|
|
74
|
+
const items: YamlValue[] = [];
|
|
75
|
+
while (i < lines.length && lines[i].indent === indent && (lines[i].text.startsWith('- ') || lines[i].text === '-')) {
|
|
76
|
+
const line = lines[i];
|
|
77
|
+
const rest = line.text === '-' ? '' : line.text.slice(2).trim();
|
|
78
|
+
i++;
|
|
79
|
+
if (rest === '') {
|
|
80
|
+
// Value lives on following, deeper lines.
|
|
81
|
+
if (i < lines.length && lines[i].indent > indent) {
|
|
82
|
+
const [value, next] = parseBlock(lines, i, lines[i].indent);
|
|
83
|
+
items.push(value);
|
|
84
|
+
i = next;
|
|
85
|
+
} else items.push(null);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const colon = splitKey(rest);
|
|
89
|
+
if (colon) {
|
|
90
|
+
// `- key: value` opens an inline mapping whose siblings are indented under the dash.
|
|
91
|
+
const childIndent = indent + 2;
|
|
92
|
+
const synthetic: Line[] = [{ indent: childIndent, text: rest, no: line.no }];
|
|
93
|
+
while (i < lines.length && lines[i].indent > indent) {
|
|
94
|
+
synthetic.push({ ...lines[i], indent: lines[i].indent });
|
|
95
|
+
i++;
|
|
96
|
+
}
|
|
97
|
+
const normalized = normalizeIndent(synthetic, childIndent);
|
|
98
|
+
const [value] = parseMapping(normalized, 0, normalized[0].indent);
|
|
99
|
+
items.push(value);
|
|
100
|
+
} else {
|
|
101
|
+
items.push(parseScalar(rest, line.no));
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return [items, i];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Re-base a synthetic block so the first line sits exactly at `target` indent. */
|
|
108
|
+
function normalizeIndent(lines: Line[], target: number): Line[] {
|
|
109
|
+
const base = Math.min(...lines.map((l) => l.indent));
|
|
110
|
+
const delta = target - base;
|
|
111
|
+
return lines.map((l) => ({ ...l, indent: l.indent + delta }));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function parseMapping(lines: Line[], i: number, indent: number): [Record<string, YamlValue>, number] {
|
|
115
|
+
const map: Record<string, YamlValue> = {};
|
|
116
|
+
while (i < lines.length && lines[i].indent === indent) {
|
|
117
|
+
const line = lines[i];
|
|
118
|
+
if (line.text.startsWith('- ')) break;
|
|
119
|
+
const parts = splitKey(line.text);
|
|
120
|
+
if (!parts) throw new Error(`YAML line ${line.no}: expected "key: value", got "${line.text}"`);
|
|
121
|
+
const [key, rest] = parts;
|
|
122
|
+
i++;
|
|
123
|
+
if (rest !== '') {
|
|
124
|
+
map[key] = parseScalar(rest, line.no);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (i < lines.length && lines[i].indent > indent) {
|
|
128
|
+
const [value, next] = parseBlock(lines, i, lines[i].indent);
|
|
129
|
+
map[key] = value;
|
|
130
|
+
i = next;
|
|
131
|
+
} else if (i < lines.length && lines[i].indent === indent && lines[i].text.startsWith('- ')) {
|
|
132
|
+
const [value, next] = parseSequence(lines, i, indent);
|
|
133
|
+
map[key] = value;
|
|
134
|
+
i = next;
|
|
135
|
+
} else {
|
|
136
|
+
map[key] = null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return [map, i];
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Split `key: rest` outside quotes. Returns null when the line has no top-level colon. */
|
|
143
|
+
function splitKey(text: string): [string, string] | null {
|
|
144
|
+
let quote: string | null = null;
|
|
145
|
+
for (let i = 0; i < text.length; i++) {
|
|
146
|
+
const c = text[i];
|
|
147
|
+
if (quote) {
|
|
148
|
+
if (c === quote) quote = null;
|
|
149
|
+
} else if (c === '"' || c === "'") {
|
|
150
|
+
quote = c;
|
|
151
|
+
} else if (c === ':' && (i + 1 === text.length || /\s/.test(text[i + 1]))) {
|
|
152
|
+
return [unquote(text.slice(0, i).trim()), text.slice(i + 1).trim()];
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function parseScalar(text: string, lineNo: number): YamlValue {
|
|
159
|
+
if (text.startsWith('[')) {
|
|
160
|
+
if (!text.endsWith(']')) throw new Error(`YAML line ${lineNo}: unterminated flow sequence`);
|
|
161
|
+
const inner = text.slice(1, -1).trim();
|
|
162
|
+
if (inner === '') return [];
|
|
163
|
+
return splitFlow(inner).map((part) => parseScalar(part.trim(), lineNo));
|
|
164
|
+
}
|
|
165
|
+
if (text.startsWith('{')) throw new Error(`YAML line ${lineNo}: flow mappings are not supported`);
|
|
166
|
+
if ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'"))) {
|
|
167
|
+
return unquote(text);
|
|
168
|
+
}
|
|
169
|
+
const lower = text.toLowerCase();
|
|
170
|
+
if (lower === 'true' || lower === 'yes') return true;
|
|
171
|
+
if (lower === 'false' || lower === 'no') return false;
|
|
172
|
+
if (lower === 'null' || lower === '~' || lower === '') return null;
|
|
173
|
+
if (/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(text)) return Number(text);
|
|
174
|
+
if (/^-?\d+(\.\d+)?%$/.test(text)) return Number(text.slice(0, -1)) / 100;
|
|
175
|
+
return text;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Split a flow sequence body on commas that sit outside quotes and brackets. */
|
|
179
|
+
function splitFlow(inner: string): string[] {
|
|
180
|
+
const out: string[] = [];
|
|
181
|
+
let depth = 0;
|
|
182
|
+
let quote: string | null = null;
|
|
183
|
+
let start = 0;
|
|
184
|
+
for (let i = 0; i < inner.length; i++) {
|
|
185
|
+
const c = inner[i];
|
|
186
|
+
if (quote) {
|
|
187
|
+
if (c === quote) quote = null;
|
|
188
|
+
} else if (c === '"' || c === "'") quote = c;
|
|
189
|
+
else if (c === '[') depth++;
|
|
190
|
+
else if (c === ']') depth--;
|
|
191
|
+
else if (c === ',' && depth === 0) {
|
|
192
|
+
out.push(inner.slice(start, i));
|
|
193
|
+
start = i + 1;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
out.push(inner.slice(start));
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function unquote(text: string): string {
|
|
201
|
+
if ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'"))) {
|
|
202
|
+
return text.slice(1, -1).replace(/\\n/g, '\n').replace(/\\"/g, '"');
|
|
203
|
+
}
|
|
204
|
+
return text;
|
|
205
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* cost-estimator · SERVER entry.
|
|
3
|
+
*
|
|
4
|
+
* Exposes measured delivery telemetry over REST so the client can render a cost
|
|
5
|
+
* view without re-reading the session store in the browser.
|
|
6
|
+
*
|
|
7
|
+
* Scanning ~800 sessions costs real I/O, so results are cached for `CACHE_TTL_MS`
|
|
8
|
+
* and recomputed lazily on the next request. This endpoint is read-only: it never
|
|
9
|
+
* writes to the session store.
|
|
10
|
+
*
|
|
11
|
+
* IMPORTANT: the `cost` recorded per session is a METERED API-price computation.
|
|
12
|
+
* When capacity is bought on a flat subscription that figure is theoretical, so
|
|
13
|
+
* the route returns BOTH the meter-equivalent and the actual seat cost, plus the
|
|
14
|
+
* leverage ratio between them. Never present the meter figure as cash out.
|
|
15
|
+
*/
|
|
16
|
+
import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
17
|
+
|
|
18
|
+
import { DEFAULT_SUBSCRIPTION_PLAN, SUBSCRIPTION_PLANS } from "../engine/defaults.js";
|
|
19
|
+
import { aggregateByProject, compareSubscription, measureConstants, scanSessions } from "../telemetry/sessions.js";
|
|
20
|
+
|
|
21
|
+
export interface CostEstimatorConfig {
|
|
22
|
+
gapCapMinutes: number;
|
|
23
|
+
hoursPerDay: number;
|
|
24
|
+
seatPlan: string;
|
|
25
|
+
seatMonthlyUsd: number;
|
|
26
|
+
seats: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const CACHE_TTL_MS = 60_000;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Schema defaults, applied in code.
|
|
33
|
+
*
|
|
34
|
+
* `getPluginConfig()` returns whatever is stored, and nothing is stored until the
|
|
35
|
+
* user first saves the settings form — so relying on JSON-Schema defaults to be
|
|
36
|
+
* materialized would leave a fresh install reporting the METERED basis. That is
|
|
37
|
+
* the one framing this plugin exists to prevent: the meter is a theoretical
|
|
38
|
+
* pay-as-you-go price nobody on a seat plan actually pays. Defaulting here keeps
|
|
39
|
+
* first render honest.
|
|
40
|
+
*/
|
|
41
|
+
const CONFIG_DEFAULTS: CostEstimatorConfig = {
|
|
42
|
+
gapCapMinutes: 15,
|
|
43
|
+
hoursPerDay: 8,
|
|
44
|
+
seatPlan: DEFAULT_SUBSCRIPTION_PLAN,
|
|
45
|
+
seatMonthlyUsd: 0,
|
|
46
|
+
seats: 1,
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export function resolveConfig(stored: Partial<CostEstimatorConfig> | undefined | null): CostEstimatorConfig {
|
|
50
|
+
return {
|
|
51
|
+
gapCapMinutes: stored?.gapCapMinutes ?? CONFIG_DEFAULTS.gapCapMinutes,
|
|
52
|
+
hoursPerDay: stored?.hoursPerDay ?? CONFIG_DEFAULTS.hoursPerDay,
|
|
53
|
+
seatPlan: stored?.seatPlan ?? CONFIG_DEFAULTS.seatPlan,
|
|
54
|
+
seatMonthlyUsd: stored?.seatMonthlyUsd ?? CONFIG_DEFAULTS.seatMonthlyUsd,
|
|
55
|
+
seats: stored?.seats ?? CONFIG_DEFAULTS.seats,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface CachedScan {
|
|
60
|
+
at: number;
|
|
61
|
+
key: string;
|
|
62
|
+
payload: unknown;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let cache: CachedScan | null = null;
|
|
66
|
+
|
|
67
|
+
/** Resolve the monthly seat spend from config, or null when metered. */
|
|
68
|
+
export function seatMonthly(config: CostEstimatorConfig): number | null {
|
|
69
|
+
if (config.seatPlan === "metered") return null;
|
|
70
|
+
if (config.seatPlan === "custom") return config.seatMonthlyUsd > 0 ? config.seatMonthlyUsd : null;
|
|
71
|
+
return SUBSCRIPTION_PLANS[config.seatPlan]?.monthly ?? null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export default async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
|
|
75
|
+
ctx.fastify.get("/api/cost-estimator/telemetry", async () => {
|
|
76
|
+
const config = resolveConfig(ctx.getPluginConfig<Partial<CostEstimatorConfig>>());
|
|
77
|
+
const { gapCapMinutes: gapCap, hoursPerDay, seats } = config;
|
|
78
|
+
const key = `${gapCap}:${hoursPerDay}:${config.seatPlan}:${config.seatMonthlyUsd}:${seats}`;
|
|
79
|
+
|
|
80
|
+
if (cache && cache.key === key && Date.now() - cache.at < CACHE_TTL_MS) {
|
|
81
|
+
return cache.payload;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
let records: ReturnType<typeof scanSessions>;
|
|
85
|
+
try {
|
|
86
|
+
records = scanSessions({ gapCapMinutes: gapCap });
|
|
87
|
+
} catch (error) {
|
|
88
|
+
ctx.logger.error({ err: error }, "cost-estimator: session scan failed");
|
|
89
|
+
return { ok: false, error: "session scan failed", projects: [], measured: null, subscription: null };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (records.length === 0) {
|
|
93
|
+
return { ok: true, empty: true, projects: [], measured: null, subscription: null };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const measured = measureConstants(records, hoursPerDay);
|
|
97
|
+
const projects = aggregateByProject(records, hoursPerDay);
|
|
98
|
+
const monthly = seatMonthly(config);
|
|
99
|
+
const subscription =
|
|
100
|
+
monthly != null ? compareSubscription(measured, monthly * seats) : null;
|
|
101
|
+
|
|
102
|
+
const payload = {
|
|
103
|
+
ok: true,
|
|
104
|
+
empty: false,
|
|
105
|
+
generatedAt: Date.now(),
|
|
106
|
+
measured,
|
|
107
|
+
projects,
|
|
108
|
+
subscription,
|
|
109
|
+
seatPlan: config.seatPlan,
|
|
110
|
+
seats,
|
|
111
|
+
// Stated explicitly so no consumer mistakes the meter for cash.
|
|
112
|
+
costBasisNote:
|
|
113
|
+
subscription != null
|
|
114
|
+
? "measured.totalCost is a METER-EQUIVALENT. subscription.subscriptionCost is the cash figure."
|
|
115
|
+
: "Metered basis: measured.totalCost is the billed figure.",
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
cache = { at: Date.now(), key, payload };
|
|
119
|
+
return payload;
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
ctx.logger.info("cost-estimator: telemetry route registered");
|
|
123
|
+
}
|