1
+import fs from 'node:fs';
2
+import path from 'node:path';
3
+import vm from 'node:vm';
4
+import {createHash} from 'node:crypto';
5
+
6
+// These are original contiguous, parser-blocking <script> runs in index.html.
7
+// Preserve all CSS boundaries and early CSP/auth binding scripts unchanged.
8
+const groups=[
9
+ {name:'foundation',files:['admin','sync','ui','invoices','print','products','contacts','cheques','expenses','companies','backup','words']},
10
+ {name:'business',files:['patches','idle-and-reports','money-format','projects','invoice-excel-import','purchases','commercial-rnd','operations','payments','accounting']},
11
+ {name:'accounting',files:['accounting-foundation','journal-engine','context-help','accounting-foundation-ui','accounting-foundation-render','journal-ui','document-management','drilldown','phase4-contracting','phase5-domain','phase5-enterprise','phase6-reporting','enterprise-iran','enterprise-iran-v2','selfcheck','ux-hardening-r2']}
12
+];
13
+const localScript=/<script src="(js\/([a-z0-9-]+)\.js(?:\?v=[a-z0-9-]+)?)"><\/script>/gi;
14
+
15
+export function bundleFinoraPagesBlockingScripts(originalHtml,outDir){
16
+ let html=originalHtml;
17
+ for(const {name,files} of groups){
18
+ const tags=[...html.matchAll(localScript)];
19
+ const from=tags.find(t=>t[2]===files[0]);
20
+ const last=tags.find(t=>t[2]===files.at(-1));
21
+ if(!from||!last||last.index<from.index)throw new Error('Missing Pages group '+name);
22
+ const segment=html.slice(from.index,last.index+last[0].length);
23
+ const found=[...segment.matchAll(localScript)].map(t=>t[2]);
24
+ if(JSON.stringify(found)!==JSON.stringify(files)||segment.replace(localScript,'').trim())
25
+ throw new Error('Non-contiguous or reordered Pages scripts in '+name);
26
+ const sources=files.map(file=>{
27
+ const filename=path.join(outDir,'js',file+'.js');
28
+ if(!fs.existsSync(filename))throw new Error('Missing Pages JS '+file);
29
+ return fs.readFileSync(filename,'utf8');
30
+ });
31
+ // A classic-script concatenation preserves global declarations and
32
+ // executes each source in its original document order, exactly once.
33
+ const content='// Finora '+name+' Pages-only bundle. Original order.\n'+sources.join('\n;\n');
34
+ new vm.Script(content,{filename:'finora-'+name+'-pages.js'});
35
+ const hash=createHash('sha256').update(content).digest('hex').slice(0,16);
36
+ const file='finora-pages-'+name+'.js';
37
+ fs.writeFileSync(path.join(outDir,'js',file),content);
38
+ html=html.slice(0,from.index)+'<script src="js/'+file+'?v='+hash+'"></script>'+html.slice(last.index+last[0].length);
39
+ }
40
+ return html;
41
+}