@rangefoundry/importers 0.0.0-stage → 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 +21 -2
- 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 +62 -3
package/README.md
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @rangefoundry/importers
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Parsers that turn chronograph exports, pressure histories, spreadsheets, load files and the RangeFoundry JSON and CSV files into candidates: a session, or a record without the id and save time the caller gives it (`id` is `idOfKey(key)`). The table and load-file readers report a skipped cell or field as a code with its values (`{ code, params }`) for the caller to word. They take text or a workbook the caller has read and do no I/O.
|
|
4
|
+
|
|
5
|
+
With Node 26 or later:
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @rangefoundry/importers
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
import { parseDelimited } from '@rangefoundry/importers'
|
|
13
|
+
|
|
14
|
+
const result = parseDelimited('2800\n2810\n2795', { columns: { velocity: 1 }, velocityUnit: 'ft/s' })
|
|
15
|
+
console.log(result.session.strings[0].shots.map((shot) => shot.velocity.value)) // [ 853.44, 856.488, 851.916 ]
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Documentation: https://rangefoundry.github.io/workbench/docs/libraries/importers/
|
|
19
|
+
|
|
20
|
+
Changes: https://github.com/RangeFoundry/workbench/blob/main/packages/importers/CHANGELOG.md
|
|
21
|
+
|
|
22
|
+
License: AGPL-3.0-or-later
|
package/dist/cells.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Name and rows of cell text of one worksheet; no styles, formats or formulas applied. */
|
|
2
|
+
export interface Worksheet {
|
|
3
|
+
name: string;
|
|
4
|
+
/** Rows in document order; cells placed by their reference, gaps as empty text. */
|
|
5
|
+
rows: string[][];
|
|
6
|
+
}
|
|
7
|
+
/** The worksheets of an XLSX or legacy XLS file, in file order. */
|
|
8
|
+
export interface Workbook {
|
|
9
|
+
worksheets: Worksheet[];
|
|
10
|
+
}
|
|
11
|
+
/** Cells (gaps included) and characters of cell text every worksheet of a workbook may still produce. */
|
|
12
|
+
export interface CellBudget {
|
|
13
|
+
cells: number;
|
|
14
|
+
characters: number;
|
|
15
|
+
}
|
|
16
|
+
/** Cell text trimmed and U+FEFF removed. */
|
|
17
|
+
export declare const clean: (text: string) => string;
|
|
18
|
+
/** Where a refused cell is: its reference, or its column (from 1) when it has none. */
|
|
19
|
+
export type CellPlace = {
|
|
20
|
+
cell: string;
|
|
21
|
+
} | {
|
|
22
|
+
column: number;
|
|
23
|
+
};
|
|
24
|
+
/** A cell to place: its column (from 1), its text, and its place, built only for a refusal. */
|
|
25
|
+
export interface PlacedCell {
|
|
26
|
+
column: number;
|
|
27
|
+
text: string;
|
|
28
|
+
at: () => CellPlace;
|
|
29
|
+
}
|
|
30
|
+
/** After the row's cells, gaps as empty text, counting the budgets; refuses a column beyond IV or not after the previous cell. */
|
|
31
|
+
export declare function placeCell(cells: string[], { column, text, at }: PlacedCell, remaining: CellBudget): void;
|
package/dist/cells.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Workbook types and the cell placement shared by the workbook readers.
|
|
2
|
+
import { refuseFile } from './diagnostics.js';
|
|
3
|
+
import { maxCellCharacters, maxCells, maxColumn } from './limits.js';
|
|
4
|
+
/** Cell text trimmed and U+FEFF removed. */
|
|
5
|
+
export const clean = (text) => text.replaceAll('', '').trim();
|
|
6
|
+
/** After the row's cells, gaps as empty text, counting the budgets; refuses a column beyond IV or not after the previous cell. */
|
|
7
|
+
export function placeCell(cells, { column, text, at }, remaining) {
|
|
8
|
+
if (column > maxColumn)
|
|
9
|
+
refuseFile('cellBeyondColumnIV', at());
|
|
10
|
+
if (column <= cells.length)
|
|
11
|
+
refuseFile('cellOutOfOrder', at());
|
|
12
|
+
remaining.cells -= column - cells.length;
|
|
13
|
+
remaining.characters -= text.length;
|
|
14
|
+
if (remaining.cells < 0)
|
|
15
|
+
refuseFile('tooManyCells', { max: maxCells });
|
|
16
|
+
if (remaining.characters < 0)
|
|
17
|
+
refuseFile('tooMuchCellText', { max: maxCellCharacters });
|
|
18
|
+
while (cells.length < column - 1)
|
|
19
|
+
cells.push('');
|
|
20
|
+
cells.push(text);
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=cells.js.map
|
package/dist/cfb.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** Directly under the root storage, names in upper case; each call reads the stream's bytes and refuses a stream that declares more than `limit` bytes. */
|
|
2
|
+
export declare function compoundStreams(bytes: Uint8Array, wanted: readonly string[]): Map<string, (limit: number) => Uint8Array>;
|
package/dist/cfb.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// Compound files ([MS-CFB] Compound File Binary File Format, revision 12.0, https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-cfb/53989ce4-7b05-4f8d-829b-d08d6148375b; section numbers refer to it), read only as far as the streams under the root storage; every loop is bounded by the file's sector count, and no buffer is sized from a declared value before that value passed a limit
|
|
2
|
+
import { refuseFile } from './diagnostics.js';
|
|
3
|
+
// sector numbers above REGSECT 0xFFFFFFF9 are markers (2.1)
|
|
4
|
+
const lastRegular = 0xfffffff9;
|
|
5
|
+
const noStream = 0xffffffff;
|
|
6
|
+
/** Sector `k` of `chain`; the callers' bounds checks keep `k` inside it. */
|
|
7
|
+
function inChain(chain, k) {
|
|
8
|
+
return chain[k] ?? refuseFile('cfbSectorOutsideChain', { index: k, length: chain.length });
|
|
9
|
+
}
|
|
10
|
+
// assumed bound, not a cited one: a workbook's root storage holds a few entries
|
|
11
|
+
const maxRootEntries = 65536;
|
|
12
|
+
/** The header (2.2): byte order, version 3 or 4 with its sector size, standard mini stream layout. */
|
|
13
|
+
function readHeader(bytes) {
|
|
14
|
+
if (bytes.length < 512)
|
|
15
|
+
refuseFile('cfbTooShort');
|
|
16
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
17
|
+
// the last sector may be short (2.3), so every read is checked against the file length
|
|
18
|
+
const within = (at, n) => {
|
|
19
|
+
if (at + n > bytes.length)
|
|
20
|
+
refuseFile('cfbEndsBefore', { byte: at + n });
|
|
21
|
+
return at;
|
|
22
|
+
};
|
|
23
|
+
const u16 = (at) => view.getUint16(within(at, 2), true);
|
|
24
|
+
const u32 = (at) => view.getUint32(within(at, 4), true);
|
|
25
|
+
if (u16(0x1c) !== 0xfffe)
|
|
26
|
+
refuseFile('cfbByteOrder');
|
|
27
|
+
const version = u16(0x1a);
|
|
28
|
+
const shift = u16(0x1e);
|
|
29
|
+
if (!((version === 3 && shift === 9) || (version === 4 && shift === 12))) {
|
|
30
|
+
refuseFile('cfbVersion', { version, shift });
|
|
31
|
+
}
|
|
32
|
+
if (u16(0x20) !== 6 || u32(0x38) !== 4096)
|
|
33
|
+
refuseFile('cfbMiniLayout');
|
|
34
|
+
const size = 1 << shift;
|
|
35
|
+
// sector n starts at (n + 1) * size (2.3) and must start inside the file
|
|
36
|
+
const sectors = Math.ceil(bytes.length / size) - 1;
|
|
37
|
+
const offset = (n) => {
|
|
38
|
+
if (n >= sectors)
|
|
39
|
+
refuseFile('cfbSectorOutside', { sector: n });
|
|
40
|
+
return (n + 1) * size;
|
|
41
|
+
};
|
|
42
|
+
return { bytes, version, size, per: size / 4, sectors, within, u16, u32, offset };
|
|
43
|
+
}
|
|
44
|
+
/** The FAT sectors: 109 in the header, then the DIFAT chain (2.5); each must lie in the file. */
|
|
45
|
+
function buildFat(file) {
|
|
46
|
+
const { u32, offset } = file;
|
|
47
|
+
const fatCount = u32(0x2c);
|
|
48
|
+
const fat = [];
|
|
49
|
+
const listed = () => refuseFile('cfbFatListed', { listed: fat.length, count: fatCount });
|
|
50
|
+
if (fatCount > file.sectors)
|
|
51
|
+
listed();
|
|
52
|
+
for (let k = 0; k < 109 && fat.length < fatCount; k++)
|
|
53
|
+
fat.push(u32(0x4c + 4 * k));
|
|
54
|
+
readDifat(file, fat, fatCount);
|
|
55
|
+
if (fat.length < fatCount)
|
|
56
|
+
listed();
|
|
57
|
+
for (const n of fat)
|
|
58
|
+
offset(n);
|
|
59
|
+
return fat;
|
|
60
|
+
}
|
|
61
|
+
/** Adds the FAT sectors the DIFAT chain lists (2.5) to `fat`, up to `fatCount`. */
|
|
62
|
+
function readDifat(file, fat, fatCount) {
|
|
63
|
+
const { u32, offset, size, per } = file;
|
|
64
|
+
const difatSeen = new Set();
|
|
65
|
+
for (let d = u32(0x44), k = 0; fat.length < fatCount && k < u32(0x48); k++) {
|
|
66
|
+
if (d > lastRegular)
|
|
67
|
+
break;
|
|
68
|
+
if (difatSeen.has(d))
|
|
69
|
+
refuseFile('cfbChainLoops', { sector: d });
|
|
70
|
+
difatSeen.add(d);
|
|
71
|
+
const at = offset(d);
|
|
72
|
+
for (let j = 0; j < per - 1 && fat.length < fatCount; j++)
|
|
73
|
+
fat.push(u32(at + 4 * j));
|
|
74
|
+
d = u32(at + size - 4);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** From the table (FAT or mini FAT) held in the sectors `table`, read in place (2.3); `missing` is the refusal of a sector the table does not reach. */
|
|
78
|
+
function tableNext(file, table, missing) {
|
|
79
|
+
return (n) => {
|
|
80
|
+
const s = table[Math.floor(n / file.per)];
|
|
81
|
+
if (s === undefined)
|
|
82
|
+
refuseFile(missing, { sector: n });
|
|
83
|
+
return file.u32(file.offset(s) + 4 * (n % file.per));
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/** `count` sectors, or up to the end when undefined; loops and early ends are refused, and with `inFile` each sector must lie in the file. */
|
|
87
|
+
function readChain(file, { step, inFile }, start, count) {
|
|
88
|
+
const out = [];
|
|
89
|
+
const seen = new Set();
|
|
90
|
+
for (let n = start; count === undefined ? n <= lastRegular : out.length < count; n = step(n)) {
|
|
91
|
+
if (n > lastRegular)
|
|
92
|
+
refuseFile('cfbChainEnds');
|
|
93
|
+
if (seen.has(n))
|
|
94
|
+
refuseFile('cfbChainLoops', { sector: n });
|
|
95
|
+
seen.add(n);
|
|
96
|
+
if (inFile)
|
|
97
|
+
file.offset(n);
|
|
98
|
+
out.push(n);
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
/** Streams under 4096 bytes lie in the mini stream of the root entry at `root`; the reader refuses a stream that declares more than its `limit`. */
|
|
103
|
+
function streamReader(file, fatChain, root, { name, start, declared }) {
|
|
104
|
+
const { bytes, size, u32, offset } = file;
|
|
105
|
+
return (limit) => {
|
|
106
|
+
if (declared > limit)
|
|
107
|
+
refuseFile('cfbStreamTooLarge', { stream: name, declared, limit });
|
|
108
|
+
const out = new Uint8Array(declared);
|
|
109
|
+
const copy = (from, length, to) => {
|
|
110
|
+
if (from + length > bytes.length)
|
|
111
|
+
refuseFile('cfbStreamPastEnd', { stream: name });
|
|
112
|
+
out.set(bytes.subarray(from, from + length), to);
|
|
113
|
+
};
|
|
114
|
+
if (declared >= 4096) {
|
|
115
|
+
readChain(file, fatChain, start, Math.ceil(declared / size)).forEach((n, k) => {
|
|
116
|
+
copy(offset(n), Math.min(size, declared - k * size), k * size);
|
|
117
|
+
});
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
if (declared === 0)
|
|
121
|
+
return out;
|
|
122
|
+
// mini stream (2.4): 64-byte mini sectors in the root entry's chain
|
|
123
|
+
const miniFatStart = u32(0x3c);
|
|
124
|
+
const rootStart = u32(root + 0x74);
|
|
125
|
+
if (miniFatStart > lastRegular || rootStart > lastRegular)
|
|
126
|
+
refuseFile('cfbNoMiniStream');
|
|
127
|
+
const miniFat = readChain(file, fatChain, miniFatStart);
|
|
128
|
+
const rootChain = readChain(file, fatChain, rootStart);
|
|
129
|
+
const miniLength = Math.min(u32(root + 0x78), rootChain.length * size);
|
|
130
|
+
const miniNext = tableNext(file, miniFat, 'cfbNoMiniFatEntry');
|
|
131
|
+
const miniChain = { step: miniNext, inFile: false };
|
|
132
|
+
readChain(file, miniChain, start, Math.ceil(declared / 64)).forEach((m, k) => {
|
|
133
|
+
if ((m + 1) * 64 > miniLength)
|
|
134
|
+
refuseFile('cfbMiniSectorOutside', { sector: m });
|
|
135
|
+
const from = offset(inChain(rootChain, Math.floor((m * 64) / size))) + ((m * 64) % size);
|
|
136
|
+
copy(from, Math.min(64, declared - k * 64), k * 64);
|
|
137
|
+
});
|
|
138
|
+
return out;
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** The name of the directory entry at `at`. */
|
|
142
|
+
function entryName(file, at) {
|
|
143
|
+
// the name length counts bytes with the terminating NUL; at most 32 UTF-16 code units
|
|
144
|
+
const units = Math.floor(Math.min(file.u16(at + 0x40), 64) / 2) - 1;
|
|
145
|
+
let name = '';
|
|
146
|
+
for (let k = 0; k < units; k++)
|
|
147
|
+
name += String.fromCharCode(file.u16(at + 2 * k));
|
|
148
|
+
return name;
|
|
149
|
+
}
|
|
150
|
+
/** The declared stream size of the directory entry at `at`. */
|
|
151
|
+
function entrySize(file, at) {
|
|
152
|
+
// version 3 ignores the high 32 bits of the size (2.6.1)
|
|
153
|
+
return file.u32(at + 0x78) + (file.version === 4 ? file.u32(at + 0x7c) * 2 ** 32 : 0);
|
|
154
|
+
}
|
|
155
|
+
/** The directory (2.6, 128-byte entries in the directory chain): a reader for each stream named in `wanted` among the children of the root storage. */
|
|
156
|
+
function readDirectory(file, fatChain, wanted) {
|
|
157
|
+
const { bytes, size, within, u32, offset } = file;
|
|
158
|
+
const directory = readChain(file, fatChain, u32(0x30));
|
|
159
|
+
const perSector = size / 128;
|
|
160
|
+
const entries = directory.length * perSector;
|
|
161
|
+
const entry = (id) => within(offset(inChain(directory, Math.floor(id / perSector))) + (id % perSector) * 128, 128);
|
|
162
|
+
if (entries === 0 || bytes[entry(0) + 0x42] !== 5)
|
|
163
|
+
refuseFile('cfbNoRoot');
|
|
164
|
+
const root = entry(0);
|
|
165
|
+
const streams = new Map();
|
|
166
|
+
// the root's children form a binary tree of siblings (2.6.4); visited without recursion
|
|
167
|
+
const stack = [u32(root + 0x4c)];
|
|
168
|
+
const visited = new Set();
|
|
169
|
+
for (let id = stack.pop(); id !== undefined; id = stack.pop()) {
|
|
170
|
+
if (id === noStream)
|
|
171
|
+
continue;
|
|
172
|
+
if (id >= entries || visited.has(id))
|
|
173
|
+
refuseFile('cfbEntryRepeated', { entry: id });
|
|
174
|
+
visited.add(id);
|
|
175
|
+
if (visited.size > maxRootEntries) {
|
|
176
|
+
refuseFile('cfbRootTooLarge', { max: maxRootEntries });
|
|
177
|
+
}
|
|
178
|
+
const at = entry(id);
|
|
179
|
+
stack.push(u32(at + 0x44), u32(at + 0x48));
|
|
180
|
+
if (bytes[at + 0x42] !== 2)
|
|
181
|
+
continue;
|
|
182
|
+
const name = entryName(file, at);
|
|
183
|
+
if (!wanted.includes(name.toUpperCase()))
|
|
184
|
+
continue;
|
|
185
|
+
const stream = { name, start: u32(at + 0x74), declared: entrySize(file, at) };
|
|
186
|
+
streams.set(name.toUpperCase(), streamReader(file, fatChain, root, stream));
|
|
187
|
+
}
|
|
188
|
+
return streams;
|
|
189
|
+
}
|
|
190
|
+
/** Directly under the root storage, names in upper case; each call reads the stream's bytes and refuses a stream that declares more than `limit` bytes. */
|
|
191
|
+
export function compoundStreams(bytes, wanted) {
|
|
192
|
+
const file = readHeader(bytes);
|
|
193
|
+
const fat = buildFat(file);
|
|
194
|
+
return readDirectory(file, { step: tableNext(file, fat, 'cfbNoFatEntry'), inFile: true }, wanted);
|
|
195
|
+
}
|
|
196
|
+
//# sourceMappingURL=cfb.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type GrtLoadRead } from './grtload.ts';
|
|
2
|
+
/**
|
|
3
|
+
* The record candidates of a ChamberSim Reloaded load file: those of `readGrtLoad` (the cartridge,
|
|
4
|
+
* the bullet after its maker, the powder and the load), then a session for each measurement series
|
|
5
|
+
* whose strings name the load. A series maps per charge to a string of shot velocities (m/s) that varies
|
|
6
|
+
* the charge; shot pressures, the display settings and every other part are listed as not read.
|
|
7
|
+
* A format other than 1 gives a warning. Ids come from the content (a repeated series of the same
|
|
8
|
+
* content also from its count), so a file read again gives the same ids. Throws with the reason
|
|
9
|
+
* on a file that is no load file of this format. The caller makes each candidate a record and
|
|
10
|
+
* checks it with the user record schema.
|
|
11
|
+
*/
|
|
12
|
+
export declare function readCsrLoad(xml: string): GrtLoadRead;
|
package/dist/csrload.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// The load files of ChamberSim Reloaded (`.csrload`, XML) as record candidates: the load input has the layout of a GRT load file (`readLoadInput`), this file adds the format check and the measurement series; mapping and reasons in `apps/docs/docs/data/grt-load-files.md`, written from saved files of format 1
|
|
2
|
+
import { refuseFile } from './diagnostics.js';
|
|
3
|
+
import { clip, elements, named, readLoadInput, unescaped, } from './grtload.js';
|
|
4
|
+
import { idOfKey } from './record-ids.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 csrLoadRoot = 'ChamberSimReloaded';
|
|
9
|
+
/** The `format` attribute of the root the reader was written for. */
|
|
10
|
+
const csrFormat = '1';
|
|
11
|
+
/** The most shots of a string and strings of a session the session schema takes. */
|
|
12
|
+
const maxShots = 5000;
|
|
13
|
+
const maxStrings = 500;
|
|
14
|
+
/** The attributes of the measurement elements that are read; the others are listed when they hold a value. */
|
|
15
|
+
const readAttributes = {
|
|
16
|
+
Measurement: [],
|
|
17
|
+
charge: ['name', 'note', 'value'],
|
|
18
|
+
shot: ['velocity'],
|
|
19
|
+
};
|
|
20
|
+
/** An attribute value that holds nothing: empty, an unmeasured pressure, empty source options. */
|
|
21
|
+
const holdsNothing = (name, value) => value === '' || (name === 'pressure' && Number(value) === 0) || value === '%7B%7D';
|
|
22
|
+
/** The attributes of `e` that hold a value and are not read, as `at.name`, into `unmapped`. */
|
|
23
|
+
function unreadAttributes(e, at, unmapped) {
|
|
24
|
+
for (const [name, value] of Object.entries(e.attributes))
|
|
25
|
+
if (!readAttributes[e.name]?.includes(name) && !holdsNothing(name, value.trim()))
|
|
26
|
+
unmapped.add(`${at}.${name}`);
|
|
27
|
+
}
|
|
28
|
+
/** The shots of a charge with a velocity above 0, in m/s; each other shot gives a warning. */
|
|
29
|
+
function shotsOf(c, at, unmapped, warnings) {
|
|
30
|
+
const shots = [];
|
|
31
|
+
for (const s of elements(c)) {
|
|
32
|
+
if (s.name !== 'shot') {
|
|
33
|
+
unmapped.add(`${at}.${s.name}`);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
unreadAttributes(s, `${at}.shot`, unmapped);
|
|
37
|
+
const v = readDecimal((s.attributes['velocity'] ?? '').trim());
|
|
38
|
+
if (Number.isFinite(v) && v > 0)
|
|
39
|
+
shots.push({ velocity: { value: v } });
|
|
40
|
+
else
|
|
41
|
+
warnings.push({ code: 'shotWithoutVelocity', params: { at } });
|
|
42
|
+
}
|
|
43
|
+
return shots;
|
|
44
|
+
}
|
|
45
|
+
/** Velocities in m/s, the charge from kg to g; undefined, with a warning, when no shot has a velocity. */
|
|
46
|
+
function stringOf(c, at, unmapped, warnings) {
|
|
47
|
+
unreadAttributes(c, at, unmapped);
|
|
48
|
+
const shots = shotsOf(c, at, unmapped, warnings);
|
|
49
|
+
const label = clip(unescaped(c.attributes['name'] ?? '', `${at}.name`, warnings));
|
|
50
|
+
const labelText = label ?? '';
|
|
51
|
+
if (shots.length === 0) {
|
|
52
|
+
warnings.push({ code: 'chargeWithoutShots', params: { at, label: labelText } });
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
const note = clip(unescaped(c.attributes['note'] ?? '', `${at}.note`, warnings), 2000);
|
|
56
|
+
const grams = chargeGrams(c);
|
|
57
|
+
const string = {
|
|
58
|
+
...(label && { label }),
|
|
59
|
+
...(note && { note }),
|
|
60
|
+
shots: shots.slice(0, maxShots),
|
|
61
|
+
};
|
|
62
|
+
if (shots.length > maxShots)
|
|
63
|
+
warnings.push({
|
|
64
|
+
code: 'shotsBeyondLimit',
|
|
65
|
+
params: { at, count: shots.length - maxShots, label: labelText, max: maxShots },
|
|
66
|
+
});
|
|
67
|
+
if (grams === undefined)
|
|
68
|
+
warnings.push({ code: 'chargeWithoutMass', params: { at, label: labelText } });
|
|
69
|
+
else
|
|
70
|
+
string.variation = { kind: 'charge', value: { value: grams } };
|
|
71
|
+
return string;
|
|
72
|
+
}
|
|
73
|
+
/** The mass of a charge in g from its `value` in kg, or undefined when that is not above 0. */
|
|
74
|
+
function chargeGrams(c) {
|
|
75
|
+
const kg = readDecimal((c.attributes['value'] ?? '').trim());
|
|
76
|
+
return Number.isFinite(kg) && kg > 0 ? Number((kg * 1000).toPrecision(12)) : undefined;
|
|
77
|
+
}
|
|
78
|
+
/** Each measurement series of the appendix as a session candidate whose strings name the load. */
|
|
79
|
+
function sessionsOf(appendix, load, { unmapped, warnings }) {
|
|
80
|
+
const sessions = [];
|
|
81
|
+
const seen = new Map();
|
|
82
|
+
for (const m of appendix ? elements(appendix).filter((e) => e.name === 'Measurement') : []) {
|
|
83
|
+
const at = 'appendix.Measurement';
|
|
84
|
+
unreadAttributes(m, at, unmapped);
|
|
85
|
+
const strings = elements(m).flatMap((c) => {
|
|
86
|
+
if (c.name === 'charge')
|
|
87
|
+
return stringOf(c, `${at}.charge`, unmapped, warnings) ?? [];
|
|
88
|
+
unmapped.add(`${at}.${c.name}`);
|
|
89
|
+
return [];
|
|
90
|
+
});
|
|
91
|
+
if (strings.length === 0)
|
|
92
|
+
continue;
|
|
93
|
+
const left = strings.slice(maxStrings);
|
|
94
|
+
if (left.length > 0)
|
|
95
|
+
warnings.push({
|
|
96
|
+
code: 'chargesBeyondLimit',
|
|
97
|
+
params: {
|
|
98
|
+
at,
|
|
99
|
+
count: left.length,
|
|
100
|
+
shots: left.reduce((n, s) => n + s.shots.length, 0),
|
|
101
|
+
max: maxStrings,
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
const data = {
|
|
105
|
+
origin: 'user',
|
|
106
|
+
device: { kind: 'other' },
|
|
107
|
+
strings: strings
|
|
108
|
+
.slice(0, maxStrings)
|
|
109
|
+
.map((s) => ({ load: `user:${idOfKey(load.key)}`, ...s })),
|
|
110
|
+
provenance: {
|
|
111
|
+
kind: 'measured',
|
|
112
|
+
sources: [{ title: 'Measurements of a ChamberSim Reloaded load file' }],
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
// The first series of a content keeps the plain key; a repeat adds its count, so ids stay apart.
|
|
116
|
+
const content = JSON.stringify(data);
|
|
117
|
+
const repeat = seen.get(content) ?? 0;
|
|
118
|
+
seen.set(content, repeat + 1);
|
|
119
|
+
const key = repeat === 0 ? 'session' : `session|${repeat}`;
|
|
120
|
+
sessions.push({ kind: 'session', ...named(key, load.name, data) });
|
|
121
|
+
}
|
|
122
|
+
return sessions;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The record candidates of a ChamberSim Reloaded load file: those of `readGrtLoad` (the cartridge,
|
|
126
|
+
* the bullet after its maker, the powder and the load), then a session for each measurement series
|
|
127
|
+
* whose strings name the load. A series maps per charge to a string of shot velocities (m/s) that varies
|
|
128
|
+
* the charge; shot pressures, the display settings and every other part are listed as not read.
|
|
129
|
+
* A format other than 1 gives a warning. Ids come from the content (a repeated series of the same
|
|
130
|
+
* content also from its count), so a file read again gives the same ids. Throws with the reason
|
|
131
|
+
* on a file that is no load file of this format. The caller makes each candidate a record and
|
|
132
|
+
* checks it with the user record schema.
|
|
133
|
+
*/
|
|
134
|
+
export function readCsrLoad(xml) {
|
|
135
|
+
const root = parseXml(xml.replace(/^/, ''));
|
|
136
|
+
if (root.name !== csrLoadRoot)
|
|
137
|
+
refuseFile('rootNotLoad', { root: csrLoadRoot });
|
|
138
|
+
const input = elements(root).find((e) => e.name === 'load');
|
|
139
|
+
if (!input)
|
|
140
|
+
refuseFile('noLoad');
|
|
141
|
+
const read = readLoadInput(input);
|
|
142
|
+
const format = root.attributes['format'];
|
|
143
|
+
const formatWarning = format
|
|
144
|
+
? { code: 'otherFormat', params: { format: format.slice(0, 20), expected: csrFormat } }
|
|
145
|
+
: { code: 'unknownFormat', params: { expected: csrFormat } };
|
|
146
|
+
const warnings = format === csrFormat ? read.warnings : [formatWarning, ...read.warnings];
|
|
147
|
+
const unmapped = new Set(read.unmapped.filter((u) => u !== 'appendix.Measurement'));
|
|
148
|
+
const load = read.candidates.at(-1);
|
|
149
|
+
const appendix = elements(input).find((e) => e.name === 'appendix');
|
|
150
|
+
const sessions = load ? sessionsOf(appendix, load, { unmapped, warnings }) : [];
|
|
151
|
+
return { candidates: [...read.candidates, ...sessions], unmapped: [...unmapped], warnings };
|
|
152
|
+
}
|
|
153
|
+
//# sourceMappingURL=csrload.js.map
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { UserRecord } from '@rangefoundry/schema';
|
|
2
|
+
import type { Diagnostic } from '@rangefoundry/statistics';
|
|
3
|
+
/** A finding of a reader: its code and the values its message names. The app words it in its language. */
|
|
4
|
+
export type ReaderDiagnostic<Code extends string> = Diagnostic<Code, Readonly<Record<string, string | number | readonly string[]>>>;
|
|
5
|
+
/** A file a reader refuses: `diagnostic` says why, and the app words it. The message is the code. */
|
|
6
|
+
export declare class ReaderError extends Error {
|
|
7
|
+
readonly diagnostic: ChronoDiagnostic | PressureDiagnostic | FileDiagnostic;
|
|
8
|
+
constructor(diagnostic: ChronoDiagnostic | PressureDiagnostic | FileDiagnostic, options?: ErrorOptions);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* What a chronograph reader warns of or refuses a file for. A `worksheet` or `row` param names
|
|
12
|
+
* where; the app words it before the message.
|
|
13
|
+
*/
|
|
14
|
+
export type ChronoDiagnostic = ReaderDiagnostic<'sha256Malformed' | 'outsideRange' | 'noShots' | 'unitDiffersFromCaller' | 'unknownUnit' | 'missingUnit' | 'unknownUnitNamedByCaller' | 'missingUnitNamedByCaller' | 'velocityNotNumber' | 'velocityNotPositive' | 'skipRowsNotWhole' | 'skipRowsWithHeaderText' | 'columnBelowOne' | 'emptyHeaderText' | 'noHeaderRow' | 'commaMaySplit' | 'commaMayCutVelocity' | 'cellCountDiffers' | 'moreCellsThanHeader' | 'moreCellsThanHeaderComma' | 'unitCellDiffersFromHeader' | 'coldBoreUnknown' | 'noVelocity' | 'stringReturns' | 'notShotView' | 'footerDateUnknown' | 'footerDateMissing' | 'noShotViewHeader' | 'statisticNotNumber' | 'statisticDiffers' | 'footerStatisticsMissing' | 'dateFromOption' | 'noShotRows' | 'noStringOnDate' | 'severalDays' | 'notSessionJson' | 'versionUnsupported' | 'memberNotPositive' | 'memberNotText' | 'memberNotObject' | 'memberNotDeviceKind' | 'velocityRequired' | 'memberNotBoolean' | 'excludedNotText' | 'noStrings' | 'noStringShots' | 'memberNotDate' | 'notTemplate' | 'needsColumnMapping' | 'readsText' | 'readsWorkbooks'>;
|
|
15
|
+
/** Throws the refusal `code` with `params`. */
|
|
16
|
+
export declare function refuse(code: ChronoDiagnostic['code'], params?: ChronoDiagnostic['params']): never;
|
|
17
|
+
/**
|
|
18
|
+
* What the pressure-history reader warns of or refuses a trace for. `column` is `time` or
|
|
19
|
+
* `pressure`, `line` the line of the file.
|
|
20
|
+
*/
|
|
21
|
+
export type PressureDiagnostic = ReaderDiagnostic<'sensorMissing' | 'columnsNotDistinct' | 'cutoffNotPositive' | 'columnUnitDiffersFromCaller' | 'columnUnitMissing' | 'columnUnitNamedByCaller' | 'readingNotNumber' | 'readingNotFinite' | 'timesNotIncreasing' | 'tooFewSamples'>;
|
|
22
|
+
/** Throws the pressure-history refusal `code` with `params`. */
|
|
23
|
+
export declare function refuseTrace(code: PressureDiagnostic['code'], params?: PressureDiagnostic['params']): never;
|
|
24
|
+
/**
|
|
25
|
+
* Why a file reader refuses the bytes or the text of a file: text decoding, the ZIP and XML of an
|
|
26
|
+
* XLSX workbook, the compound file and records of an XLS workbook, their cells, and the root of an
|
|
27
|
+
* XML load file. A `part` param names the XLSX part, a `worksheet` param the XLS worksheet and a
|
|
28
|
+
* `sharedString` param the XLS shared string; the app words them before the message. A refused
|
|
29
|
+
* cell is named by its reference (`cell`), or by its column (`column`) when it has none.
|
|
30
|
+
*/
|
|
31
|
+
export type FileDiagnostic = ReaderDiagnostic<'utf16OddBytes' | 'notUnicodeText' | 'cellBeyondColumnIV' | 'cellOutOfOrder' | 'tooManyCells' | 'tooMuchCellText' | 'zipDirectoryMalformed' | 'zip64' | 'zipNoEnd' | 'zipSplit' | 'zipDirectoryOutside' | 'partTwice' | 'partsDifferInCase' | 'partEncrypted' | 'partMethod' | 'partTooLarge' | 'partsTooLarge' | 'partCompressedTooLarge' | 'partNoLocalHeader' | 'partDataOutside' | 'partStoredSize' | 'partCorrupt' | 'partInflatesMore' | 'partInflatesLess' | 'partCrc' | 'relationshipLeaves' | 'sharedStringOutOfRange' | 'cellRefMalformed' | 'partMissing' | 'notUtf8' | 'xmlElementsExceeded' | 'xmlCharactersExceeded' | 'relationshipTwice' | 'sheetNoRelationship' | 'sheetPartAgain' | 'noDecompressionStream' | 'noWorkbookPart' | 'unknownEntity' | 'notXmlChar' | 'bareAmpersand' | 'xmlBudgetSpent' | 'unclosedProcessingInstruction' | 'unclosedComment' | 'unclosedCdata' | 'duplicateAttribute' | 'tooManyAttributes' | 'malformedTag' | 'malformedTagNamed' | 'textOutsideRoot' | 'encodingNotRead' | 'endTagMismatch' | 'nestTooDeep' | 'secondRoot' | 'doctype' | 'markupDeclaration' | 'unclosedElement' | 'noRoot' | 'rootNotLoad' | 'noLoad' | 'cfbSectorOutsideChain' | 'cfbTooShort' | 'cfbEndsBefore' | 'cfbByteOrder' | 'cfbVersion' | 'cfbMiniLayout' | 'cfbSectorOutside' | 'cfbFatListed' | 'cfbChainLoops' | 'cfbNoFatEntry' | 'cfbNoMiniFatEntry' | 'cfbChainEnds' | 'cfbStreamTooLarge' | 'cfbStreamPastEnd' | 'cfbNoMiniStream' | 'cfbMiniSectorOutside' | 'cfbNoRoot' | 'cfbEntryRepeated' | 'cfbRootTooLarge' | 'xlsPhoneticNegative' | 'xlsStringMalformed' | 'xlsRecordPastEnd' | 'xlsSubstreamsOverlap' | 'xlsRecordShort' | 'xlsNotBiff8' | 'xlsNoWorkbookEof' | 'xlsEncrypted' | 'xlsFormulaNoString' | 'xlsNumberNotFinite' | 'xlsUnknownErrorCode' | 'xlsCellsMismatch' | 'xlsUnknownValueType' | 'xlsWorksheetNoEof' | 'xlsWorksheetNoBof' | 'xlsWorksheetSameStart' | 'xlsNoWorkbookStream' | 'xlsSharedStringsEnd'>;
|
|
32
|
+
/** Throws the file refusal `code` with `params`. */
|
|
33
|
+
export declare function refuseFile(code: FileDiagnostic['code'], params?: FileDiagnostic['params']): never;
|
|
34
|
+
/** `e` again with `at` added to the params of its diagnostic, when it is a reader's refusal. */
|
|
35
|
+
export declare function locatedError(e: unknown, at: Record<string, string | number>): unknown;
|
|
36
|
+
/**
|
|
37
|
+
* A record as a reader reads it, without the id and save time the app gives it when it keeps it.
|
|
38
|
+
* Its id is `idOfKey(key)`; the references of the candidates of one read to each other use it.
|
|
39
|
+
*/
|
|
40
|
+
export type Candidate = UserRecord extends infer R ? R extends UserRecord ? Omit<R, 'id' | 'saved'> & {
|
|
41
|
+
key: string;
|
|
42
|
+
} : never : never;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** A file a reader refuses: `diagnostic` says why, and the app words it. The message is the code. */
|
|
2
|
+
export class ReaderError extends Error {
|
|
3
|
+
diagnostic;
|
|
4
|
+
constructor(diagnostic, options) {
|
|
5
|
+
super(diagnostic.code, options);
|
|
6
|
+
this.name = 'ReaderError';
|
|
7
|
+
this.diagnostic = diagnostic;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** Throws the refusal `code` with `params`. */
|
|
11
|
+
export function refuse(code, params = {}) {
|
|
12
|
+
throw new ReaderError({ code, params });
|
|
13
|
+
}
|
|
14
|
+
/** Throws the pressure-history refusal `code` with `params`. */
|
|
15
|
+
export function refuseTrace(code, params = {}) {
|
|
16
|
+
throw new ReaderError({ code, params });
|
|
17
|
+
}
|
|
18
|
+
/** Throws the file refusal `code` with `params`. */
|
|
19
|
+
export function refuseFile(code, params = {}) {
|
|
20
|
+
throw new ReaderError({ code, params });
|
|
21
|
+
}
|
|
22
|
+
/** `e` again with `at` added to the params of its diagnostic, when it is a reader's refusal. */
|
|
23
|
+
export function locatedError(e, at) {
|
|
24
|
+
if (!(e instanceof ReaderError))
|
|
25
|
+
return e;
|
|
26
|
+
const d = e.diagnostic;
|
|
27
|
+
return new ReaderError({ ...d, params: { ...d.params, ...at } }, { cause: e });
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type ChronoFormatId, type ChronoImport, type ChronoParserOptions, type SessionCandidate } from './result.ts';
|
|
2
|
+
/** A column number counted from 1, or the header text of the column. */
|
|
3
|
+
export type Column = number | string;
|
|
4
|
+
/**
|
|
5
|
+
* Which column holds what. `velocity` is required. `string` labels the string of a shot,
|
|
6
|
+
* `velocityUnit` names the velocity unit per row, `coldBore` and `excluded` flag a shot.
|
|
7
|
+
*/
|
|
8
|
+
export interface ColumnMap {
|
|
9
|
+
velocity: Column;
|
|
10
|
+
string?: Column;
|
|
11
|
+
velocityUnit?: Column;
|
|
12
|
+
coldBore?: Column;
|
|
13
|
+
excluded?: Column;
|
|
14
|
+
}
|
|
15
|
+
/** Cell separator of a delimited file: tab, `;`, `,`, or `none` for one cell per line. */
|
|
16
|
+
export type Delimiter = ',' | ';' | '\t' | 'none';
|
|
17
|
+
/**
|
|
18
|
+
* Options of `parseDelimited`; `columns` is required.
|
|
19
|
+
*/
|
|
20
|
+
export interface DelimitedOptions extends ChronoParserOptions {
|
|
21
|
+
columns: ColumnMap;
|
|
22
|
+
/** Cell separator; detected when absent. */
|
|
23
|
+
delimiter?: Delimiter | undefined;
|
|
24
|
+
/** File rows before the data, used when every mapped column is a number. */
|
|
25
|
+
skipRows?: number | undefined;
|
|
26
|
+
/** Device of the session; kind `other` without manufacturer name or model when absent. */
|
|
27
|
+
device?: SessionCandidate['device'] | undefined;
|
|
28
|
+
}
|
|
29
|
+
/** The cells of a line split at `d`; `none` keeps the trimmed line as one cell. */
|
|
30
|
+
export declare const splitCells: (line: string, d: Delimiter) => string[];
|
|
31
|
+
/** The first that separates cells in every non-empty line (outside quotes), else the first that does in any line, else one column. */
|
|
32
|
+
export declare function detectDelimiter(lines: string[]): Delimiter;
|
|
33
|
+
/**
|
|
34
|
+
* What the user can do about a detected comma that may cut a velocity, the `remedy` param of
|
|
35
|
+
* `commaMaySplit`, `commaMayCutVelocity` and `moreCellsThanHeaderComma`: quote the cell or use `;`
|
|
36
|
+
* (`quoteOrSemicolon`, a template), else name the delimiter (`nameDelimiter`).
|
|
37
|
+
*/
|
|
38
|
+
export type CommaRemedy = 'quoteOrSemicolon' | 'nameDelimiter';
|
|
39
|
+
/**
|
|
40
|
+
* Delimited text with a user column mapping: one row per shot in firing order. Never detected.
|
|
41
|
+
*/
|
|
42
|
+
export declare function parseDelimited(text: string, options: DelimitedOptions): ChronoImport;
|
|
43
|
+
/** With `options.columns` as `format`; `detected`: the delimiter in `options` was detected, not named by the user. */
|
|
44
|
+
export declare function parseDelimitedRows(format: ChronoFormatId, text: string, options: DelimitedOptions, detected?: boolean): ChronoImport;
|