bmad-plus 0.24.0 → 0.25.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/CHANGELOG.md +9 -0
- package/README.md +26 -15
- package/SECURITY.md +2 -2
- package/package.json +2 -2
- package/readme-international/README.de.md +26 -15
- package/readme-international/README.es.md +26 -15
- package/readme-international/README.fr.md +26 -15
- package/src/bmad-plus/data/role-triggers.yaml +26 -0
- package/src/bmad-plus/module.yaml +34 -0
- package/src/bmad-plus/packs/pack-dev-studio/categories/analysis/tech-writer-agent.md +7 -0
- package/src/bmad-plus/packs/pack-ghostwriter/SKILL.md +23 -0
- package/src/bmad-plus/packs/pack-ghostwriter/bmad-skill-manifest.yaml +13 -0
- package/src/bmad-plus/packs/pack-ghostwriter/ghostwriter.md +28 -0
- package/src/bmad-plus/packs/pack-ghostwriter/intake.yaml +73 -0
- package/src/bmad-plus/packs/pack-ghostwriter/languages/en.md +11 -0
- package/src/bmad-plus/packs/pack-ghostwriter/languages/fr-FR.md +15 -0
- package/src/bmad-plus/packs/pack-ghostwriter/languages/glossary.md +14 -0
- package/src/bmad-plus/packs/pack-ghostwriter/languages/pt-BR.md +11 -0
- package/src/bmad-plus/packs/pack-ghostwriter/profiles/README.md +22 -0
- package/src/bmad-plus/packs/pack-ghostwriter/profiles/author-note-fr.yaml +20 -0
- package/src/bmad-plus/packs/pack-ghostwriter/profiles/character-dialogue-fr.yaml +20 -0
- package/src/bmad-plus/packs/pack-ghostwriter/profiles/customer-reply-pt-br.yaml +20 -0
- package/src/bmad-plus/packs/pack-ghostwriter/profiles/service-report-en.yaml +20 -0
- package/src/bmad-plus/packs/pack-ghostwriter/references/evaluation.md +5 -0
- package/src/bmad-plus/packs/pack-ghostwriter/references/provenance.md +32 -0
- package/src/bmad-plus/packs/pack-ghostwriter/schemas/config.schema.json +82 -0
- package/src/bmad-plus/packs/pack-ghostwriter/schemas/review-result.schema.json +212 -0
- package/src/bmad-plus/packs/pack-ghostwriter/schemas/run-manifest.schema.json +197 -0
- package/src/bmad-plus/packs/pack-ghostwriter/schemas/voice-profile.schema.json +55 -0
- package/src/bmad-plus/packs/pack-ghostwriter/shared/catalog.json +14 -0
- package/src/bmad-plus/packs/pack-ghostwriter/shared/editorial-contract.md +38 -0
- package/src/bmad-plus/packs/pack-ghostwriter/shared/execution.md +44 -0
- package/src/bmad-plus/packs/pack-ghostwriter/tools/inspect-typography.cjs +273 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workflows/agent-output-review.md +25 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workflows/draft.md +26 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workflows/humanize.md +52 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workflows/improve.md +26 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workflows/localize.md +24 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workflows/voice-profile.md +24 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/README.md +57 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/brief.md +23 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/check.cjs +128 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/jury.json +129 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/opening.md +1 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/select.cjs +54 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/freytag-pyramid/README.md +32 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/freytag-pyramid/specialist.md +12 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/hero-journey/README.md +44 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/hero-journey/specialist.md +17 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/in-medias-res/README.md +15 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/in-medias-res/specialist.md +15 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/kishotenketsu/README.md +26 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/kishotenketsu/specialist.md +10 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/narrative-arc/README.md +24 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/narrative-arc/specialist.md +9 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/snowflake-method/README.md +15 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/snowflake-method/specialist.md +15 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/story-circle/README.md +28 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/story-circle/specialist.md +10 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/story-spine/README.md +28 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/story-spine/specialist.md +9 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/README.md +39 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/briefs/objection.md +27 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/briefs/proposal.md +15 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/example.md +11 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/objections.json +103 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/proposals.json +79 -0
- package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/specialist.md +9 -0
- package/src/bmad-plus/skills/ghostwriter-edit/SKILL.md +16 -0
- package/src/bmad-plus/skills/ghostwriter-humanize/SKILL.md +16 -0
- package/src/bmad-plus/skills/ghostwriter-localize/SKILL.md +16 -0
- package/src/bmad-plus/skills/ghostwriter-verify/SKILL.md +16 -0
- package/src/bmad-plus/skills/ghostwriter-voice/SKILL.md +16 -0
- package/src/bmad-plus/skills/ghostwriter-write/SKILL.md +16 -0
- package/tools/cli/bmad-plus-cli.js +1 -0
- package/tools/cli/commands/ghostwriter.js +76 -0
- package/tools/cli/commands/install.js +4 -0
- package/tools/cli/lib/ghostwriter-fidelity.js +352 -0
- package/tools/cli/lib/ghostwriter-manifest.js +238 -0
- package/tools/cli/lib/ghostwriter-nexus.js +542 -0
- package/tools/cli/lib/ghostwriter-project.js +304 -0
- package/tools/cli/lib/ghostwriter-quantities.js +239 -0
- package/tools/cli/lib/ghostwriter-structured.js +154 -0
- package/tools/cli/lib/ghostwriter.js +263 -0
- package/tools/cli/lib/nexus-process.js +44 -1
- package/tools/cli/lib/nexus.js +18 -0
- package/tools/cli/lib/packs.js +141 -6
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const crypto = require('node:crypto');
|
|
6
|
+
const yaml = require('js-yaml');
|
|
7
|
+
const { safeTarget } = require('../../build/generate-adapters');
|
|
8
|
+
|
|
9
|
+
const BASE = '.bmad-plus/ghostwriter';
|
|
10
|
+
const PACK = '.agents/skills/pack-ghostwriter';
|
|
11
|
+
const CONFIG = BASE + '/config.yaml';
|
|
12
|
+
const MAX_FILE = 512 * 1024;
|
|
13
|
+
const MAX_CONTEXT = 2 * 1024 * 1024;
|
|
14
|
+
const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
|
|
15
|
+
const digest = (value) => hash(JSON.stringify(value));
|
|
16
|
+
|
|
17
|
+
function identifier(value) {
|
|
18
|
+
if (typeof value !== 'string' || !/^[a-z][a-z0-9-]{0,62}$/.test(value)) {
|
|
19
|
+
throw new Error('Expected a lowercase identifier of at most 63 characters.');
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function textFile(root, file, limit = MAX_FILE) {
|
|
25
|
+
const target = safeTarget(root, file);
|
|
26
|
+
const stat = fs.lstatSync(target);
|
|
27
|
+
if (!stat.isFile() || stat.size > limit)
|
|
28
|
+
throw new Error('File exceeds the allowed scope or size: ' + file);
|
|
29
|
+
const bytes = fs.readFileSync(target);
|
|
30
|
+
const content = bytes.toString('utf8');
|
|
31
|
+
if (bytes.length > limit || bytes.includes(0) || !Buffer.from(content).equals(bytes)) {
|
|
32
|
+
throw new Error('Expected bounded UTF-8 text: ' + file);
|
|
33
|
+
}
|
|
34
|
+
return { path: file, sha256: hash(bytes), content, bytes: bytes.length };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function projectArtifact(root, file) {
|
|
38
|
+
if (
|
|
39
|
+
typeof file !== 'string' ||
|
|
40
|
+
file
|
|
41
|
+
.split('/')
|
|
42
|
+
.some((segment) =>
|
|
43
|
+
/^(?:\.git|\.ssh|node_modules|\.bmad-plus|\.env(?:\..*)?|\.credentials|credentials)$/i.test(
|
|
44
|
+
segment
|
|
45
|
+
)
|
|
46
|
+
)
|
|
47
|
+
) {
|
|
48
|
+
throw new Error('Select a project content file outside private and control directories.');
|
|
49
|
+
}
|
|
50
|
+
return textFile(root, file);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function present(root, file) {
|
|
54
|
+
return fs.existsSync(safeTarget(root, file));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function writeOnce(root, file, value) {
|
|
58
|
+
const target = safeTarget(root, file);
|
|
59
|
+
fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
60
|
+
const temp = target + '.' + crypto.randomUUID() + '.tmp';
|
|
61
|
+
try {
|
|
62
|
+
fs.writeFileSync(temp, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
63
|
+
// Publish a complete immutable record only when the destination does not exist.
|
|
64
|
+
fs.linkSync(temp, target);
|
|
65
|
+
} finally {
|
|
66
|
+
fs.rmSync(temp, { force: true });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function selection(value, allowed, label) {
|
|
71
|
+
if (!allowed.includes(value)) throw new Error('Unsupported ' + label + ': ' + value);
|
|
72
|
+
return value;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function strings(value, label) {
|
|
76
|
+
if (
|
|
77
|
+
!Array.isArray(value) ||
|
|
78
|
+
value.some((v) => typeof v !== 'string' || !v.trim()) ||
|
|
79
|
+
new Set(value).size !== value.length ||
|
|
80
|
+
value.length > 128
|
|
81
|
+
) {
|
|
82
|
+
throw new Error('Expected a bounded list of distinct strings for ' + label);
|
|
83
|
+
}
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function object(value, name) {
|
|
88
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
89
|
+
throw new Error('Expected an object for ' + name);
|
|
90
|
+
return value;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function keys(value, names, name) {
|
|
94
|
+
object(value, name);
|
|
95
|
+
const unknown = Object.keys(value).filter((key) => !names.includes(key));
|
|
96
|
+
if (unknown.length) throw new Error('Unknown ' + name + ' field: ' + unknown.join(', '));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function integer(value, min, max, label) {
|
|
100
|
+
if (!Number.isSafeInteger(value) || value < min || value > max)
|
|
101
|
+
throw new Error('Invalid ' + label);
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function locale(value) {
|
|
106
|
+
if (typeof value !== 'string' || !value.trim()) throw new Error('Expected a locale.');
|
|
107
|
+
return Intl.getCanonicalLocales(value)[0];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function loadConfig(root) {
|
|
111
|
+
const resource = present(root, CONFIG) ? textFile(root, CONFIG) : null;
|
|
112
|
+
const config = resource ? yaml.load(resource.content) : { schema_version: 1 };
|
|
113
|
+
keys(
|
|
114
|
+
config,
|
|
115
|
+
[
|
|
116
|
+
'schema_version',
|
|
117
|
+
'enabled',
|
|
118
|
+
'mode',
|
|
119
|
+
'default_locale',
|
|
120
|
+
'voice_profile',
|
|
121
|
+
'content_types',
|
|
122
|
+
'review_policy',
|
|
123
|
+
'scope',
|
|
124
|
+
'verification',
|
|
125
|
+
'limits',
|
|
126
|
+
'output',
|
|
127
|
+
],
|
|
128
|
+
'configuration'
|
|
129
|
+
);
|
|
130
|
+
if (config.schema_version !== 1)
|
|
131
|
+
throw new Error('Unsupported Ghostwriter configuration version.');
|
|
132
|
+
if (config.enabled !== undefined && typeof config.enabled !== 'boolean')
|
|
133
|
+
throw new Error('enabled must be boolean.');
|
|
134
|
+
if (config.enabled === false) throw new Error('Ghostwriter has been disabled for this project.');
|
|
135
|
+
const verification = config.verification ?? {};
|
|
136
|
+
keys(verification, ['facts', 'reviewer_context', 'semantic_review', 'fidelity'], 'verification');
|
|
137
|
+
selection(verification.fidelity ?? 'required', ['required'], 'fidelity policy');
|
|
138
|
+
selection(verification.semantic_review ?? 'required', ['required'], 'semantic review policy');
|
|
139
|
+
selection(verification.reviewer_context ?? 'separate', ['separate'], 'reviewer policy');
|
|
140
|
+
selection(
|
|
141
|
+
config.review_policy ?? 'required_for_selected_deliverables',
|
|
142
|
+
['required_for_selected_deliverables'],
|
|
143
|
+
'review policy'
|
|
144
|
+
);
|
|
145
|
+
const output = config.output ?? {};
|
|
146
|
+
keys(output, ['text', 'report'], 'output');
|
|
147
|
+
selection(output.text ?? 'final-only', ['final-only'], 'text output');
|
|
148
|
+
selection(output.report ?? 'separate', ['separate'], 'report output');
|
|
149
|
+
const limits = config.limits ?? {};
|
|
150
|
+
keys(limits, ['max_revision_attempts', 'timeout_ms', 'max_output_bytes'], 'limits');
|
|
151
|
+
const scope = config.scope ?? {};
|
|
152
|
+
keys(
|
|
153
|
+
scope,
|
|
154
|
+
['include_paths', 'exclude_paths', 'editable_fields', 'protected_spans', 'protected_terms'],
|
|
155
|
+
'scope'
|
|
156
|
+
);
|
|
157
|
+
const include = strings(scope.include_paths ?? [], 'include_paths');
|
|
158
|
+
const exclude = strings(scope.exclude_paths ?? [], 'exclude_paths');
|
|
159
|
+
for (const entry of [...include, ...exclude]) {
|
|
160
|
+
if (/[?*]/.test(entry))
|
|
161
|
+
throw new Error('Select paths or directory prefixes, without wildcards.');
|
|
162
|
+
const relative = entry.replace(/\/$/, '');
|
|
163
|
+
if (
|
|
164
|
+
/[\\:\0]/.test(relative) ||
|
|
165
|
+
relative.split('/').some((part) => !part || part === '.' || part === '..')
|
|
166
|
+
) {
|
|
167
|
+
throw new Error('Scope paths must be project relative.');
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
config_path: resource?.path ?? null,
|
|
172
|
+
config_sha256: resource?.sha256 ?? null,
|
|
173
|
+
mode: selection(config.mode ?? 'manual', ['manual', 'host_policy', 'orchestrated'], 'mode'),
|
|
174
|
+
default_locale: locale(config.default_locale ?? 'fr-FR'),
|
|
175
|
+
voice_profile: config.voice_profile === undefined ? null : profileId(config.voice_profile),
|
|
176
|
+
content_types: strings(config.content_types ?? [], 'content_types'),
|
|
177
|
+
scope: { include_paths: include, exclude_paths: exclude },
|
|
178
|
+
editable_fields: strings(scope.editable_fields ?? [], 'editable_fields'),
|
|
179
|
+
protected_terms: strings(scope.protected_terms ?? [], 'protected_terms'),
|
|
180
|
+
protected_spans: strings(scope.protected_spans ?? [], 'protected_spans'),
|
|
181
|
+
facts: selection(
|
|
182
|
+
verification.facts ?? 'not_run',
|
|
183
|
+
['not_run', 'provided-sources'],
|
|
184
|
+
'fact policy'
|
|
185
|
+
),
|
|
186
|
+
limits: {
|
|
187
|
+
max_revision_attempts: integer(
|
|
188
|
+
limits.max_revision_attempts ?? 2,
|
|
189
|
+
1,
|
|
190
|
+
5,
|
|
191
|
+
'revision attempt limit'
|
|
192
|
+
),
|
|
193
|
+
timeout_ms: integer(limits.timeout_ms ?? 300000, 1000, 600000, 'timeout'),
|
|
194
|
+
max_output_bytes: integer(limits.max_output_bytes ?? 131072, 1024, MAX_FILE, 'output limit'),
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function profileId(value) {
|
|
200
|
+
if (typeof value !== 'string') throw new Error('Expected a voice profile id.');
|
|
201
|
+
const relative = /^profiles\/([a-z][a-z0-9-]{0,62})\.yaml$/.exec(value);
|
|
202
|
+
return identifier(relative ? relative[1] : value);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function voice(root, name) {
|
|
206
|
+
if (name === null || name === undefined || name === 'preserve-existing') {
|
|
207
|
+
const builtin = {
|
|
208
|
+
id: 'preserve-existing',
|
|
209
|
+
version: 1,
|
|
210
|
+
kind: 'policy',
|
|
211
|
+
policy: 'Preserve the voice of the input.',
|
|
212
|
+
};
|
|
213
|
+
return {
|
|
214
|
+
id: builtin.id,
|
|
215
|
+
version: 1,
|
|
216
|
+
path: null,
|
|
217
|
+
sha256: digest(builtin),
|
|
218
|
+
samples: [],
|
|
219
|
+
terms: [],
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
identifier(name);
|
|
223
|
+
const userPath = BASE + '/profiles/' + name + '.yaml';
|
|
224
|
+
const file = textFile(
|
|
225
|
+
root,
|
|
226
|
+
present(root, userPath) ? userPath : PACK + '/profiles/' + name + '.yaml'
|
|
227
|
+
);
|
|
228
|
+
const profile = object(yaml.load(file.content), 'voice profile');
|
|
229
|
+
if (profile.schema_version !== 1 || profile.id !== name)
|
|
230
|
+
throw new Error('Voice profile identity or schema mismatch.');
|
|
231
|
+
integer(profile.version, 1, Number.MAX_SAFE_INTEGER, 'voice profile version');
|
|
232
|
+
selection(profile.kind, ['author', 'brand'], 'voice kind');
|
|
233
|
+
selection(profile.status, ['draft', 'approved'], 'voice status');
|
|
234
|
+
locale(profile.locale);
|
|
235
|
+
if (profile.channels !== undefined) strings(profile.channels, 'profile channels');
|
|
236
|
+
if (profile.unresolved_questions !== undefined)
|
|
237
|
+
strings(profile.unresolved_questions, 'unresolved questions');
|
|
238
|
+
if (profile.explicit_preferences !== undefined)
|
|
239
|
+
object(profile.explicit_preferences, 'explicit preferences');
|
|
240
|
+
for (const field of ['glossary', 'exceptions']) {
|
|
241
|
+
if (profile[field] !== undefined && !Array.isArray(profile[field]))
|
|
242
|
+
throw new Error('Invalid profile ' + field);
|
|
243
|
+
}
|
|
244
|
+
const samples = profile.approved_samples ?? [];
|
|
245
|
+
if (!Array.isArray(samples) || samples.length > 32) throw new Error('Invalid voice samples.');
|
|
246
|
+
const records = samples.map((sample) => {
|
|
247
|
+
identifier(sample.id);
|
|
248
|
+
const current = projectArtifact(root, sample.path);
|
|
249
|
+
if (current.sha256 !== sample.sha256)
|
|
250
|
+
throw new Error('Voice sample hash mismatch: ' + sample.id);
|
|
251
|
+
return { id: sample.id, path: current.path, sha256: current.sha256 };
|
|
252
|
+
});
|
|
253
|
+
if (new Set(records.map((r) => r.id)).size !== records.length)
|
|
254
|
+
throw new Error('Duplicate voice sample id.');
|
|
255
|
+
if (!Array.isArray(profile.observations ?? [])) throw new Error('Invalid voice observations.');
|
|
256
|
+
for (const observation of profile.observations ?? []) {
|
|
257
|
+
if (
|
|
258
|
+
!observation ||
|
|
259
|
+
typeof observation !== 'object' ||
|
|
260
|
+
(observation.confidence !== undefined &&
|
|
261
|
+
!['string', 'number'].includes(typeof observation.confidence))
|
|
262
|
+
) {
|
|
263
|
+
throw new Error('Invalid voice observation metadata.');
|
|
264
|
+
}
|
|
265
|
+
const sample = records.find((r) => r.id === observation.sample_id);
|
|
266
|
+
if (
|
|
267
|
+
!sample ||
|
|
268
|
+
typeof observation.passage !== 'string' ||
|
|
269
|
+
!observation.passage.trim() ||
|
|
270
|
+
typeof observation.observation !== 'string' ||
|
|
271
|
+
!observation.observation.trim() ||
|
|
272
|
+
!textFile(root, sample.path).content.includes(observation.passage)
|
|
273
|
+
)
|
|
274
|
+
throw new Error('Unanchored voice observation.');
|
|
275
|
+
}
|
|
276
|
+
return {
|
|
277
|
+
id: name,
|
|
278
|
+
version: profile.version,
|
|
279
|
+
path: file.path,
|
|
280
|
+
sha256: file.sha256,
|
|
281
|
+
samples: records,
|
|
282
|
+
terms: strings(profile.protected_names ?? [], 'protected_names'),
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
module.exports = {
|
|
287
|
+
BASE,
|
|
288
|
+
PACK,
|
|
289
|
+
projectArtifact,
|
|
290
|
+
MAX_FILE,
|
|
291
|
+
MAX_CONTEXT,
|
|
292
|
+
hash,
|
|
293
|
+
digest,
|
|
294
|
+
identifier,
|
|
295
|
+
textFile,
|
|
296
|
+
present,
|
|
297
|
+
writeOnce,
|
|
298
|
+
selection,
|
|
299
|
+
strings,
|
|
300
|
+
object,
|
|
301
|
+
locale,
|
|
302
|
+
loadConfig,
|
|
303
|
+
voice,
|
|
304
|
+
};
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Amounts and account references may exceed Number.MAX_SAFE_INTEGER.
|
|
4
|
+
const conventions = {
|
|
5
|
+
'en-us': { group: ',', decimal: '.', dayFirst: false },
|
|
6
|
+
'en-gb': { group: ',', decimal: '.', dayFirst: true },
|
|
7
|
+
en: { group: ',', decimal: '.' },
|
|
8
|
+
'fr-fr': { group: ' ', decimal: ',', dayFirst: true },
|
|
9
|
+
fr: { group: ' ', decimal: ',', dayFirst: true },
|
|
10
|
+
'pt-br': { group: '.', decimal: ',', dayFirst: true },
|
|
11
|
+
pt: { group: '.', decimal: ',', dayFirst: true },
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const monthRows = [
|
|
15
|
+
'january jan janvier janv janeiro',
|
|
16
|
+
'february feb février févr fev fevereiro',
|
|
17
|
+
'march mar mars março',
|
|
18
|
+
'april apr avril avr abril abr',
|
|
19
|
+
'may mai maio',
|
|
20
|
+
'june jun juin junho',
|
|
21
|
+
'july jul juillet juil julho',
|
|
22
|
+
'august aug août agosto ago',
|
|
23
|
+
'september sept sep septembre setembro set',
|
|
24
|
+
'october oct octobre outubro out',
|
|
25
|
+
'november nov novembre novembro',
|
|
26
|
+
'december dec décembre déc dezembro dez',
|
|
27
|
+
];
|
|
28
|
+
const monthNumber = new Map(
|
|
29
|
+
monthRows.flatMap((row, i) => row.split(' ').map((word) => [word, i + 1]))
|
|
30
|
+
);
|
|
31
|
+
const months = Array.from(monthNumber.keys())
|
|
32
|
+
.sort((a, b) => b.length - a.length)
|
|
33
|
+
.join('|');
|
|
34
|
+
const month = String.raw`(?:${months})\.?`;
|
|
35
|
+
const day = String.raw`\d{1,2}(?:st|nd|rd|th|er|º)?`;
|
|
36
|
+
const space = String.raw`[ \t\u00a0\u202f]`;
|
|
37
|
+
const gap = String.raw`${space}+(?:de${space}+)?`;
|
|
38
|
+
const namedDate = String.raw`(?<![\p{L}\d])(?:${day}${gap}${month}(?:${gap}\d{4})?|${month}${space}+(?:\d{4}|${day}(?:,?${space}+\d{4})?))(?![\p{L}\d])`;
|
|
39
|
+
const numericDate = String.raw`(?<!\d)(?:\d{4}[-/]\d{1,2}[-/]\d{1,2}|\d{1,2}[-/]\d{1,2}[-/](?:\d{4}|\d{2}))(?!\d)`;
|
|
40
|
+
const number = String.raw`[+\-−±]?(?:\d+(?:(?:[.,]\d+)|(?:[ \u00a0\u202f]\d{3}(?!\d)))*|[.,]\d+)(?:[eE][+\-]?\d+)?`;
|
|
41
|
+
const tokens = new RegExp(`(?<date>${numericDate}|${namedDate})|(?<number>${number})`, 'giu');
|
|
42
|
+
|
|
43
|
+
function calendarDate(year, monthValue, dayValue) {
|
|
44
|
+
const m = Number(monthValue);
|
|
45
|
+
const d = Number(dayValue);
|
|
46
|
+
const leap = !year || (+year % 4 === 0 && (+year % 100 !== 0 || +year % 400 === 0));
|
|
47
|
+
const lengths = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
48
|
+
if (m < 1 || m > 12 || d < 1 || d > lengths[m - 1]) throw new Error('Invalid calendar date.');
|
|
49
|
+
return [year || '--', String(m).padStart(2, '0'), String(d).padStart(2, '0')].join('-');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function dateValue(raw, locale) {
|
|
53
|
+
if (!locale) return raw;
|
|
54
|
+
const segments = raw.match(/\d+/g);
|
|
55
|
+
const name = raw
|
|
56
|
+
.toLowerCase()
|
|
57
|
+
.match(/\p{L}+/gu)
|
|
58
|
+
?.find((word) => monthNumber.has(word));
|
|
59
|
+
if (name) {
|
|
60
|
+
const m = monthNumber.get(name);
|
|
61
|
+
const year = segments.find((part) => part.length === 4);
|
|
62
|
+
const d = segments.find((part) => part.length < 3);
|
|
63
|
+
return d ? calendarDate(year, m, d) : `${year}-${String(m).padStart(2, '0')}`;
|
|
64
|
+
}
|
|
65
|
+
const [first, second, last] = segments;
|
|
66
|
+
if (first.length === 4) return calendarDate(first, second, last);
|
|
67
|
+
// Neither a century nor the region behind bare "en" can be reconstructed.
|
|
68
|
+
if (last.length !== 4 || locale.dayFirst === undefined) return raw;
|
|
69
|
+
return locale.dayFirst ? calendarDate(last, second, first) : calendarDate(last, first, second);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function decimalValue(raw, locale) {
|
|
73
|
+
if (!locale) return raw;
|
|
74
|
+
const [, sign, body, exponent] = /^([+\-−±]?)([\d., \u00a0\u202f]+)([eE][+-]?\d+)?$/.exec(raw);
|
|
75
|
+
const parts = body.replace(/[\u00a0\u202f]/g, ' ').split(locale.decimal);
|
|
76
|
+
const groups = (parts[0] || '0').split(locale.group);
|
|
77
|
+
const validGrouping =
|
|
78
|
+
groups.length === 1 || (groups[0].length <= 3 && groups.slice(1).every((g) => g.length === 3));
|
|
79
|
+
if (
|
|
80
|
+
parts.length > 2 ||
|
|
81
|
+
!groups.every((g) => /^\d+$/.test(g)) ||
|
|
82
|
+
!validGrouping ||
|
|
83
|
+
(parts.length === 2 && !/^\d+$/.test(parts[1]))
|
|
84
|
+
) {
|
|
85
|
+
// A dotted version, address or unexpected numeric convention keeps its exact spelling.
|
|
86
|
+
return `literal:${raw}`;
|
|
87
|
+
}
|
|
88
|
+
const fraction = parts[1]?.replace(/0+$/, '');
|
|
89
|
+
return (
|
|
90
|
+
sign.replace('−', '-') + groups.join('') + (fraction ? `.${fraction}` : '') + (exponent || '')
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const currency = String.raw`(?:US\$|CA\$|A\$|R\$|[$€£¥₹₽₩₺₫₴₦₱₡]|(?:USD|EUR|GBP|BRL|CAD|AUD|JPY|CHF|CNY|INR|MXN|NZD|SEK|NOK|DKK|PLN|ZAR|KRW)(?!\p{L}))`;
|
|
95
|
+
const prefix = new RegExp(String.raw`(?<!\p{L})([+\-−±]?)(${currency})${space}*$`, 'u');
|
|
96
|
+
const suffix = new RegExp(String.raw`^${space}*(${currency})`, 'u');
|
|
97
|
+
const unitRows = {
|
|
98
|
+
'%': ['%', 'percent', 'per cent', 'pour cent', 'por cento'],
|
|
99
|
+
'‰': ['‰'],
|
|
100
|
+
second: ['second', 'seconds', 'seconde', 'secondes', 'segundo', 'segundos'],
|
|
101
|
+
minute: ['minute', 'minutes', 'minuto', 'minutos'],
|
|
102
|
+
hour: ['hour', 'hours', 'heure', 'heures', 'hora', 'horas'],
|
|
103
|
+
day: ['day', 'days', 'jour', 'jours', 'dia', 'dias'],
|
|
104
|
+
week: ['week', 'weeks', 'semaine', 'semaines', 'semana', 'semanas'],
|
|
105
|
+
month: ['month', 'months', 'mois', 'mês', 'meses'],
|
|
106
|
+
year: ['year', 'years', 'an', 'ans', 'année', 'années', 'ano', 'anos'],
|
|
107
|
+
gram: ['gram', 'grams', 'gramme', 'grammes', 'grama', 'gramas'],
|
|
108
|
+
kilogram: ['kilogram', 'kilograms', 'kilogramme', 'kilogrammes', 'quilograma', 'quilogramas'],
|
|
109
|
+
milligram: ['milligram', 'milligrams', 'milligramme', 'milligrammes', 'miligrama', 'miligramas'],
|
|
110
|
+
metre: ['meter', 'meters', 'metre', 'metres', 'mètre', 'mètres', 'metro', 'metros'],
|
|
111
|
+
kilometre: [
|
|
112
|
+
'kilometer',
|
|
113
|
+
'kilometers',
|
|
114
|
+
'kilometre',
|
|
115
|
+
'kilometres',
|
|
116
|
+
'kilomètre',
|
|
117
|
+
'kilomètres',
|
|
118
|
+
'quilômetro',
|
|
119
|
+
'quilômetros',
|
|
120
|
+
],
|
|
121
|
+
mile: ['mile', 'miles', 'milha', 'milhas'],
|
|
122
|
+
litre: ['liter', 'liters', 'litre', 'litres', 'litro', 'litros'],
|
|
123
|
+
euro: ['euro', 'euros'],
|
|
124
|
+
dollar: ['dollar', 'dollars', 'dólar', 'dólares'],
|
|
125
|
+
pound: ['pound', 'pounds', 'livre', 'livres', 'libra', 'libras'],
|
|
126
|
+
};
|
|
127
|
+
const unitNames = new Map(
|
|
128
|
+
Object.entries(unitRows).flatMap(([key, names]) => names.map((n) => [n, key]))
|
|
129
|
+
);
|
|
130
|
+
const namedUnit = new RegExp(
|
|
131
|
+
String.raw`^${space}*(${[...unitNames.keys()].sort((a, b) => b.length - a.length).join('|')})(?!\p{L})`,
|
|
132
|
+
'iu'
|
|
133
|
+
);
|
|
134
|
+
const symbolUnit = new RegExp(
|
|
135
|
+
String.raw`^${space}*((?:°[CF]|[μµnumcdkMGT]?(?:g|m|s|L|l|W|V|A|Pa|Hz|J)|(?:[kKMGTPE]i?)?[bB](?:/s|ps)?|h|min|bps|rpm|kcal|mol)(?:[²³])?(?:\/[\p{L}]+[²³]?)?)(?![\p{L}\d])`,
|
|
136
|
+
'u'
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
// French uses the long scale. Only a known language licenses converting a
|
|
140
|
+
// magnitude word to a power of ten (one French billion is one English trillion).
|
|
141
|
+
const magnitudes = {
|
|
142
|
+
fr: {
|
|
143
|
+
mille: 3,
|
|
144
|
+
millier: 3,
|
|
145
|
+
milliers: 3,
|
|
146
|
+
million: 6,
|
|
147
|
+
millions: 6,
|
|
148
|
+
milliard: 9,
|
|
149
|
+
milliards: 9,
|
|
150
|
+
billion: 12,
|
|
151
|
+
billions: 12,
|
|
152
|
+
billiard: 15,
|
|
153
|
+
billiards: 15,
|
|
154
|
+
trillion: 18,
|
|
155
|
+
trillions: 18,
|
|
156
|
+
},
|
|
157
|
+
en: {
|
|
158
|
+
thousand: 3,
|
|
159
|
+
thousands: 3,
|
|
160
|
+
million: 6,
|
|
161
|
+
millions: 6,
|
|
162
|
+
billion: 9,
|
|
163
|
+
billions: 9,
|
|
164
|
+
trillion: 12,
|
|
165
|
+
trillions: 12,
|
|
166
|
+
quadrillion: 15,
|
|
167
|
+
quadrillions: 15,
|
|
168
|
+
quintillion: 18,
|
|
169
|
+
quintillions: 18,
|
|
170
|
+
},
|
|
171
|
+
pt: { mil: 3, milhão: 6, milhões: 6, bilhão: 9, bilhões: 9, trilhão: 12, trilhões: 12 },
|
|
172
|
+
};
|
|
173
|
+
const magnitudeWords = [...new Set(Object.values(magnitudes).flatMap(Object.keys))].join('|');
|
|
174
|
+
const magnitudeToken = new RegExp(String.raw`(?<!\p{L})(?:${magnitudeWords})(?!\p{L})`, 'giu');
|
|
175
|
+
const magnitudeSuffix = new RegExp(String.raw`^${space}*(${magnitudeWords})(?!\p{L})`, 'iu');
|
|
176
|
+
const scaleConnector = /^\s+(?:de\s+|d['’])/iu;
|
|
177
|
+
|
|
178
|
+
function quantities(text, localeName) {
|
|
179
|
+
if (typeof text !== 'string') throw new TypeError('Expected prose text.');
|
|
180
|
+
if (/(?:(?![0-9])\p{Nd})/u.test(text)) {
|
|
181
|
+
throw new Error('This numerical script requires a separate comparison.');
|
|
182
|
+
}
|
|
183
|
+
const localeKey = localeName?.toLowerCase();
|
|
184
|
+
if (localeKey && !Object.hasOwn(conventions, localeKey)) {
|
|
185
|
+
throw new Error('Unsupported locale for numerical comparison.');
|
|
186
|
+
}
|
|
187
|
+
const locale = conventions[localeKey];
|
|
188
|
+
const numbers = [];
|
|
189
|
+
const dates = [];
|
|
190
|
+
const units = [];
|
|
191
|
+
const digitScales = new Set();
|
|
192
|
+
for (const hit of text.matchAll(tokens)) {
|
|
193
|
+
if (hit.groups.date) {
|
|
194
|
+
dates.push(dateValue(hit[0], locale));
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
const after = text.slice(hit.index + hit[0].length, hit.index + hit[0].length + 72);
|
|
198
|
+
const before = text.slice(Math.max(0, hit.index - 36), hit.index);
|
|
199
|
+
const leading = prefix.exec(before);
|
|
200
|
+
const trailing = suffix.exec(after);
|
|
201
|
+
const left = leading ? before.slice(0, leading.index) : before;
|
|
202
|
+
const operator = /([<>≤≥≈≠]=?)\s*$/.exec(left)?.[1];
|
|
203
|
+
let unitText = trailing ? after.slice(trailing[0].length) : after;
|
|
204
|
+
const scale = magnitudeSuffix.exec(unitText);
|
|
205
|
+
let scaledCurrency;
|
|
206
|
+
if (scale) {
|
|
207
|
+
const offset = hit.index + hit[0].length + (trailing?.[0].length || 0);
|
|
208
|
+
digitScales.add(offset + scale[0].length - scale[1].length);
|
|
209
|
+
const word = scale[1].toLowerCase();
|
|
210
|
+
const exponent = magnitudes[localeKey?.split('-')[0]]?.[word];
|
|
211
|
+
units.push(`${numbers.length}:scale:${exponent ?? word}`);
|
|
212
|
+
unitText = unitText.slice(scale[0].length).replace(scaleConnector, '');
|
|
213
|
+
scaledCurrency = suffix.exec(unitText);
|
|
214
|
+
if (scaledCurrency) unitText = unitText.slice(scaledCurrency[0].length);
|
|
215
|
+
}
|
|
216
|
+
const longName = namedUnit.exec(unitText);
|
|
217
|
+
const symbol = symbolUnit.exec(unitText);
|
|
218
|
+
const attached = /^[\p{L}°µμ]+/u.exec(unitText);
|
|
219
|
+
const unit = longName ? unitNames.get(longName[1].toLowerCase()) : symbol?.[1] || attached?.[0];
|
|
220
|
+
const index = numbers.length;
|
|
221
|
+
numbers.push((leading?.[1] || '').replace('−', '-') + decimalValue(hit[0], locale));
|
|
222
|
+
if (leading) units.push(`${index}:${leading[2]}`);
|
|
223
|
+
if (trailing) units.push(`${index}:${trailing[1]}`);
|
|
224
|
+
if (scaledCurrency) units.push(`${index}:${scaledCurrency[1]}`);
|
|
225
|
+
if (unit) units.push(`${index}:${unit}`);
|
|
226
|
+
if (operator) units.push(`${index}:${operator}`);
|
|
227
|
+
if ((leading || trailing || scaledCurrency) && /\(\s*$/.test(left) && /^\s*\)/.test(unitText)) {
|
|
228
|
+
units.push(`${index}:accounting-parentheses`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
for (const occurrence of text.matchAll(magnitudeToken)) {
|
|
232
|
+
if (!digitScales.has(occurrence.index)) {
|
|
233
|
+
throw new Error('A magnitude without a numeric coefficient requires separate comparison.');
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return { numbers, dates, units };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
module.exports = { quantities };
|