procurement-writing-engine 0.0.0-stage → 0.1.0-alpha.6
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/.vale.ini +5 -0
- package/CHANGELOG.md +45 -0
- package/CODE_OF_CONDUCT.md +5 -0
- package/CONTRIBUTING.md +15 -0
- package/LICENSE +21 -0
- package/README.md +142 -2
- package/SECURITY.md +14 -0
- package/THIRD_PARTY.md +17 -0
- package/assets/logo.svg +7 -0
- package/assets/social-preview.png +0 -0
- package/assets/wordmark.svg +8 -0
- package/docs/ALPHA2_ACCEPTANCE.md +11 -0
- package/docs/ALPHA3_ACCEPTANCE.md +13 -0
- package/docs/API.md +24 -0
- package/docs/ARCHITECTURE.md +30 -0
- package/docs/LOCAL_VERIFICATION.md +26 -0
- package/docs/PROMOTION.md +21 -0
- package/docs/README.fa.md +29 -0
- package/docs/RELEASE.md +42 -0
- package/docs/RELEASE_NOTES.md +3 -0
- package/docs/UPSTREAM_AUDIT.md +55 -0
- package/examples/review.mjs +16 -0
- package/package.json +102 -4
- package/src/adapters/formal-persian.mjs +7 -0
- package/src/adapters/harper.mjs +45 -0
- package/src/adapters/orthography-diff.mjs +66 -0
- package/src/adapters/procurement-ranking.mjs +31 -0
- package/src/adapters/reports.mjs +56 -0
- package/src/adapters/textlint.mjs +31 -0
- package/src/adapters/virastar.mjs +27 -0
- package/src/engine.mjs +108 -0
- package/src/index.d.mts +30 -0
- package/src/index.mjs +6 -0
- package/src/node/index.d.mts +4 -0
- package/src/node/index.mjs +58 -0
- package/src/policy.mjs +54 -0
- package/src/regions.mjs +84 -0
- package/styles/Procurement/DeliveryClarity.yml +6 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {binaryInlined} from 'harper.js/binaryInlined';
|
|
2
|
+
import {createEngine,createHarper,createVirastar,createTextlint,procurementPolicyRules} from '../src/index.mjs';
|
|
3
|
+
// Synthetic text only; production region classification must be supplied by the authorized host.
|
|
4
|
+
const prefix='Please send teh quotation for ', part='Rosemount 3051 — 3 PCS', suffix=' as soon as possible.';
|
|
5
|
+
const text=prefix+part+suffix;
|
|
6
|
+
const harper=await createHarper({binary:binaryInlined,worker:false});
|
|
7
|
+
try {
|
|
8
|
+
const engine=createEngine([harper.provider,await createVirastar(),await createTextlint(procurementPolicyRules)]);
|
|
9
|
+
const report=await engine.analyze({text,snapshotId:'example:1',regions:[
|
|
10
|
+
{start:0,end:prefix.length,kind:'prose',language:'en'},
|
|
11
|
+
{start:prefix.length,end:prefix.length+part.length,kind:'protected'},
|
|
12
|
+
{start:prefix.length+part.length,end:text.length,kind:'prose',language:'en'}
|
|
13
|
+
]});
|
|
14
|
+
// Console output is confined to this synthetic example; the library has no logging.
|
|
15
|
+
console.log(JSON.stringify(report,null,2));
|
|
16
|
+
} finally {await harper.dispose();}
|
package/package.json
CHANGED
|
@@ -1,6 +1,104 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "procurement-writing-engine",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-alpha.6",
|
|
4
|
+
"description": "Composable English and Persian writing review for procurement and technical commercial prose. No LLM required.",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"engines": {
|
|
9
|
+
"node": ">=22.12.0"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./src/index.d.mts",
|
|
14
|
+
"import": "./src/index.mjs"
|
|
15
|
+
},
|
|
16
|
+
"./node": {
|
|
17
|
+
"types": "./src/node/index.d.mts",
|
|
18
|
+
"import": "./src/node/index.mjs"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"src",
|
|
23
|
+
"styles",
|
|
24
|
+
"examples",
|
|
25
|
+
"docs",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE",
|
|
28
|
+
"THIRD_PARTY.md",
|
|
29
|
+
"SECURITY.md",
|
|
30
|
+
".vale.ini",
|
|
31
|
+
"assets/logo.svg",
|
|
32
|
+
"CHANGELOG.md",
|
|
33
|
+
"assets/social-preview.png",
|
|
34
|
+
"assets/wordmark.svg",
|
|
35
|
+
"CONTRIBUTING.md",
|
|
36
|
+
"CODE_OF_CONDUCT.md"
|
|
37
|
+
],
|
|
38
|
+
"scripts": {
|
|
39
|
+
"test": "node --test test/*.test.mjs",
|
|
40
|
+
"test:upstream": "node --test test/upstream.integration.mjs",
|
|
41
|
+
"check": "node scripts/check.mjs",
|
|
42
|
+
"test:services": "node --test test/services.integration.mjs",
|
|
43
|
+
"typecheck": "tsc --strict --target ES2022 --module NodeNext --moduleResolution NodeNext --noEmit test/types.mts",
|
|
44
|
+
"build:demo": "vite build demo --config demo/vite.config.mjs --base=./ --outDir=../dist/demo",
|
|
45
|
+
"demo": "vite demo --config demo/vite.config.mjs --host 127.0.0.1",
|
|
46
|
+
"test:browser": "node scripts/browser-smoke.mjs",
|
|
47
|
+
"verify": "npm run check && npm test && npm run typecheck && npm run test:upstream && npm run build:demo && npm run test:browser",
|
|
48
|
+
"release:check": "node scripts/release-check.mjs"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"harper.js": "3.2.0",
|
|
52
|
+
"virastar": "0.22.1",
|
|
53
|
+
"@textlint/kernel": "16.1.3",
|
|
54
|
+
"@textlint/textlint-plugin-text": "16.1.3"
|
|
55
|
+
},
|
|
56
|
+
"peerDependenciesMeta": {
|
|
57
|
+
"harper.js": {
|
|
58
|
+
"optional": true
|
|
59
|
+
},
|
|
60
|
+
"virastar": {
|
|
61
|
+
"optional": true
|
|
62
|
+
},
|
|
63
|
+
"@textlint/kernel": {
|
|
64
|
+
"optional": true
|
|
65
|
+
},
|
|
66
|
+
"@textlint/textlint-plugin-text": {
|
|
67
|
+
"optional": true
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
"repository": {
|
|
71
|
+
"type": "git",
|
|
72
|
+
"url": "git+https://github.com/FireXCore/procurement-writing-engine.git"
|
|
73
|
+
},
|
|
74
|
+
"homepage": "https://github.com/FireXCore/procurement-writing-engine#readme",
|
|
75
|
+
"bugs": {
|
|
76
|
+
"url": "https://github.com/FireXCore/procurement-writing-engine/issues"
|
|
77
|
+
},
|
|
78
|
+
"keywords": [
|
|
79
|
+
"procurement",
|
|
80
|
+
"technical-writing",
|
|
81
|
+
"grammar-checker",
|
|
82
|
+
"persian",
|
|
83
|
+
"english",
|
|
84
|
+
"rfq",
|
|
85
|
+
"erp",
|
|
86
|
+
"webassembly",
|
|
87
|
+
"offline",
|
|
88
|
+
"writing-assistant"
|
|
89
|
+
],
|
|
90
|
+
"devDependencies": {
|
|
91
|
+
"harper.js": "3.2.0",
|
|
92
|
+
"virastar": "0.22.1",
|
|
93
|
+
"@textlint/kernel": "16.1.3",
|
|
94
|
+
"@textlint/textlint-plugin-text": "16.1.3",
|
|
95
|
+
"typescript": "5.9.3",
|
|
96
|
+
"vite": "8.3.8",
|
|
97
|
+
"playwright-core": "1.58.2"
|
|
98
|
+
},
|
|
99
|
+
"publishConfig": {
|
|
100
|
+
"access": "public",
|
|
101
|
+
"tag": "alpha",
|
|
102
|
+
"registry": "https://registry.npmjs.org/"
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Local, deliberately narrow formal-writing policy. Not an upstream Virastar rule.
|
|
2
|
+
// Exact unmarked adverbs only; no blanket final-alef or diacritic normalization.
|
|
3
|
+
const formalAdverbs=new Set(['لطفا','حتما','قطعا','واقعا','تقریبا','فورا','قبلا','بعدا','موقتا','رسما','صرفا','مستقیما']);
|
|
4
|
+
export function formalPersianOrthography(text){
|
|
5
|
+
if(typeof text!=='string'||!text.isWellFormed())throw new TypeError('Invalid Persian text');
|
|
6
|
+
return text.replace(/[\p{L}\p{M}\p{N}\p{Cf}]+/gu,word=>formalAdverbs.has(word)?word+'\u064b':word);
|
|
7
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { validRange } from '../regions.mjs';
|
|
2
|
+
const category = kind => ['Spelling','Typo'].includes(kind) ? 'spelling' : ['Grammar','Agreement','WordOrder'].includes(kind) ? 'grammar' : 'style';
|
|
3
|
+
|
|
4
|
+
import { rankSpellingAlternatives } from './procurement-ranking.mjs';
|
|
5
|
+
|
|
6
|
+
export function harperAdapter(linter) {
|
|
7
|
+
if (!linter || typeof linter.organizedLints !== 'function') throw new TypeError('Harper linter required');
|
|
8
|
+
return Object.freeze({id:'harper',languages:['en'],async check(text) {
|
|
9
|
+
const rules = await linter.organizedLints(text,{language:'plaintext',dedup:true,isolateEnglish:false});
|
|
10
|
+
const output = [];
|
|
11
|
+
// WASM bindings are owned by this adapter and released even on malformed results.
|
|
12
|
+
for (const [rule,lints] of Object.entries(rules)) {
|
|
13
|
+
for (const lint of lints) {
|
|
14
|
+
let span, suggestions = [];
|
|
15
|
+
try {
|
|
16
|
+
span = lint.span(); const {start,end} = span;
|
|
17
|
+
if (!validRange(text,start,end) || text.slice(start,end) !== lint.get_problem_text()) continue;
|
|
18
|
+
const common = {rule,category:category(lint.lint_kind()),start,end,original:text.slice(start,end),message:lint.message()};
|
|
19
|
+
suggestions = lint.suggestions();
|
|
20
|
+
if (!suggestions.length) output.push(common);
|
|
21
|
+
const alternatives=[];
|
|
22
|
+
for (const s of suggestions) {
|
|
23
|
+
const kind = s.kind();
|
|
24
|
+
if (kind === 0 || kind === 1) alternatives.push({...common,replacement:s.get_replacement_text()});
|
|
25
|
+
else if (kind === 2) alternatives.push({...common,replacement:common.original+s.get_replacement_text()});
|
|
26
|
+
}
|
|
27
|
+
output.push(...(common.category==='spelling'?rankSpellingAlternatives(alternatives,text):alternatives));
|
|
28
|
+
} finally {
|
|
29
|
+
for (const s of suggestions) s.free?.();
|
|
30
|
+
span?.free?.(); lint.free?.();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return output;
|
|
35
|
+
}});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Explicit setup, never on page load. Host must bundle/self-host the WASM artifact.
|
|
39
|
+
export async function createHarper({binary, worker = true, dialect} = {}) {
|
|
40
|
+
if (!binary) throw new TypeError('Explicit local Harper binary required');
|
|
41
|
+
const sdk = await import('harper.js');
|
|
42
|
+
const linter = new (worker ? sdk.WorkerLinter : sdk.LocalLinter)({binary,dialect});
|
|
43
|
+
try { await linter.setup(); } catch (error) { await linter.dispose(); throw error; }
|
|
44
|
+
return {provider:harperAdapter(linter),dispose:() => linter.dispose()};
|
|
45
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { LIMITS, boundaries, validRange, validReplacement } from '../regions.mjs';
|
|
2
|
+
|
|
3
|
+
// Align exact unchanged words, not guessed linguistic rules. Bounded matrix.
|
|
4
|
+
const MAX_CELLS=1_000_000;
|
|
5
|
+
const words=text=>Array.from(text.matchAll(/\S+/gu),m=>({text:m[0],start:m.index,end:m.index+m[0].length}));
|
|
6
|
+
|
|
7
|
+
export function orthographyEdits(source,target){
|
|
8
|
+
if(typeof source!=='string'||typeof target!=='string'||!source.isWellFormed()||!target.isWellFormed()||
|
|
9
|
+
source.length>LIMITS.region||target.length>LIMITS.region*2)throw new Error('Invalid orthography input');
|
|
10
|
+
if(source===target)return [];
|
|
11
|
+
const a=words(source),b=words(target),stride=b.length+1,cells=(a.length+1)*stride;
|
|
12
|
+
if(cells>MAX_CELLS)throw new Error('Orthography alignment budget exceeded');
|
|
13
|
+
const matrix=new Uint16Array(cells);
|
|
14
|
+
for(let i=a.length-1;i>=0;i--)for(let j=b.length-1;j>=0;j--){
|
|
15
|
+
matrix[i*stride+j]=a[i].text===b[j].text?1+matrix[(i+1)*stride+j+1]:
|
|
16
|
+
Math.max(matrix[(i+1)*stride+j],matrix[i*stride+j+1]);
|
|
17
|
+
}
|
|
18
|
+
const edits=[],sourceBoundaries=boundaries(source),targetBoundaries=boundaries(target);
|
|
19
|
+
function add(start,end,bs,be){
|
|
20
|
+
const original=source.slice(start,end),replacement=target.slice(bs,be);
|
|
21
|
+
if(original===replacement)return;
|
|
22
|
+
if(!validRange(source,start,end,sourceBoundaries)||!validRange(target,bs,be,targetBoundaries)||
|
|
23
|
+
(start===end&&(start===0||start===source.length))||!validReplacement(original,replacement,'fa')||
|
|
24
|
+
edits.length>=LIMITS.providerFindings)throw new Error('Unsafe or excessive orthography edits');
|
|
25
|
+
edits.push({start,end,original,replacement});
|
|
26
|
+
}
|
|
27
|
+
function gap(start,end,bs,be){
|
|
28
|
+
const left=source.slice(start,end),right=target.slice(bs,be);
|
|
29
|
+
if(left===right)return;
|
|
30
|
+
const x=words(left),y=words(right);
|
|
31
|
+
// Equal word counts and identical separators permit individual word patches.
|
|
32
|
+
if(x.length&&x.length===y.length){
|
|
33
|
+
let prev=0,next=0,aligned=true;
|
|
34
|
+
for(let k=0;k<x.length;k++){
|
|
35
|
+
if(left.slice(prev,x[k].start)!==right.slice(next,y[k].start)){aligned=false;break;}
|
|
36
|
+
prev=x[k].end;next=y[k].end;
|
|
37
|
+
}
|
|
38
|
+
if(aligned&&left.slice(prev)===right.slice(next)){
|
|
39
|
+
for(let k=0;k<x.length;k++)add(start+x[k].start,start+x[k].end,bs+y[k].start,bs+y[k].end);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// Merged/split words stay together; exclude identical outer whitespace.
|
|
44
|
+
const prefix=left.match(/^\s+/u)?.[0]??'',otherPrefix=right.match(/^\s+/u)?.[0]??'';
|
|
45
|
+
if(prefix===otherPrefix){start+=prefix.length;bs+=prefix.length;}
|
|
46
|
+
const suffix=source.slice(start,end).match(/\s+$/u)?.[0]??'',otherSuffix=target.slice(bs,be).match(/\s+$/u)?.[0]??'';
|
|
47
|
+
if(suffix===otherSuffix){end-=suffix.length;be-=suffix.length;}
|
|
48
|
+
add(start,end,bs,be);
|
|
49
|
+
}
|
|
50
|
+
let i=0,j=0,sourceEnd=0,targetEnd=0;
|
|
51
|
+
while(i<a.length&&j<b.length){
|
|
52
|
+
if(a[i].text===b[j].text){
|
|
53
|
+
gap(sourceEnd,a[i].start,targetEnd,b[j].start);
|
|
54
|
+
sourceEnd=a[i++].end;targetEnd=b[j++].end;
|
|
55
|
+
}else if(matrix[(i+1)*stride+j]>=matrix[i*stride+j+1])i++;
|
|
56
|
+
else j++;
|
|
57
|
+
}
|
|
58
|
+
gap(sourceEnd,source.length,targetEnd,target.length);
|
|
59
|
+
let rebuilt='',cursor=0;
|
|
60
|
+
for(const edit of edits){
|
|
61
|
+
if(edit.start<cursor)throw new Error('Overlapping orthography edits');
|
|
62
|
+
rebuilt+=source.slice(cursor,edit.start)+edit.replacement;cursor=edit.end;
|
|
63
|
+
}
|
|
64
|
+
if(rebuilt+source.slice(cursor)!==target)throw new Error('Orthography reconstruction mismatch');
|
|
65
|
+
return edits;
|
|
66
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Review-only, deterministic contextual ranking. Never generates or applies a replacement.
|
|
2
|
+
// Phrase evidence is a small audited procurement corpus, not a typo-to-fix dictionary.
|
|
3
|
+
// Upstream order is retained for ties and for candidates without contextual evidence.
|
|
4
|
+
const phrases = [
|
|
5
|
+
'please provide','please confirm','please submit','please send','please quote','please advise','please supply','please deliver','please inspect','please acknowledge','please specify','please attach','please review','please verify','please proceed',
|
|
6
|
+
'have received','has received','we received','received your','received the','will proceed','proceed with','proceed to','your quotation','the quotation','a quotation','request quotation','submit quotation','commercial quotation','technical quotation',
|
|
7
|
+
'requested equipment','industrial equipment','the equipment','provide your','provide the','provide us','provide a','provide details','provide documents','provide information','provide pricing','provide confirmation','provide evidence','prove that','prove compliance','prove ownership','prove the claim',
|
|
8
|
+
'delivery schedule','delivery date','delivery terms','purchase order','technical specification','material certificate','inspection report','commercial offer','payment terms','lead time','unit price','order confirmation','quotation validity'
|
|
9
|
+
];
|
|
10
|
+
const contexts=new Set(phrases);
|
|
11
|
+
const vocabulary=new Set(['quotation','supplier','equipment','procurement','purchase','delivery','availability','manufacturer','inspection','certificate','commercial','technical','invoice','shipment','warranty','material','quantity']);
|
|
12
|
+
const words=s=>s.toLowerCase().match(/[a-z]+/g)??[];
|
|
13
|
+
export function rankSpellingAlternatives(proposals,source){
|
|
14
|
+
return proposals.map((proposal,index)=>{
|
|
15
|
+
const candidate=proposal.replacement?.toLowerCase()??'';
|
|
16
|
+
if(!/^[a-z]+$/.test(candidate))return {proposal,index,score:0};
|
|
17
|
+
const left=source.slice(Math.max(0,proposal.start-80),proposal.start);
|
|
18
|
+
const right=source.slice(proposal.end,proposal.end+80);
|
|
19
|
+
// Do not use context across a sentence boundary or a protected region.
|
|
20
|
+
const before=words(left.split(/[.!?;\r\n]/u).at(-1)).slice(-2);
|
|
21
|
+
const after=words(right.split(/[.!?;\r\n]/u)[0]).slice(0,2);
|
|
22
|
+
const joined=[...before,candidate,...after];
|
|
23
|
+
const pos=before.length;
|
|
24
|
+
let score=vocabulary.has(candidate)?1:0;
|
|
25
|
+
for(let width=2;width<=3;width++)for(let i=Math.max(0,pos-width+1);i<=pos&&i+width<=joined.length;i++){
|
|
26
|
+
const phrase=joined.slice(i,i+width).join(' ');
|
|
27
|
+
if(contexts.has(phrase))score+=phrase.startsWith('please ')?width*2:width*4;
|
|
28
|
+
}
|
|
29
|
+
return {proposal,index,score};
|
|
30
|
+
}).sort((a,b)=>b.score-a.score||a.index-b.index).map(x=>x.proposal);
|
|
31
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { codePointOffset, validRange } from '../regions.mjs';
|
|
2
|
+
|
|
3
|
+
export function languageToolAdapter(check) {
|
|
4
|
+
if (typeof check !== 'function') throw new TypeError('Explicit self-hosted LanguageTool transport required');
|
|
5
|
+
return Object.freeze({id:'languagetool',languages:['en','fa'],async check(text,language,signal) {
|
|
6
|
+
const result = await check(text,language,signal);
|
|
7
|
+
if (!Array.isArray(result?.matches)) throw new Error('Invalid LanguageTool response');
|
|
8
|
+
return result.matches.flatMap(m=>{
|
|
9
|
+
if (!Number.isSafeInteger(m?.offset) || !Number.isSafeInteger(m?.length) || m.length<0) return [];
|
|
10
|
+
const start=m.offset,end=start+m.length;
|
|
11
|
+
if (!validRange(text,start,end)) return [];
|
|
12
|
+
const context=m.context;
|
|
13
|
+
if (typeof context?.text!=='string'||!Number.isSafeInteger(context.offset)||context.offset<0||context.length!==m.length||
|
|
14
|
+
context.offset+context.length>context.text.length||context.text.slice(context.offset,context.offset+context.length)!==text.slice(start,end)) return [];
|
|
15
|
+
const base={start,end,original:text.slice(start,end),rule:m.rule?.id,category:m.rule?.issueType==='misspelling'?'spelling':'grammar',message:m.message};
|
|
16
|
+
const suggestions=(Array.isArray(m.replacements)?m.replacements:[]).slice(0,5).filter(x=>typeof x?.value==='string');
|
|
17
|
+
return suggestions.length?suggestions.map(x=>({...base,replacement:x.value})):[base];
|
|
18
|
+
});
|
|
19
|
+
}});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// STE100 is advisory, not a claim of official ASD conformance. Its Python offsets are code points.
|
|
23
|
+
export function ste100Adapter(check) {
|
|
24
|
+
if (typeof check !== 'function') throw new TypeError('STE100 runner required');
|
|
25
|
+
return Object.freeze({id:'ste100',languages:['en'],async check(text,_language,signal) {
|
|
26
|
+
const report=await check(text,signal);
|
|
27
|
+
if (!Array.isArray(report?.violations)) throw new Error('Invalid STE100 report');
|
|
28
|
+
return report.violations.flatMap(v=>{
|
|
29
|
+
const start=codePointOffset(text,v.start),end=codePointOffset(text,v.end);
|
|
30
|
+
if (!validRange(text,start,end) || text.slice(start,end)!==v.text) return [];
|
|
31
|
+
// Upstream suggestions may be explanatory guidance rather than literal replacement text.
|
|
32
|
+
return [{start,end,original:v.text,rule:v.rule,category:'technical-writing',message:v.message}];
|
|
33
|
+
});
|
|
34
|
+
}});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Vale columns can depend on parser/encoding. Use an unambiguous exact match on the reported line.
|
|
38
|
+
// Never use heuristic global search or a repeated match. Keep findings advisory.
|
|
39
|
+
export function valeAdapter(check) {
|
|
40
|
+
if (typeof check !== 'function') throw new TypeError('Vale runner required');
|
|
41
|
+
return Object.freeze({id:'vale',languages:['en'],async check(text,_language,signal) {
|
|
42
|
+
const report=await check(text,signal);
|
|
43
|
+
if (!report || typeof report!=='object'||Array.isArray(report)) throw new Error('Invalid Vale report');
|
|
44
|
+
const groups=Object.values(report);
|
|
45
|
+
if (groups.length>1 || groups.some(g=>!Array.isArray(g))) throw new Error('Expected one Vale document');
|
|
46
|
+
const lines=text.split('\n'), offsets=[];
|
|
47
|
+
let offset=0; for (const line of lines) {offsets.push(offset);offset+=line.length+1;}
|
|
48
|
+
return groups.flat().flatMap(a=>{
|
|
49
|
+
if (!Number.isSafeInteger(a?.Line)||a.Line<1||a.Line>lines.length||typeof a.Match!=='string'||!a.Match) return [];
|
|
50
|
+
const line=lines[a.Line-1], i=line.indexOf(a.Match);
|
|
51
|
+
if (i<0||line.indexOf(a.Match,i+1)!==-1) return [];
|
|
52
|
+
const start=offsets[a.Line-1]+i,end=start+a.Match.length;
|
|
53
|
+
return [{start,end,original:a.Match,rule:a.Check,category:'terminology',message:a.Message}];
|
|
54
|
+
});
|
|
55
|
+
}});
|
|
56
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { validRange } from '../regions.mjs';
|
|
2
|
+
// Only host-supplied, reviewed plugin/rule modules; never load rules from user text or URLs.
|
|
3
|
+
// Textlint reports may contain fixes on different ranges; use the explicit fix range, not message.index.
|
|
4
|
+
export function textlintAdapter(kernel, options) {
|
|
5
|
+
if (!kernel || typeof kernel.lintText !== 'function' || !Array.isArray(options?.rules) || !Array.isArray(options?.plugins)) throw new TypeError('Reviewed textlint configuration required');
|
|
6
|
+
const config = {ext:'.txt',filePath:'procurement.txt',plugins:[...options.plugins],rules:[...options.rules]};
|
|
7
|
+
return Object.freeze({id:'textlint',languages:['en','fa'],async check(text) {
|
|
8
|
+
const result = await kernel.lintText(text,config);
|
|
9
|
+
if (!Array.isArray(result?.messages)) throw new Error('Invalid textlint result');
|
|
10
|
+
const output=[];
|
|
11
|
+
for (const m of result.messages) {
|
|
12
|
+
// Fatal parser diagnostics cannot establish a text range.
|
|
13
|
+
if (!m.ruleId || m.fatal || typeof m.message !== 'string') continue;
|
|
14
|
+
if (Array.isArray(m.fix?.range) && m.fix.range.length === 2 && typeof m.fix.text === 'string') {
|
|
15
|
+
const [start,end]=m.fix.range;
|
|
16
|
+
if (validRange(text,start,end)) output.push({start,end,original:text.slice(start,end),replacement:m.fix.text,rule:m.ruleId,category:m.ruleId==='procurement-agreement'?'grammar':'style',message:m.message});
|
|
17
|
+
}
|
|
18
|
+
else if (Array.isArray(m.range) && m.range.length===2 && validRange(text,...m.range) && m.range[0]<m.range[1]) {
|
|
19
|
+
const [start,end]=m.range;
|
|
20
|
+
output.push({start,end,original:text.slice(start,end),rule:m.ruleId,category:'style',message:m.message});
|
|
21
|
+
}
|
|
22
|
+
// Point-only messages have no verified span: fail closed instead of guessing an end offset.
|
|
23
|
+
}
|
|
24
|
+
return output;
|
|
25
|
+
}});
|
|
26
|
+
}
|
|
27
|
+
export async function createTextlint(rules) {
|
|
28
|
+
const [{TextlintKernel}, plugin] = await Promise.all([import('@textlint/kernel'),import('@textlint/textlint-plugin-text')]);
|
|
29
|
+
const textPlugin=plugin.default?.default ?? plugin.default;
|
|
30
|
+
return textlintAdapter(new TextlintKernel(),{plugins:[{pluginId:'text',plugin:textPlugin}],rules});
|
|
31
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { orthographyEdits } from './orthography-diff.mjs';
|
|
2
|
+
import { formalPersianOrthography } from './formal-persian.mjs';
|
|
3
|
+
|
|
4
|
+
// Deny all documented transformations except narrow Persian orthography operations.
|
|
5
|
+
// Changes to upstream defaults require requalification of the exact package version.
|
|
6
|
+
const disabled = ['cleanup_begin_and_end','cleanup_extra_marks','cleanup_kashidas','cleanup_line_breaks','cleanup_rlm','cleanup_spacing','cleanup_zwnj','decode_htmlentities','fix_arabic_numbers','fix_dashes','fix_diacritics','fix_english_numbers','fix_english_quotes_pairs','fix_english_quotes','fix_hamzeh','fix_hamzeh_arabic','fix_misc_non_persian_chars','fix_misc_spacing','fix_numeral_symbols','fix_perfix_spacing','fix_persian_glyphs','fix_punctuations','fix_question_mark','fix_spacing_for_braces_and_quotes','fix_spacing_for_punctuations','fix_suffix_misc','fix_suffix_spacing','fix_three_dots','kashidas_as_parenthetic','markdown_normalize_braces','markdown_normalize_lists','normalize_dates','normalize_ellipsis','remove_spaces_before_ellipsis','normalize_eol','remove_diacritics'];
|
|
7
|
+
export const VIRASTAR_OPTIONS = Object.freeze({...Object.fromEntries(disabled.map(k=>[k,false])),fix_misc_non_persian_chars:true,fix_perfix_spacing:true,fix_persian_glyphs:true,fix_suffix_spacing:true,fix_suffix_misc:true,preserve_braces:true,preserve_brackets:true});
|
|
8
|
+
|
|
9
|
+
export function normalizerAdapter(normalize, {experimental=false}={}) {
|
|
10
|
+
if (typeof normalize !== 'function') throw new TypeError('Persian normalizer required');
|
|
11
|
+
return Object.freeze({id:experimental?'virastar-ts':'virastar',languages:['fa'],async check(text) {
|
|
12
|
+
const normalized = await normalize(text);
|
|
13
|
+
if (typeof normalized !== 'string' || !normalized.isWellFormed()) throw new Error('Invalid normalizer result');
|
|
14
|
+
return orthographyEdits(text,normalized).map(edit=>({...edit,rule:'orthography',category:'orthography',message:'Review Persian orthography.',...(experimental?{replacement:undefined}:{})}));
|
|
15
|
+
}});
|
|
16
|
+
}
|
|
17
|
+
export async function createVirastar() {
|
|
18
|
+
const {default:Virastar} = await import('virastar');
|
|
19
|
+
const linter = new Virastar({...VIRASTAR_OPTIONS});
|
|
20
|
+
// Compose the reviewed local formal style policy after upstream cleanup.
|
|
21
|
+
return normalizerAdapter(text=>formalPersianOrthography(linter.cleanup(text)));
|
|
22
|
+
}
|
|
23
|
+
// Experimental TypeScript fork is an alternative, advisory-only provider; do not run both by default.
|
|
24
|
+
export function experimentalVirastarAdapter(instance) {
|
|
25
|
+
if (!instance || typeof instance.process !== 'function') throw new TypeError('Experimental Virastar instance required');
|
|
26
|
+
return normalizerAdapter(text=>instance.process(text),{experimental:true});
|
|
27
|
+
}
|
package/src/engine.mjs
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { LIMITS, validateDocument, eligible, boundaries, validRange, validReplacement } from './regions.mjs';
|
|
2
|
+
|
|
3
|
+
const providerId = /^[a-z][a-z0-9-]{0,47}$/;
|
|
4
|
+
const ruleId = /^[a-zA-Z0-9_.:/-]{1,100}$/;
|
|
5
|
+
const categories = new Set(['spelling','grammar','orthography','terminology','style','technical-writing']);
|
|
6
|
+
const by = (a,b) => a < b ? -1 : a > b ? 1 : 0;
|
|
7
|
+
const plainMessage = x => typeof x === 'string' && x.length > 0 && x.length <= LIMITS.message && !/[<>\p{Cc}\p{Cf}]/u.test(x);
|
|
8
|
+
const frozen = x => Object.freeze(x);
|
|
9
|
+
|
|
10
|
+
function report(snapshotId, status, findings, diagnostics) {
|
|
11
|
+
return frozen({ snapshotId, status, findings: frozen(findings.map(frozen)), diagnostics: frozen(diagnostics.map(frozen)), apply: false });
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function createEngine(providers) {
|
|
15
|
+
if (!Array.isArray(providers) || !providers.length || providers.length > LIMITS.providers) throw new TypeError('Invalid provider set');
|
|
16
|
+
const ids = new Set();
|
|
17
|
+
const configured = providers.map(p => {
|
|
18
|
+
if (!p || typeof p.id !== 'string' || !providerId.test(p.id) || ids.has(p.id) || typeof p.check !== 'function' ||
|
|
19
|
+
!Array.isArray(p.languages) || !p.languages.length || p.languages.some(l => !['en','fa'].includes(l))) throw new TypeError('Invalid provider');
|
|
20
|
+
ids.add(p.id);
|
|
21
|
+
return frozen({id:p.id, languages:frozen([...p.languages]), check:p.check.bind(p)});
|
|
22
|
+
});
|
|
23
|
+
let running = false, retired = false;
|
|
24
|
+
// Cancellation is cooperative. Stop waiting for noncooperative asynchronous providers,
|
|
25
|
+
// retire the engine rather than overlap calls. The host must terminate a worker that hangs.
|
|
26
|
+
async function boundedCheck(p, source, language, signal, remaining) {
|
|
27
|
+
const controller = new AbortController();
|
|
28
|
+
let timer, onAbort;
|
|
29
|
+
const pending = Promise.resolve().then(()=>{if(controller.signal.aborted)throw new Error('Cancelled');return p.check(source,language,controller.signal);})
|
|
30
|
+
.then(value=>({kind:'result',value}),()=>({kind:'failed'}));
|
|
31
|
+
const stop = new Promise(resolve=>{
|
|
32
|
+
onAbort=()=>{controller.abort();resolve({kind:'cancelled'});};
|
|
33
|
+
if (signal?.aborted) onAbort();
|
|
34
|
+
else signal?.addEventListener('abort',onAbort,{once:true});
|
|
35
|
+
timer=setTimeout(()=>{controller.abort();resolve({kind:'timeout'});},Math.max(1,Math.min(remaining,LIMITS.providerMs)));
|
|
36
|
+
});
|
|
37
|
+
try { return await Promise.race([pending,stop]); }
|
|
38
|
+
finally { clearTimeout(timer);signal?.removeEventListener('abort',onAbort); }
|
|
39
|
+
}
|
|
40
|
+
return frozen({ async analyze(document, { signal } = {}) {
|
|
41
|
+
if (retired) return report(null,'blocked',[],[{code:'engine-retired'}]);
|
|
42
|
+
if (running) return report(null,'busy',[],[]);
|
|
43
|
+
// Capture before first await. No source text or raw exception appears in diagnostics.
|
|
44
|
+
if (!validateDocument(document)) return report(null,'blocked',[],[{code:'invalid-region-map'}]);
|
|
45
|
+
const { text, snapshotId } = document;
|
|
46
|
+
const regions = document.regions.map(r => frozen({...r}));
|
|
47
|
+
if (signal?.aborted) return report(snapshotId,'cancelled',[],[]);
|
|
48
|
+
running = true;
|
|
49
|
+
try {
|
|
50
|
+
const findings = [], diagnostics = [];
|
|
51
|
+
const seen = new Set();
|
|
52
|
+
let partial = false, calls = 0;
|
|
53
|
+
const deadline = performance.now() + LIMITS.elapsedMs;
|
|
54
|
+
regionLoop: for (const region of regions) {
|
|
55
|
+
if (region.kind === 'protected') continue;
|
|
56
|
+
const source = text.slice(region.start,region.end);
|
|
57
|
+
if (!eligible(source,region.language)) {
|
|
58
|
+
partial = true; diagnostics.push({code:'unsafe-region',start:region.start}); continue;
|
|
59
|
+
}
|
|
60
|
+
const enabled = configured.filter(p => p.languages.includes(region.language));
|
|
61
|
+
if (!enabled.length) { partial = true; diagnostics.push({code:'no-provider',start:region.start}); continue; }
|
|
62
|
+
const b = boundaries(source);
|
|
63
|
+
for (const p of enabled) {
|
|
64
|
+
if (signal?.aborted) return report(snapshotId,'cancelled',[],[]);
|
|
65
|
+
if (++calls > LIMITS.calls || performance.now() >= deadline) {
|
|
66
|
+
partial = true; diagnostics.push({code:'budget-exhausted'}); break regionLoop;
|
|
67
|
+
}
|
|
68
|
+
const checked = await boundedCheck(p,source,region.language,signal,deadline-performance.now());
|
|
69
|
+
if (checked.kind === 'cancelled' || signal?.aborted) {
|
|
70
|
+
if (checked.kind === 'cancelled') retired = true;
|
|
71
|
+
return report(snapshotId,'cancelled',[],[]);
|
|
72
|
+
}
|
|
73
|
+
if (checked.kind === 'timeout') {
|
|
74
|
+
retired = true; partial = true; diagnostics.push({code:'provider-timeout',provider:p.id,start:region.start}); break regionLoop;
|
|
75
|
+
}
|
|
76
|
+
if (checked.kind === 'failed') {partial=true;diagnostics.push({code:'provider-failed',provider:p.id,start:region.start});continue;}
|
|
77
|
+
const raw = checked.value;
|
|
78
|
+
if (!Array.isArray(raw)) { partial = true; diagnostics.push({code:'invalid-provider-result',provider:p.id}); continue; }
|
|
79
|
+
if (raw.length > LIMITS.providerFindings) { partial = true; diagnostics.push({code:'provider-limit',provider:p.id}); }
|
|
80
|
+
let rejected = false, limited = false;
|
|
81
|
+
for (const f of raw.slice(0,LIMITS.providerFindings)) {
|
|
82
|
+
if (!f || typeof f.rule !== 'string' || !ruleId.test(f.rule) || !categories.has(f.category) ||
|
|
83
|
+
!validRange(source,f.start,f.end,b) || source.slice(f.start,f.end) !== f.original ||
|
|
84
|
+
!plainMessage(f.message) || (f.replacement === undefined && f.start === f.end)) {
|
|
85
|
+
partial = true; rejected = true; continue;
|
|
86
|
+
}
|
|
87
|
+
// Inserts on a protected-region boundary are rejected; do not guess where they belong.
|
|
88
|
+
if (f.start === f.end && (f.start === 0 || f.start === source.length)) { partial = true; rejected = true; continue; }
|
|
89
|
+
if (f.replacement !== undefined && !validReplacement(f.original,f.replacement,region.language)) { partial = true; rejected = true; continue; }
|
|
90
|
+
const start = region.start + f.start, end = region.start + f.end;
|
|
91
|
+
const key = JSON.stringify([p.id,f.rule,start,end,f.replacement ?? null]);
|
|
92
|
+
if (seen.has(key)) continue;
|
|
93
|
+
seen.add(key);
|
|
94
|
+
if (findings.length >= LIMITS.findings) { partial = true; limited = true; continue; }
|
|
95
|
+
findings.push({provider:p.id, rule:f.rule, category:f.category, start,end,original:f.original,
|
|
96
|
+
...(f.replacement === undefined ? {} : {replacement:f.replacement}), message:f.message});
|
|
97
|
+
}
|
|
98
|
+
if (rejected) diagnostics.push({code:'rejected-finding',provider:p.id,start:region.start});
|
|
99
|
+
if (limited) diagnostics.push({code:'finding-limit',provider:p.id,start:region.start});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (signal?.aborted) return report(snapshotId,'cancelled',[],[]);
|
|
103
|
+
// Stable sort: do not alphabetize competing replacements from the same rule.
|
|
104
|
+
findings.sort((a,b) => a.start-b.start || a.end-b.end || by(a.provider,b.provider) || by(a.rule,b.rule));
|
|
105
|
+
return report(snapshotId,partial?'partial':'complete',findings,diagnostics);
|
|
106
|
+
} finally { running = false; }
|
|
107
|
+
}});
|
|
108
|
+
}
|
package/src/index.d.mts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export type Language = 'en' | 'fa';
|
|
2
|
+
export type Category = 'spelling'|'grammar'|'orthography'|'terminology'|'style'|'technical-writing';
|
|
3
|
+
export type Region = Readonly<{start:number;end:number} & ({kind:'protected'}|{kind:'prose';language:Language})>;
|
|
4
|
+
export interface DocumentSnapshot { readonly text:string; readonly snapshotId:string; readonly regions:readonly Region[] }
|
|
5
|
+
export interface Proposal { readonly start:number; readonly end:number; readonly original:string; readonly replacement?:string; readonly rule:string; readonly category:Category; readonly message:string }
|
|
6
|
+
export interface Provider { readonly id:string; readonly languages:readonly Language[]; check(text:string,language:Language,signal?:AbortSignal):Promise<readonly Proposal[]>|readonly Proposal[] }
|
|
7
|
+
export interface Finding extends Proposal { readonly provider:string }
|
|
8
|
+
export interface Diagnostic { readonly code:string; readonly provider?:string; readonly start?:number }
|
|
9
|
+
export interface Analysis { readonly snapshotId:string|null; readonly status:'complete'|'partial'|'blocked'|'cancelled'|'busy'; readonly findings:readonly Finding[]; readonly diagnostics:readonly Diagnostic[]; readonly apply:false }
|
|
10
|
+
export interface Engine { analyze(document:DocumentSnapshot,options?:{signal?:AbortSignal}):Promise<Analysis> }
|
|
11
|
+
export function createEngine(providers:readonly Provider[]):Engine;
|
|
12
|
+
export interface HarperSuggestion { kind():number; get_replacement_text():string; free?():void }
|
|
13
|
+
export interface HarperLint { span():{start:number;end:number;free?():void}; get_problem_text():string; lint_kind():string; message():string; suggestions():HarperSuggestion[]; free?():void }
|
|
14
|
+
export interface HarperLinter { organizedLints(text:string,options?:{language:'plaintext';dedup:boolean;isolateEnglish:boolean}):Promise<Record<string,readonly HarperLint[]>> }
|
|
15
|
+
export function harperAdapter(linter:HarperLinter):Provider;
|
|
16
|
+
export function createHarper(options:{binary:unknown;worker?:boolean;dialect?:unknown}):Promise<{provider:Provider;dispose:()=>Promise<void>}>;
|
|
17
|
+
export function createVirastar():Promise<Provider>;
|
|
18
|
+
export function normalizerAdapter(normalize:(text:string)=>string|Promise<string>,options?:{experimental?:boolean}):Provider;
|
|
19
|
+
export function experimentalVirastarAdapter(instance:{process(text:string):string|Promise<string>}):Provider;
|
|
20
|
+
export const VIRASTAR_OPTIONS:Readonly<Record<string,boolean>>;
|
|
21
|
+
export interface TextlintRule { ruleId:string; rule:unknown; options?:unknown }
|
|
22
|
+
export interface TextlintPlugin { pluginId:string; plugin:unknown; options?:unknown }
|
|
23
|
+
export function textlintAdapter(kernel:{lintText(text:string,options:any):Promise<unknown>},options:{rules:readonly TextlintRule[];plugins:readonly TextlintPlugin[]}):Provider;
|
|
24
|
+
export function createTextlint(rules:readonly TextlintRule[]):Promise<Provider>;
|
|
25
|
+
export const procurementDeliveryRule:TextlintRule;
|
|
26
|
+
export const procurementAgreementRule:TextlintRule;
|
|
27
|
+
export const procurementPolicyRules:readonly TextlintRule[];
|
|
28
|
+
export function languageToolAdapter(check:(text:string,language:Language,signal?:AbortSignal)=>Promise<unknown>):Provider;
|
|
29
|
+
export function ste100Adapter(check:(text:string,signal?:AbortSignal)=>Promise<unknown>):Provider;
|
|
30
|
+
export function valeAdapter(check:(text:string,signal?:AbortSignal)=>Promise<unknown>):Provider;
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export {createEngine} from './engine.mjs';
|
|
2
|
+
export {harperAdapter,createHarper} from './adapters/harper.mjs';
|
|
3
|
+
export {createVirastar,normalizerAdapter,experimentalVirastarAdapter,VIRASTAR_OPTIONS} from './adapters/virastar.mjs';
|
|
4
|
+
export {textlintAdapter,createTextlint} from './adapters/textlint.mjs';
|
|
5
|
+
export {languageToolAdapter,ste100Adapter,valeAdapter} from './adapters/reports.mjs';
|
|
6
|
+
export {procurementDeliveryRule,procurementAgreementRule,procurementPolicyRules} from './policy.mjs';
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type {Provider} from '../index.mjs';
|
|
2
|
+
export function createVale(options:{executable:string;config:string}):Provider;
|
|
3
|
+
export function createSTE100(options:{executable:string}):Provider;
|
|
4
|
+
export function createLocalLanguageTool(options?:{endpoint?:string}):Provider;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join, isAbsolute } from 'node:path';
|
|
5
|
+
import { languageToolAdapter, ste100Adapter, valeAdapter } from '../adapters/reports.mjs';
|
|
6
|
+
|
|
7
|
+
const MAX_RESPONSE=1024*1024;
|
|
8
|
+
const TIMEOUT=15000;
|
|
9
|
+
function runJson(executable,args,{stdin,signal,accepted=[0]}={}) {
|
|
10
|
+
if (!isAbsolute(executable)) throw new TypeError('Absolute executable path required');
|
|
11
|
+
return new Promise((resolve,reject)=>{
|
|
12
|
+
if (signal?.aborted) {reject(new Error('Cancelled'));return;}
|
|
13
|
+
const env = {};
|
|
14
|
+
for (const key of ['PATH','Path','SystemRoot','WINDIR','TEMP','TMP','TMPDIR','LANG','LC_ALL']) {
|
|
15
|
+
if (process.env[key] !== undefined) env[key] = process.env[key];
|
|
16
|
+
}
|
|
17
|
+
const child=spawn(executable,args,{shell:false,windowsHide:true,stdio:['pipe','pipe','ignore'],env});
|
|
18
|
+
let settled=false, bytes=0; const chunks=[];
|
|
19
|
+
const timer=setTimeout(()=>fail('Process timeout'),TIMEOUT);
|
|
20
|
+
const abort=()=>fail('Cancelled');
|
|
21
|
+
function cleanup(){clearTimeout(timer);signal?.removeEventListener('abort',abort);}
|
|
22
|
+
function fail(reason){if(settled)return;settled=true;cleanup();child.kill();reject(new Error(reason));}
|
|
23
|
+
signal?.addEventListener('abort',abort,{once:true});
|
|
24
|
+
child.stdout.on('data',chunk=>{bytes+=chunk.length;if(bytes>MAX_RESPONSE)fail('Output limit');else if(!settled)chunks.push(chunk);});
|
|
25
|
+
child.on('error',()=>fail('Process unavailable'));
|
|
26
|
+
child.stdin.on('error',()=>fail('Input failed'));
|
|
27
|
+
child.on('close',code=>{if(settled)return;if(!accepted.includes(code)){fail('Process failed');return;}settled=true;cleanup();try{resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));}catch{reject(new Error('Invalid JSON'));}});
|
|
28
|
+
child.stdin.end(stdin??'');
|
|
29
|
+
if(signal?.aborted)abort();
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
// Absolute paths and configs are deployment-owned. Do not accept them from user requests.
|
|
33
|
+
export function createVale({executable,config}) {
|
|
34
|
+
if(!isAbsolute(executable)||!isAbsolute(config))throw new TypeError('Absolute paths required');
|
|
35
|
+
return valeAdapter((text,signal)=>runJson(executable,['--config',config,'--output=JSON','--ext=.txt','--no-exit'],{stdin:text,signal}));
|
|
36
|
+
}
|
|
37
|
+
export function createSTE100({executable}) {
|
|
38
|
+
if(!isAbsolute(executable))throw new TypeError('Absolute executable path required');
|
|
39
|
+
return ste100Adapter(async(text,signal)=>{
|
|
40
|
+
const dir=await mkdtemp(join(tmpdir(),'pwe-'));
|
|
41
|
+
try{const path=join(dir,'input.txt');await writeFile(path,text,{encoding:'utf8',mode:0o600,flag:'wx'});return await runJson(executable,[path,'--format','json'],{signal});}
|
|
42
|
+
finally{await rm(dir,{recursive:true,force:true});}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
// A self-hosted service is explicitly enabled by the host. No external API, DNS, redirect, or cookies.
|
|
46
|
+
// Use only a loopback service verified to have no cloud forwarding/telemetry.
|
|
47
|
+
export function createLocalLanguageTool({endpoint='http://127.0.0.1:8081/v2/check'}={}) {
|
|
48
|
+
const url=new URL(endpoint);
|
|
49
|
+
if(url.protocol!=='http:'||url.hostname!=='127.0.0.1'||!url.port||url.pathname!=='/v2/check'||url.search||url.hash||url.username||url.password)throw new TypeError('Loopback LanguageTool endpoint required');
|
|
50
|
+
return languageToolAdapter(async(text,language,signal)=>{
|
|
51
|
+
const timeout=AbortSignal.timeout(TIMEOUT);
|
|
52
|
+
const response=await fetch(url,{method:'POST',body:new URLSearchParams({text,language:language==='en'?'en-US':'fa'}),redirect:'error',credentials:'omit',cache:'no-store',signal:signal?AbortSignal.any([signal,timeout]):timeout});
|
|
53
|
+
if(!response.ok||!response.body)throw new Error('LanguageTool unavailable');
|
|
54
|
+
const reader=response.body.getReader(), chunks=[];let bytes=0;
|
|
55
|
+
try{while(true){const {done,value}=await reader.read();if(done)break;bytes+=value.byteLength;if(bytes>MAX_RESPONSE)throw new Error('Output limit');chunks.push(value);}return JSON.parse(Buffer.concat(chunks).toString('utf8'));}
|
|
56
|
+
finally{await reader.cancel().catch(()=>{});reader.releaseLock();}
|
|
57
|
+
});
|
|
58
|
+
}
|