@rangefoundry/importers 0.0.0 → 0.1.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/LICENSE +661 -0
- package/README.md +20 -1
- package/dist/cells.d.ts +31 -0
- package/dist/cells.js +22 -0
- package/dist/cfb.d.ts +2 -0
- package/dist/cfb.js +196 -0
- package/dist/csrload.d.ts +12 -0
- package/dist/csrload.js +153 -0
- package/dist/diagnostics.d.ts +42 -0
- package/dist/diagnostics.js +29 -0
- package/dist/generic.d.ts +44 -0
- package/dist/generic.js +272 -0
- package/dist/grtload.d.ts +32 -0
- package/dist/grtload.js +264 -0
- package/dist/index.d.ts +85 -0
- package/dist/index.js +126 -0
- package/dist/limits.d.ts +7 -0
- package/dist/limits.js +12 -0
- package/dist/pressure-history.d.ts +61 -0
- package/dist/pressure-history.js +158 -0
- package/dist/rangefoundry-json.d.ts +17 -0
- package/dist/rangefoundry-json.js +176 -0
- package/dist/record-fields.d.ts +35 -0
- package/dist/record-fields.js +190 -0
- package/dist/record-ids.d.ts +2 -0
- package/dist/record-ids.js +28 -0
- package/dist/records.d.ts +91 -0
- package/dist/records.js +433 -0
- package/dist/result.d.ts +65 -0
- package/dist/result.js +90 -0
- package/dist/shot-rows.d.ts +11 -0
- package/dist/shot-rows.js +39 -0
- package/dist/shotview.d.ts +16 -0
- package/dist/shotview.js +131 -0
- package/dist/statistics.d.ts +12 -0
- package/dist/statistics.js +48 -0
- package/dist/tables.d.ts +41 -0
- package/dist/tables.js +277 -0
- package/dist/template.d.ts +13 -0
- package/dist/template.js +37 -0
- package/dist/text.d.ts +28 -0
- package/dist/text.js +150 -0
- package/dist/units.d.ts +12 -0
- package/dist/units.js +62 -0
- package/dist/workbook.d.ts +12 -0
- package/dist/workbook.js +264 -0
- package/dist/worksheet-strings.d.ts +36 -0
- package/dist/worksheet-strings.js +50 -0
- package/dist/xls.d.ts +3 -0
- package/dist/xls.js +486 -0
- package/dist/xml.d.ts +26 -0
- package/dist/xml.js +261 -0
- package/dist/zip.d.ts +27 -0
- package/dist/zip.js +183 -0
- package/package.json +58 -4
package/dist/generic.js
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { ReaderError, refuse } from './diagnostics.js';
|
|
2
|
+
import { buildChronoImport, } from './result.js';
|
|
3
|
+
import { bracketed, joinQuotedLines, splitDelimited, splitLines } from './text.js';
|
|
4
|
+
import { parseVelocity, parseVelocityUnit, resolveUnit } from './units.js';
|
|
5
|
+
const falsy = ['', '0', 'no', 'false'];
|
|
6
|
+
const truthy = ['1', 'x', 'yes', 'true'];
|
|
7
|
+
const candidates = ['\t', ';', ','];
|
|
8
|
+
/** The cells of a line split at `d`; `none` keeps the trimmed line as one cell. */
|
|
9
|
+
export const splitCells = (line, d) => d === 'none' ? [line.trim()] : splitDelimited(line, d);
|
|
10
|
+
/** True when `d` separates cells of the line outside quoted cells. */
|
|
11
|
+
const splits = (line, d) => splitCells(line, d).length > 1;
|
|
12
|
+
/** The first that separates cells in every non-empty line (outside quotes), else the first that does in any line, else one column. */
|
|
13
|
+
export function detectDelimiter(lines) {
|
|
14
|
+
const filled = lines.filter((l) => l.trim());
|
|
15
|
+
return (candidates.find((d) => filled.length > 0 && filled.every((l) => splits(l, d))) ??
|
|
16
|
+
candidates.find((d) => filled.some((l) => splits(l, d))) ??
|
|
17
|
+
'none');
|
|
18
|
+
}
|
|
19
|
+
/** Index of the first row whose cells hold every name (trimmed, case-insensitive), or -1. */
|
|
20
|
+
const headerIndex = (rows, names) => rows.findIndex((cells) => {
|
|
21
|
+
const lower = cells.map((c) => c.toLowerCase());
|
|
22
|
+
return names.every((name) => lower.includes(name));
|
|
23
|
+
});
|
|
24
|
+
/** The unit token of a header cell: its recognized bracketed text (`SPEED (FPS)`), else a recognized last word (`v fps`). */
|
|
25
|
+
function unitToken(cell) {
|
|
26
|
+
const inside = bracketed(cell);
|
|
27
|
+
if (parseVelocityUnit(inside))
|
|
28
|
+
return inside;
|
|
29
|
+
const last = cell.split(' ').at(-1);
|
|
30
|
+
return parseVelocityUnit(last) ? last : undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Delimited text with a user column mapping: one row per shot in firing order. Never detected.
|
|
34
|
+
*/
|
|
35
|
+
export function parseDelimited(text, options) {
|
|
36
|
+
return parseDelimitedRows('delimited', text, options);
|
|
37
|
+
}
|
|
38
|
+
/** Throws on a column number below 1, empty header text, or a `skipRows` that is not a whole number or comes with a header-text column. */
|
|
39
|
+
function validateColumns(options) {
|
|
40
|
+
const columns = Object.entries(options.columns).filter((column) => column[1] !== undefined);
|
|
41
|
+
for (const column of columns)
|
|
42
|
+
checkColumn(column);
|
|
43
|
+
const { skipRows } = options;
|
|
44
|
+
if (skipRows !== undefined && !(Number.isInteger(skipRows) && skipRows >= 0))
|
|
45
|
+
refuse('skipRowsNotWhole');
|
|
46
|
+
if (skipRows !== undefined && columns.some(([, c]) => typeof c === 'string'))
|
|
47
|
+
refuse('skipRowsWithHeaderText');
|
|
48
|
+
return columns;
|
|
49
|
+
}
|
|
50
|
+
/** Throws on a column number below 1 or empty header text. */
|
|
51
|
+
function checkColumn([key, c]) {
|
|
52
|
+
if (typeof c === 'number' && !(Number.isInteger(c) && c >= 1))
|
|
53
|
+
refuse('columnBelowOne', { column: key, number: c });
|
|
54
|
+
if (typeof c === 'string' && !c.trim())
|
|
55
|
+
refuse('emptyHeaderText', { column: key });
|
|
56
|
+
}
|
|
57
|
+
/** The cell index of each mapped column: its number, or the place of its header text. */
|
|
58
|
+
function columnIndex(columns, header) {
|
|
59
|
+
const index = {};
|
|
60
|
+
for (const [key, c] of columns) {
|
|
61
|
+
index[key] = typeof c === 'number' ? c - 1 : (header ?? []).indexOf(c.trim().toLowerCase());
|
|
62
|
+
}
|
|
63
|
+
return index;
|
|
64
|
+
}
|
|
65
|
+
/** The user's, else with header-text columns the first under which the header row is found and splits into cells, else one detected from the lines after the header row or the skipped rows. */
|
|
66
|
+
function chooseDelimiter(lines, named, names, skip) {
|
|
67
|
+
let delimiter = named;
|
|
68
|
+
if (delimiter === undefined && names.length > 0) {
|
|
69
|
+
delimiter = candidates.find((d) => {
|
|
70
|
+
const cells = lines.map((l) => splitCells(l, d));
|
|
71
|
+
const row = cells[headerIndex(cells, names)];
|
|
72
|
+
return row !== undefined && row.length > 1;
|
|
73
|
+
});
|
|
74
|
+
if (delimiter === undefined) {
|
|
75
|
+
const h = headerIndex(lines.map((l) => splitCells(l, 'none')), names);
|
|
76
|
+
delimiter = detectDelimiter(h < 0 ? lines : lines.slice(h + 1));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return delimiter ?? detectDelimiter(lines.slice(skip));
|
|
80
|
+
}
|
|
81
|
+
/** Holding every name (lower case), with the text of a header-text velocity column and the rows after it; all rows are data without names. */
|
|
82
|
+
function findHeader(rows, names, velocity) {
|
|
83
|
+
if (names.length === 0)
|
|
84
|
+
return { data: rows };
|
|
85
|
+
const h = headerIndex(rows.map((r) => r.cells), names);
|
|
86
|
+
const row = rows[h];
|
|
87
|
+
if (row === undefined)
|
|
88
|
+
refuse('noHeaderRow', { names });
|
|
89
|
+
const header = row.cells.map((c) => c.toLowerCase());
|
|
90
|
+
const headerText = typeof velocity === 'string'
|
|
91
|
+
? row.cells[header.indexOf(velocity.trim().toLowerCase())]
|
|
92
|
+
: undefined;
|
|
93
|
+
return { header, headerText, data: rows.slice(h + 1) };
|
|
94
|
+
}
|
|
95
|
+
/** A detected comma would cut `2,800`, `2,800.0` or `812,5` silently: without a header such a row throws; after a header only an integer velocity followed by 1 to 3 digits in an unmapped column adds one warning naming the rows, as mapped columns and the cell before the velocity (often a shot number) are read as they are. */
|
|
96
|
+
function checkRows(data, header, { index, warnings }, comma) {
|
|
97
|
+
const vi = index.velocity ?? 0;
|
|
98
|
+
const nextMapped = header !== undefined && Object.values(index).includes(vi + 1);
|
|
99
|
+
const suspect = [];
|
|
100
|
+
let first;
|
|
101
|
+
const [firstRow] = data;
|
|
102
|
+
for (const r of data) {
|
|
103
|
+
const pair = comma.mayCut ? commaPair(r, vi, header, nextMapped) : undefined;
|
|
104
|
+
checkRow(r, header, firstRow, { ...comma, pair });
|
|
105
|
+
if (pair) {
|
|
106
|
+
suspect.push(r.lineNumber);
|
|
107
|
+
first ??= pair;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (first) {
|
|
111
|
+
warnings.push({
|
|
112
|
+
code: 'commaMaySplit',
|
|
113
|
+
params: { rows: suspect.map(String), cells: first.join(','), remedy: comma.remedy },
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** Throws for a row with more cells than the header, for a velocity a comma may have cut in a file without a header (`pair`), and for a row whose cell count differs from the first row's there. */
|
|
118
|
+
function checkRow(r, header, firstRow, { mayCut, remedy, pair }) {
|
|
119
|
+
checkOverflow(r, header, mayCut, remedy);
|
|
120
|
+
if (pair && !header)
|
|
121
|
+
refuse('commaMayCutVelocity', { row: r.lineNumber, cells: pair.join(','), remedy });
|
|
122
|
+
if (!header && firstRow && r.cells.length !== firstRow.cells.length) {
|
|
123
|
+
refuse('cellCountDiffers', {
|
|
124
|
+
row: r.lineNumber,
|
|
125
|
+
cells: r.cells.length,
|
|
126
|
+
firstRow: firstRow.lineNumber,
|
|
127
|
+
firstCells: firstRow.cells.length,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** Throws when a row has more cells than the header. */
|
|
132
|
+
function checkOverflow(r, header, commaMayCut, remedy) {
|
|
133
|
+
if (!header || r.cells.length <= header.length)
|
|
134
|
+
return;
|
|
135
|
+
const params = { row: r.lineNumber, cells: r.cells.length, header: header.length };
|
|
136
|
+
if (commaMayCut)
|
|
137
|
+
refuse('moreCellsThanHeaderComma', { ...params, remedy });
|
|
138
|
+
refuse('moreCellsThanHeader', params);
|
|
139
|
+
}
|
|
140
|
+
/** The two cells of a row that may be one velocity split at a comma, when there are such. */
|
|
141
|
+
function commaPair(r, vi, header, nextMapped) {
|
|
142
|
+
const at = (k) => r.cells[k] ?? '';
|
|
143
|
+
const [before, v, after] = [at(vi - 1), at(vi), at(vi + 1)];
|
|
144
|
+
if (header)
|
|
145
|
+
return !nextMapped && /^\d+$/.test(v) && /^\d{1,3}$/.test(after) ? [v, after] : undefined;
|
|
146
|
+
if (/^\d+$/.test(v) && /^\d+(\.\d+)?$/.test(after))
|
|
147
|
+
return [v, after];
|
|
148
|
+
if (/^\d{1,3}$/.test(before) && /^\d{3}(\.\d+)?$/.test(v))
|
|
149
|
+
return [before, v];
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
/** A non-empty unit cell wins over the header `token`; refused when both name different units. */
|
|
153
|
+
function velocityUnitText(unitCell, token, headerText) {
|
|
154
|
+
const [fromCell, fromHeader] = [parseVelocityUnit(unitCell), parseVelocityUnit(token)];
|
|
155
|
+
if (fromCell && fromHeader && fromCell !== fromHeader) {
|
|
156
|
+
refuse('unitCellDiffersFromHeader', {
|
|
157
|
+
cell: unitCell ?? '',
|
|
158
|
+
token: token ?? '',
|
|
159
|
+
header: headerText ?? '',
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
// an unknown unit cell does not hide a recognized header token
|
|
163
|
+
return fromCell || !fromHeader ? unitCell || token : token;
|
|
164
|
+
}
|
|
165
|
+
/** True for a cold bore flag, false for none; refused for any other text. */
|
|
166
|
+
function isColdBore(text) {
|
|
167
|
+
if (text === undefined)
|
|
168
|
+
return false;
|
|
169
|
+
const lower = text.toLowerCase();
|
|
170
|
+
if (truthy.includes(lower))
|
|
171
|
+
return true;
|
|
172
|
+
if (falsy.includes(lower))
|
|
173
|
+
return false;
|
|
174
|
+
return refuse('coldBoreUnknown', { text, choices: [...truthy, ...falsy.slice(1)] });
|
|
175
|
+
}
|
|
176
|
+
/** `cell` returns undefined for an unmapped column; a non-empty unit cell wins over the header token, the token over the caller's unit. */
|
|
177
|
+
function readRowShot(cell, { token, headerText, options, warnings }) {
|
|
178
|
+
const unitText = velocityUnitText(cell('velocityUnit'), token, headerText);
|
|
179
|
+
const shot = {
|
|
180
|
+
velocity: parseVelocity(cell('velocity') ?? '', unitText, resolveUnit(unitText, options, warnings)),
|
|
181
|
+
};
|
|
182
|
+
if (isColdBore(cell('coldBore')))
|
|
183
|
+
shot.coldBore = true;
|
|
184
|
+
const excluded = cell('excluded');
|
|
185
|
+
if (excluded !== undefined && !falsy.includes(excluded.toLowerCase()))
|
|
186
|
+
shot.excluded = excluded;
|
|
187
|
+
return shot;
|
|
188
|
+
}
|
|
189
|
+
/** `readRowShot` with the row's line number in the diagnostic of a refusal. */
|
|
190
|
+
function readRowShotAt(lineNumber, cell, context) {
|
|
191
|
+
try {
|
|
192
|
+
return readRowShot(cell, context);
|
|
193
|
+
}
|
|
194
|
+
catch (e) {
|
|
195
|
+
if (!(e instanceof ReaderError))
|
|
196
|
+
throw e;
|
|
197
|
+
const d = e.diagnostic;
|
|
198
|
+
throw new ReaderError({ ...d, params: { ...d.params, row: lineNumber } }, { cause: e });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/** The rows from line `skip` on that hold a cell, a quoted line break kept inside its row. */
|
|
202
|
+
function filledRows(lines, delimiter, skip) {
|
|
203
|
+
// joined from `skip` on, so a quote in a skipped line cannot swallow data rows
|
|
204
|
+
const kept = lines.slice(skip);
|
|
205
|
+
const joined = delimiter === 'none'
|
|
206
|
+
? kept.map((line, index) => ({ text: line, index }))
|
|
207
|
+
: joinQuotedLines(kept, delimiter);
|
|
208
|
+
return joined
|
|
209
|
+
.map(({ text, index }) => ({
|
|
210
|
+
lineNumber: skip + index + 1,
|
|
211
|
+
cells: splitCells(text, delimiter),
|
|
212
|
+
}))
|
|
213
|
+
.filter((r) => r.cells.some((c) => c !== ''));
|
|
214
|
+
}
|
|
215
|
+
/** With `options.columns` as `format`; `detected`: the delimiter in `options` was detected, not named by the user. */
|
|
216
|
+
export function parseDelimitedRows(format, text, options, detected = false) {
|
|
217
|
+
const columns = validateColumns(options);
|
|
218
|
+
const lines = splitLines(text);
|
|
219
|
+
const names = columns.flatMap(([, c]) => (typeof c === 'string' ? [c.trim().toLowerCase()] : []));
|
|
220
|
+
const skip = options.skipRows ?? 0;
|
|
221
|
+
const delimiter = chooseDelimiter(lines, options.delimiter, names, skip);
|
|
222
|
+
const rows = filledRows(lines, delimiter, skip);
|
|
223
|
+
const { header, headerText, data } = findHeader(rows, names, options.columns.velocity);
|
|
224
|
+
const context = {
|
|
225
|
+
index: columnIndex(columns, header),
|
|
226
|
+
token: headerText === undefined ? undefined : unitToken(headerText),
|
|
227
|
+
headerText,
|
|
228
|
+
options,
|
|
229
|
+
warnings: [],
|
|
230
|
+
};
|
|
231
|
+
checkRows(data, header, context, {
|
|
232
|
+
mayCut: (options.delimiter === undefined || detected) && delimiter === ',',
|
|
233
|
+
// a template takes its delimiter from the header line, so the user cannot name another one
|
|
234
|
+
remedy: detected ? 'quoteOrSemicolon' : 'nameDelimiter',
|
|
235
|
+
});
|
|
236
|
+
const { strings, labels } = readStrings(data, context);
|
|
237
|
+
return buildChronoImport(format, { device: options.device ?? { kind: 'other' }, strings }, { labels, warnings: context.warnings }, options);
|
|
238
|
+
}
|
|
239
|
+
/** The strings of the data rows: consecutive rows with an equal `string` cell form one string. */
|
|
240
|
+
function readStrings(data, context) {
|
|
241
|
+
const { index, warnings } = context;
|
|
242
|
+
const strings = [];
|
|
243
|
+
const labels = [];
|
|
244
|
+
const seen = new Set();
|
|
245
|
+
let current;
|
|
246
|
+
let open;
|
|
247
|
+
for (const r of data) {
|
|
248
|
+
const cell = (key) => {
|
|
249
|
+
const i = index[key];
|
|
250
|
+
return i === undefined ? undefined : (r.cells[i] ?? '');
|
|
251
|
+
};
|
|
252
|
+
if (!cell('velocity')) {
|
|
253
|
+
warnings.push({ code: 'noVelocity', params: { row: r.lineNumber } });
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
const shot = readRowShotAt(r.lineNumber, cell, context);
|
|
257
|
+
const label = cell('string');
|
|
258
|
+
if (open === undefined || label !== current) {
|
|
259
|
+
if (label !== undefined && seen.has(label))
|
|
260
|
+
warnings.push({ code: 'stringReturns', params: { row: r.lineNumber, label } });
|
|
261
|
+
if (label !== undefined)
|
|
262
|
+
seen.add(label);
|
|
263
|
+
open = { shots: [] };
|
|
264
|
+
strings.push(open);
|
|
265
|
+
labels.push(label || undefined);
|
|
266
|
+
current = label;
|
|
267
|
+
}
|
|
268
|
+
open.shots.push(shot);
|
|
269
|
+
}
|
|
270
|
+
return { strings, labels };
|
|
271
|
+
}
|
|
272
|
+
//# sourceMappingURL=generic.js.map
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Candidate, type ReaderDiagnostic } from './diagnostics.ts';
|
|
2
|
+
import { type XmlElement } from './xml.ts';
|
|
3
|
+
/** A warning of a load file read, as a code and the values its message names; `at` is the field path. */
|
|
4
|
+
export type LoadDiagnostic = ReaderDiagnostic<'notPercentEncoded' | 'notConverted' | 'shotshell' | 'shotWithoutVelocity' | 'chargeWithoutShots' | 'shotsBeyondLimit' | 'chargeWithoutMass' | 'chargesBeyondLimit' | 'otherFormat' | 'unknownFormat'>;
|
|
5
|
+
/** The record candidates of one load file, the fields it did not read and its warnings. */
|
|
6
|
+
export interface GrtLoadRead {
|
|
7
|
+
candidates: Candidate[];
|
|
8
|
+
/** Fields with a value that no record field takes, as `section.name`. */
|
|
9
|
+
unmapped: string[];
|
|
10
|
+
warnings: LoadDiagnostic[];
|
|
11
|
+
}
|
|
12
|
+
export declare const elements: (e: XmlElement) => XmlElement[];
|
|
13
|
+
export declare const clip: (s: string | undefined, max?: number) => string | undefined;
|
|
14
|
+
/** Key, name and data of a candidate of `kind`, the key from its content: the same content gives the same id in every file. */
|
|
15
|
+
export declare const named: <D>(kind: string, name: string, data: D) => {
|
|
16
|
+
key: string;
|
|
17
|
+
name: string;
|
|
18
|
+
data: D;
|
|
19
|
+
};
|
|
20
|
+
/** Text with its percent escapes resolved; the text as written, with a warning, when they are not valid. */
|
|
21
|
+
export declare function unescaped(s: string, at: string, warnings: LoadDiagnostic[]): string;
|
|
22
|
+
/** Of the load input element of this layout (GRT's, also written by other programs): the cartridge, the bullet after its maker, the powder, then the load last. */
|
|
23
|
+
export declare function readLoadInput(input: XmlElement): GrtLoadRead;
|
|
24
|
+
/**
|
|
25
|
+
* The record candidates of a load file: the cartridge, the bullet (after its maker) and the powder
|
|
26
|
+
* it names, then the load. Percent escapes in text values are resolved, numbers converted from the
|
|
27
|
+
* unit each field declares to the stored unit; a field with an empty value holds nothing to read.
|
|
28
|
+
* Keys come from the content, so a file read again gives the same ids and files that share a
|
|
29
|
+
* component give it one id. Throws with the reason on a file that is no load file of this format.
|
|
30
|
+
* The caller makes each candidate a record and checks it with the user record schema.
|
|
31
|
+
*/
|
|
32
|
+
export declare function readGrtLoad(xml: string): GrtLoadRead;
|
package/dist/grtload.js
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// The load files of Gordon's Reloading Tool (`.grtload`, XML) as record candidates; mapping and reasons in `apps/docs/docs/data/grt-load-files.md`, written from saved files
|
|
2
|
+
import { refuseFile } from './diagnostics.js';
|
|
3
|
+
import { idOfKey } from './record-ids.js';
|
|
4
|
+
import { keyText } from './records.js';
|
|
5
|
+
import { readDecimal } from './text.js';
|
|
6
|
+
import { parseXml } from './xml.js';
|
|
7
|
+
/** The root element of the file, which tells it apart from other XML. */
|
|
8
|
+
const grtLoadRoot = 'GordonsReloadingTool';
|
|
9
|
+
/** The factor from each unit a file may declare to the stored unit of the quantity. */
|
|
10
|
+
const factors = {
|
|
11
|
+
length: { mm: 1, cm: 10, m: 1000 },
|
|
12
|
+
area: { mm2: 1, cm2: 100 },
|
|
13
|
+
mass: { g: 1, kg: 1000, mg: 0.001 },
|
|
14
|
+
pressure: { bar: 1, Pa: 1e-5, kPa: 0.01, MPa: 10 },
|
|
15
|
+
density: { 'kg/m3': 0.001, 'g/cm3': 1 },
|
|
16
|
+
temperature: { Cel: 1 },
|
|
17
|
+
one: { '': 1 },
|
|
18
|
+
};
|
|
19
|
+
/** The fields read, by section and name: text, or a number of a kind. Every other field is listed as not read. */
|
|
20
|
+
const fields = {
|
|
21
|
+
'caliber.CaliberName': 'text',
|
|
22
|
+
'caliber.oal': 'length',
|
|
23
|
+
'caliber.caselen': 'length',
|
|
24
|
+
'caliber.Dz': 'length',
|
|
25
|
+
'caliber.Aeff': 'area',
|
|
26
|
+
'caliber.pMaxZul': 'pressure',
|
|
27
|
+
'caliber.ps': 'pressure',
|
|
28
|
+
'caliber.sebert': 'one',
|
|
29
|
+
'gun.twistlen': 'length',
|
|
30
|
+
'gun.mgun': 'mass',
|
|
31
|
+
'projectile.ProjectileName': 'text',
|
|
32
|
+
'projectile.mname': 'text',
|
|
33
|
+
'projectile.pname': 'text',
|
|
34
|
+
'projectile.Dbul': 'length',
|
|
35
|
+
'projectile.mp': 'mass',
|
|
36
|
+
'projectile.glen': 'length',
|
|
37
|
+
'projectile.g1bc': 'one',
|
|
38
|
+
'projectile.g7bc': 'one',
|
|
39
|
+
'propellant.mname': 'text',
|
|
40
|
+
'propellant.pname': 'text',
|
|
41
|
+
'propellant.lotid': 'text',
|
|
42
|
+
'propellant.k': 'one',
|
|
43
|
+
'propellant.pc': 'density',
|
|
44
|
+
'propellant.pcd': 'density',
|
|
45
|
+
'propellant.pt': 'temperature',
|
|
46
|
+
'propellant.mc': 'mass',
|
|
47
|
+
};
|
|
48
|
+
/** The solver values of the load that no component record holds, and the field each is read from. */
|
|
49
|
+
const overrideFields = [
|
|
50
|
+
['startPressure', 'caliber.ps'],
|
|
51
|
+
['sebert', 'caliber.sebert'],
|
|
52
|
+
['twist', 'gun.twistlen'],
|
|
53
|
+
['firearmMass', 'gun.mgun'],
|
|
54
|
+
['gamma', 'propellant.k'],
|
|
55
|
+
['density', 'propellant.pc'],
|
|
56
|
+
['propellantTemperature', 'propellant.pt'],
|
|
57
|
+
];
|
|
58
|
+
export const elements = (e) => e.children.filter((c) => typeof c !== 'string');
|
|
59
|
+
const textOf = (e) => e.children.filter((c) => typeof c === 'string').join('');
|
|
60
|
+
export const clip = (s, max = 200) => s ? s.slice(0, max) : undefined;
|
|
61
|
+
/** Key, name and data of a candidate of `kind`, the key from its content: the same content gives the same id in every file. */
|
|
62
|
+
export const named = (kind, name, data) => ({
|
|
63
|
+
key: `${kind}|${JSON.stringify([name, data])}`,
|
|
64
|
+
name,
|
|
65
|
+
data,
|
|
66
|
+
});
|
|
67
|
+
/** Text with its percent escapes resolved; the text as written, with a warning, when they are not valid. */
|
|
68
|
+
export function unescaped(s, at, warnings) {
|
|
69
|
+
try {
|
|
70
|
+
return decodeURIComponent(s).trim();
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
warnings.push({ code: 'notPercentEncoded', params: { at } });
|
|
74
|
+
return s.trim();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** The number of field `at` in the stored unit of `kind`; undefined, with a warning, when the unit or number is not read. */
|
|
78
|
+
function numberValue(at, kind, { unit, value }, warnings) {
|
|
79
|
+
const factor = Object.hasOwn(factors[kind], unit) ? factors[kind][unit] : undefined;
|
|
80
|
+
// a finite number can still overflow in the stored unit
|
|
81
|
+
const stored = factor === undefined ? Number.NaN : readDecimal(value) * factor;
|
|
82
|
+
if (Number.isFinite(stored))
|
|
83
|
+
return Number(stored.toPrecision(12));
|
|
84
|
+
warnings.push({
|
|
85
|
+
code: 'notConverted',
|
|
86
|
+
params: { at, value: value.slice(0, 40), unit: unit.slice(0, 20) },
|
|
87
|
+
});
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
const isField = (at) => Object.hasOwn(fields, at);
|
|
91
|
+
/** One `input` field of a section into `read`. */
|
|
92
|
+
function readField(at, f, read) {
|
|
93
|
+
const value = (f.attributes['value'] ?? '').trim();
|
|
94
|
+
if (value === '')
|
|
95
|
+
return;
|
|
96
|
+
if (at === 'caliber.shotshell') {
|
|
97
|
+
if (value === 'true')
|
|
98
|
+
read.warnings.push({ code: 'shotshell', params: {} });
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (!isField(at)) {
|
|
102
|
+
read.unmapped.add(at);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const kind = fields[at];
|
|
106
|
+
if (kind === 'text')
|
|
107
|
+
read.texts[at] = unescaped(value, at, read.warnings);
|
|
108
|
+
else {
|
|
109
|
+
const x = numberValue(at, kind, { unit: f.attributes['unit'] ?? '', value }, read.warnings);
|
|
110
|
+
if (x !== undefined)
|
|
111
|
+
read.nums[at] = x;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** The notes of the appendix into `read`; its measurements, pictures and other parts are not read. */
|
|
115
|
+
function readAppendix(appendix, read) {
|
|
116
|
+
for (const a of elements(appendix)) {
|
|
117
|
+
if (a.name === 'note' && a.attributes['text'])
|
|
118
|
+
read.notes.push(unescaped(a.attributes['text'], 'note', read.warnings));
|
|
119
|
+
else
|
|
120
|
+
read.unmapped.add(`appendix.${a.name}`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/** The fields of the file's load input, every section and field it does not read listed. */
|
|
124
|
+
function readInput(input) {
|
|
125
|
+
const read = { texts: {}, nums: {}, notes: [], unmapped: new Set(), warnings: [] };
|
|
126
|
+
for (const section of elements(input)) {
|
|
127
|
+
const s = section.name;
|
|
128
|
+
if (s === 'title')
|
|
129
|
+
read.title = unescaped(textOf(section), s, read.warnings);
|
|
130
|
+
else if (s === 'appendix')
|
|
131
|
+
readAppendix(section, read);
|
|
132
|
+
else if (['caliber', 'gun', 'projectile', 'propellant'].includes(s))
|
|
133
|
+
for (const f of elements(section))
|
|
134
|
+
readField(`${s}.${f.attributes['name'] ?? f.name}`, f, read);
|
|
135
|
+
else
|
|
136
|
+
read.unmapped.add(section.attributes['name'] ? `${s}.${section.attributes['name']}` : s);
|
|
137
|
+
}
|
|
138
|
+
return read;
|
|
139
|
+
}
|
|
140
|
+
const quantity = (v) => (v === undefined ? undefined : { value: v });
|
|
141
|
+
function cartridgeOf(r, name) {
|
|
142
|
+
const spec = (symbol, kind, f, side) => {
|
|
143
|
+
const value = r.nums[f];
|
|
144
|
+
return value === undefined ? [] : [{ ...(side && { side }), symbol, quantity: kind, value }];
|
|
145
|
+
};
|
|
146
|
+
const values = [
|
|
147
|
+
...spec('L3', 'length', 'caliber.caselen', 'cartridge'),
|
|
148
|
+
...spec('Z', 'length', 'caliber.Dz', 'chamber'),
|
|
149
|
+
...spec('Q', 'area', 'caliber.Aeff', 'chamber'),
|
|
150
|
+
...spec('Pmax', 'pressure', 'caliber.pMaxZul'),
|
|
151
|
+
];
|
|
152
|
+
const data = {
|
|
153
|
+
origin: 'user',
|
|
154
|
+
overrides: { name, ...(values.length > 0 && { values }) },
|
|
155
|
+
};
|
|
156
|
+
return { kind: 'cartridge', ...named('cartridge', name, data) };
|
|
157
|
+
}
|
|
158
|
+
/** The candidate of a bullet's maker named `name` and the reference to it. */
|
|
159
|
+
function makerOf(name) {
|
|
160
|
+
const key = `manufacturer|${keyText(name)}`;
|
|
161
|
+
const candidate = { kind: 'manufacturer', key, name, data: { origin: 'user' } };
|
|
162
|
+
return { candidate, ref: `user:${idOfKey(key)}` };
|
|
163
|
+
}
|
|
164
|
+
/** The bullet, and its maker's candidate first when the file names one. */
|
|
165
|
+
function bulletOf(r, name) {
|
|
166
|
+
const makerName = clip(r.texts['projectile.mname']);
|
|
167
|
+
const maker = makerName ? makerOf(makerName) : undefined;
|
|
168
|
+
const coefficients = ['G1', 'G7'].flatMap((m) => {
|
|
169
|
+
const value = r.nums[m === 'G1' ? 'projectile.g1bc' : 'projectile.g7bc'];
|
|
170
|
+
return value !== undefined && value > 0 ? [{ dragModel: m, value }] : [];
|
|
171
|
+
});
|
|
172
|
+
const diameter = quantity(r.nums['projectile.Dbul']);
|
|
173
|
+
const mass = quantity(r.nums['projectile.mp']);
|
|
174
|
+
const length = quantity(r.nums['projectile.glen']);
|
|
175
|
+
const data = {
|
|
176
|
+
origin: 'user',
|
|
177
|
+
...(maker && { manufacturer: maker.ref }),
|
|
178
|
+
overrides: {
|
|
179
|
+
name: clip(r.texts['projectile.pname']) ?? name,
|
|
180
|
+
...(diameter && { diameter }),
|
|
181
|
+
...(mass && { mass }),
|
|
182
|
+
...(length && { length }),
|
|
183
|
+
...(coefficients.length > 0 && { ballisticCoefficients: coefficients }),
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
const bullet = { kind: 'bullet', ...named('bullet', name, data) };
|
|
187
|
+
return maker ? [maker.candidate, bullet] : [bullet];
|
|
188
|
+
}
|
|
189
|
+
function powderOf(r, name) {
|
|
190
|
+
const bulk = quantity(r.nums['propellant.pcd']);
|
|
191
|
+
const data = { origin: 'user', draft: { ...(bulk && { bulkDensity: bulk }) } };
|
|
192
|
+
return { kind: 'powder', ...named('powder', name, data) };
|
|
193
|
+
}
|
|
194
|
+
const userRef = (id) => (id ? `user:${id}` : undefined);
|
|
195
|
+
/** The `user:<id>` references of the load's components that have a record. */
|
|
196
|
+
function componentRefs(refs) {
|
|
197
|
+
const [cartridge, bullet, powder] = [
|
|
198
|
+
userRef(refs.cartridge),
|
|
199
|
+
userRef(refs.bullet),
|
|
200
|
+
userRef(refs.powder),
|
|
201
|
+
];
|
|
202
|
+
return { ...(cartridge && { cartridge }), ...(bullet && { bullet }), ...(powder && { powder }) };
|
|
203
|
+
}
|
|
204
|
+
/** The load, naming the component records by `user:<id>`. */
|
|
205
|
+
function loadOf(r, name, refs) {
|
|
206
|
+
const overrides = Object.fromEntries(overrideFields.flatMap(([key, f]) => {
|
|
207
|
+
const value = r.nums[f];
|
|
208
|
+
return value === undefined ? [] : [[key, value]];
|
|
209
|
+
}));
|
|
210
|
+
const charge = r.nums['propellant.mc'] ?? 0;
|
|
211
|
+
const oal = r.nums['caliber.oal'] ?? 0;
|
|
212
|
+
const lot = clip(r.texts['propellant.lotid']);
|
|
213
|
+
const note = clip(r.notes.filter(Boolean).join('\n\n'), 10000);
|
|
214
|
+
const data = {
|
|
215
|
+
origin: 'user',
|
|
216
|
+
...componentRefs(refs),
|
|
217
|
+
...(lot && { powderLot: lot }),
|
|
218
|
+
...(charge > 0 && { charge: { value: charge } }),
|
|
219
|
+
...(oal > 0 && { seating: { by: 'overallLength', value: { value: oal } } }),
|
|
220
|
+
...(note && { note }),
|
|
221
|
+
...(Object.keys(overrides).length > 0 && { analysis: { overrides } }),
|
|
222
|
+
};
|
|
223
|
+
return { kind: 'load', ...named('load', name, data) };
|
|
224
|
+
}
|
|
225
|
+
/** The id the app gives a candidate, which the other candidates of its read refer to. */
|
|
226
|
+
const idOf = (c) => c && idOfKey(c.key);
|
|
227
|
+
/** Of the load input element of this layout (GRT's, also written by other programs): the cartridge, the bullet after its maker, the powder, then the load last. */
|
|
228
|
+
export function readLoadInput(input) {
|
|
229
|
+
const r = readInput(input);
|
|
230
|
+
const cartridgeName = clip(r.texts['caliber.CaliberName']);
|
|
231
|
+
const bulletName = clip(r.texts['projectile.ProjectileName'] ?? r.texts['projectile.pname']);
|
|
232
|
+
const powderName = clip([r.texts['propellant.mname'], r.texts['propellant.pname']].filter(Boolean).join(' '));
|
|
233
|
+
const cartridge = cartridgeName ? cartridgeOf(r, cartridgeName) : undefined;
|
|
234
|
+
const bullet = bulletName ? bulletOf(r, bulletName) : [];
|
|
235
|
+
const powder = powderName ? powderOf(r, powderName) : undefined;
|
|
236
|
+
const loadName = clip(r.title) ??
|
|
237
|
+
clip([cartridgeName, bulletName, powderName].filter(Boolean).join(', ')) ??
|
|
238
|
+
'Load';
|
|
239
|
+
const load = loadOf(r, loadName, {
|
|
240
|
+
cartridge: idOf(cartridge),
|
|
241
|
+
bullet: idOf(bullet.at(-1)),
|
|
242
|
+
powder: idOf(powder),
|
|
243
|
+
});
|
|
244
|
+
const candidates = [cartridge, ...bullet, powder, load].filter((x) => x !== undefined);
|
|
245
|
+
return { candidates, unmapped: [...r.unmapped], warnings: r.warnings };
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* The record candidates of a load file: the cartridge, the bullet (after its maker) and the powder
|
|
249
|
+
* it names, then the load. Percent escapes in text values are resolved, numbers converted from the
|
|
250
|
+
* unit each field declares to the stored unit; a field with an empty value holds nothing to read.
|
|
251
|
+
* Keys come from the content, so a file read again gives the same ids and files that share a
|
|
252
|
+
* component give it one id. Throws with the reason on a file that is no load file of this format.
|
|
253
|
+
* The caller makes each candidate a record and checks it with the user record schema.
|
|
254
|
+
*/
|
|
255
|
+
export function readGrtLoad(xml) {
|
|
256
|
+
const root = parseXml(xml.replace(/^\uFEFF/, ''));
|
|
257
|
+
if (root.name !== grtLoadRoot)
|
|
258
|
+
refuseFile('rootNotLoad', { root: grtLoadRoot });
|
|
259
|
+
const input = elements(root).find((e) => e.name === 'InnerBallistikInput');
|
|
260
|
+
if (!input)
|
|
261
|
+
refuseFile('noLoad');
|
|
262
|
+
return readLoadInput(input);
|
|
263
|
+
}
|
|
264
|
+
//# sourceMappingURL=grtload.js.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { Workbook } from './cells.ts';
|
|
2
|
+
import { type DelimitedOptions } from './generic.ts';
|
|
3
|
+
import type { ChronoImport, ChronoParserOptions } from './result.ts';
|
|
4
|
+
export type { Workbook, Worksheet } from './cells.ts';
|
|
5
|
+
export { readCsrLoad } from './csrload.ts';
|
|
6
|
+
export type { Candidate, ChronoDiagnostic, FileDiagnostic, PressureDiagnostic, ReaderDiagnostic, } from './diagnostics.ts';
|
|
7
|
+
export { ReaderError } from './diagnostics.ts';
|
|
8
|
+
export type { Column, ColumnMap, CommaRemedy, DelimitedOptions, Delimiter } from './generic.ts';
|
|
9
|
+
export { parseDelimited } from './generic.ts';
|
|
10
|
+
export type { GrtLoadRead, LoadDiagnostic } from './grtload.ts';
|
|
11
|
+
export { readGrtLoad } from './grtload.ts';
|
|
12
|
+
export type { PressureHistoryImport, PressureHistoryOptions, PressureUnit, SensorPosition, TimeUnit, } from './pressure-history.ts';
|
|
13
|
+
export { parsePressureHistory } from './pressure-history.ts';
|
|
14
|
+
export { isRangeFoundryJson, parseRangeFoundryJson, sessionJsonFormat, stringifyRangeFoundryJson, } from './rangefoundry-json.ts';
|
|
15
|
+
export type { ColumnUnit, FieldSpec, TableKind } from './record-fields.ts';
|
|
16
|
+
export { fieldSpecs, tableKinds } from './record-fields.ts';
|
|
17
|
+
export { idOfKey } from './record-ids.ts';
|
|
18
|
+
export type { BuiltEntry, BuiltRecords, KindDiagnostic, KindScore, KindSuggestion, RowCounts, RowIssue, TableColumnMap, TableDiagnostic, Tier, } from './records.ts';
|
|
19
|
+
export { autoMap, buildRecords, suggestKind, tierFloors } from './records.ts';
|
|
20
|
+
export type { ChronoImport, ChronoParserOptions, SessionCandidate } from './result.ts';
|
|
21
|
+
export { parseShotView, parseShotViewWorkbook } from './shotview.ts';
|
|
22
|
+
export type { Table, TableRead, TableReadDiagnostic } from './tables.ts';
|
|
23
|
+
export { readTable, tableOfRows } from './tables.ts';
|
|
24
|
+
export type { TemplateOptions } from './template.ts';
|
|
25
|
+
export { parseRangeFoundryCsv } from './template.ts';
|
|
26
|
+
export { decodeText, formatMinutes } from './text.ts';
|
|
27
|
+
export type { VelocityUnit } from './units.ts';
|
|
28
|
+
export { parseVelocityUnit } from './units.ts';
|
|
29
|
+
export { isWorkbook, readWorkbook } from './workbook.ts';
|
|
30
|
+
export type { WorkbookOptions } from './worksheet-strings.ts';
|
|
31
|
+
export type { Inflate } from './zip.ts';
|
|
32
|
+
/** Options of `parseChrono`, each passed only to the formats that take it. */
|
|
33
|
+
export interface ParseChronoOptions extends ChronoParserOptions, Partial<Omit<DelimitedOptions, keyof ChronoParserOptions>> {
|
|
34
|
+
/** `YYYY-MM-DD`: the formats that read it keep only this day. */
|
|
35
|
+
date?: string | undefined;
|
|
36
|
+
}
|
|
37
|
+
/** A chronograph format that reads text. */
|
|
38
|
+
export interface TextChronoFormat {
|
|
39
|
+
id: string;
|
|
40
|
+
/** Shown to users. */
|
|
41
|
+
name: string;
|
|
42
|
+
reads: 'text';
|
|
43
|
+
/** True when the text is in this format; absent when the format needs a column mapping. */
|
|
44
|
+
detect?: (text: string) => boolean;
|
|
45
|
+
/** Reads the text; throws when it does not fit the format. */
|
|
46
|
+
parse: (text: string, options: ParseChronoOptions) => ChronoImport;
|
|
47
|
+
}
|
|
48
|
+
/** A chronograph format that reads a workbook read by `readWorkbook`. */
|
|
49
|
+
export interface WorkbookChronoFormat {
|
|
50
|
+
id: string;
|
|
51
|
+
/** Shown to users. */
|
|
52
|
+
name: string;
|
|
53
|
+
reads: 'workbook';
|
|
54
|
+
/** True when the workbook is in this format, told by its cells alone. */
|
|
55
|
+
detect: (book: Workbook) => boolean;
|
|
56
|
+
/** Reads the workbook; throws when it does not fit the format. */
|
|
57
|
+
parse: (book: Workbook, options: ParseChronoOptions) => ChronoImport;
|
|
58
|
+
}
|
|
59
|
+
/** One entry of `chronoFormats`. */
|
|
60
|
+
export type ChronoFormat = TextChronoFormat | WorkbookChronoFormat;
|
|
61
|
+
/**
|
|
62
|
+
* Every chronograph format, listed to users in this order by `name`; detection walks the list.
|
|
63
|
+
* `delimited` has no `detect`: it needs a column mapping.
|
|
64
|
+
*/
|
|
65
|
+
export declare const chronoFormats: readonly ChronoFormat[];
|
|
66
|
+
/** A chronograph format id, one per entry of `chronoFormats`. */
|
|
67
|
+
export type ChronoFormatId = 'rangefoundry-json' | 'shotview-csv' | 'shotview-xlsx' | 'rangefoundry-csv' | 'delimited';
|
|
68
|
+
/** The id of a chronograph format that reads a workbook. */
|
|
69
|
+
export type WorkbookFormatId = 'shotview-xlsx';
|
|
70
|
+
/**
|
|
71
|
+
* The format of a chronograph export, told by its shape, or null when none matches.
|
|
72
|
+
* `delimited` is never returned: it needs a column mapping.
|
|
73
|
+
*/
|
|
74
|
+
export declare function detectFormat(text: string): ChronoFormatId | null;
|
|
75
|
+
/**
|
|
76
|
+
* The format of a workbook read by `readWorkbook`, told by its cells alone (never by file or
|
|
77
|
+
* worksheet names), or null when none matches.
|
|
78
|
+
*/
|
|
79
|
+
export declare function detectWorkbookFormat(book: Workbook): WorkbookFormatId | null;
|
|
80
|
+
/**
|
|
81
|
+
* Parses text or a workbook (read by the caller) as `format`, detected by `detectFormat` or
|
|
82
|
+
* `detectWorkbookFormat` when not given; null when none is detected.
|
|
83
|
+
*/
|
|
84
|
+
export declare function parseChrono(input: string | Workbook, options: ParseChronoOptions, format: ChronoFormatId): ChronoImport;
|
|
85
|
+
export declare function parseChrono(input: string | Workbook, options?: ParseChronoOptions): ChronoImport | null;
|