38 lines
12 KiB
JavaScript
38 lines
12 KiB
JavaScript
// Production compiled Names/Context Razor, shared scripts and confirmation UI. Synthetic HTTP results only.
|
|
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
|
const fakeSignalR=`window.contextConnections=[];window.signalR={HubConnectionBuilder:class{withUrl(url){this.url=url;return this}withAutomaticReconnect(){return this}build(){const c={url:this.url,state:'Disconnected',handlers:{},on(n,f){const prior=this.handlers[n];this.handlers[n]=(...args)=>{prior?.(...args);f(...args)}},onreconnecting(){},onreconnected(){},onclose(){},async invoke(method,...args){(this.invocations??=[]).push(method);return method==='SendContextInteraction'?{status:'no-handler'}:method==='ClaimContextMainWindow'?true:null},async start(){this.state='Connected'},async stop(){this.state='Disconnected'}};contextConnections.push(c);return c}}};`;
|
|
(async()=>{
|
|
const installed=process.argv.includes('--installed'),base='http://127.0.0.1:5238',manifestId=base+'/Projects',profile=installed?fs.mkdtempSync(path.join(os.tmpdir(),'pd-name-verification-pwa-')):null,persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1920,height:1080}}):null,browser=installed?persistent.browser():await chromium.launch(),cdp=installed?await browser.newBrowserCDPSession():null;
|
|
try{
|
|
let page;if(installed){await persistent.pages()[0].goto(base+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=persistent.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+'/fixture?page=calendar-test'});page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else page=await browser.newPage({viewport:{width:1920,height:1080}});
|
|
const errors=[],saved=new Set(),calls={estimate:0,textual:0,execute:[],details:0};let allowed=true,remaining=5,outdated=false,interrupted=false;page.on('pageerror',e=>errors.push(e.message));
|
|
await page.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fakeSignalR}));
|
|
for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await page.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{connected:false,known:false}}));
|
|
await page.route('**/NarrativeFocus/Shared?*',r=>r.fulfill({json:{projectID:7,bookID:12,chapterID:10,sceneID:22,version:1,isValid:true}}));
|
|
await page.route('**/SharedFocus/**',r=>r.fulfill({json:{success:true}}));
|
|
async function names(route,details){const u=new URL(route.request().url());if(details){calls.details++;if(saved.has(u.searchParams.get('name')))u.searchParams.set('verified','true');if(outdated)u.searchParams.set('outdated','true');if(interrupted)u.searchParams.set('interrupted','true');}await route.fulfill({response:await page.request.get(base+'/names-workspace-fixture/'+(details?'details':'results')+'?'+u.searchParams)});}
|
|
await page.route('**/Names/Results?*',r=>names(r,false));await page.route('**/Names/Details?*',r=>names(r,true));
|
|
await page.route('**/Writing/Context/Names/Search?*',r=>names(r,false));await page.route('**/Writing/Context/Names/Details?*',r=>names(r,true));
|
|
await page.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await page.request.get(base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search)});});
|
|
await page.route('**/NameVerification/Estimate?*',r=>{calls.estimate++;const name=new URL(r.request().url()).searchParams.get('name'),zero=name==='NoSuchSyntheticName',cached=saved.has(name)&&!outdated&&new URL(r.request().url()).searchParams.get('retryInterrupted')!=='true';return r.fulfill({json:{quote:{allowed:allowed&&remaining>=1,entitled:allowed,name:'Verify name',cost:1,remaining,renewal:'2026-12-01T00:00:00Z',message:!allowed?'This operation requires an AI-enabled subscription.':remaining<1?'Insufficient monthly AI credits.':'',upgradeUrl:'/ManageAccount/Subscription'},planToken:allowed?'synthetic-plan:'+name:null,cached,requiresAi:!zero,textualMatches:zero?0:3,matchesExact:true,plannedContexts:zero?0:3,plannedMatches:zero?0:3,complete:true,summary:cached?'Saved verification reused. No AI request or credits required.':zero?'No textual matches. No AI request or credits required.':'3 textual matches across 2 saved books; 3 focused contexts will be examined. This bounded operation costs 1 credit.'}});});
|
|
await page.route('**/NameVerification/Execute',async r=>{const body=r.request().postDataJSON();assert(r.request().headers().requestverificationtoken);calls.execute.push(body);const name=body.planToken.split(':').slice(1).join(':');saved.add(name);if(interrupted)await new Promise(resolve=>setTimeout(resolve,250));interrupted=false;return r.fulfill({json:{nameVerificationID:77,processing:false,cached:false,complete:true}});});
|
|
for(const action of ['Result','Textual','Findings'])await page.route(`**/NameVerification/${action}?*`,async r=>{if(action==='Textual')calls.textual++;const u=new URL(r.request().url());u.searchParams.set('outdated',String(outdated));u.searchParams.set('interrupted',String(interrupted));u.searchParams.set('zero',String(u.searchParams.get('name')==='NoSuchSyntheticName'));await r.fulfill({response:await page.request.get(base+'/name-verification-fixture/'+action.toLowerCase()+'?'+u.searchParams)});});
|
|
await page.goto(base+'/names-workspace-fixture/page');await page.locator('[name=Search]').fill('Rose');await page.locator('[data-names-inspect]').click();await page.locator('[data-name-details-fragment]').waitFor();assert((await page.locator('[data-name-details-fragment]').innerText()).includes('Available:'));assert.equal(calls.estimate,0);assert.equal(calls.textual,0);
|
|
await page.locator('[data-name-textual]').click();await page.locator('[data-name-textual-fragment]').waitFor();assert.equal(calls.textual,1);assert((await page.locator('[data-name-textual-fragment]').innerText()).includes('not confirmed character appearances'));assert.equal(calls.execute.length,0);
|
|
allowed=false;await page.locator('[data-name-verify]').click();await page.locator('.pd-ai-confirm').waitFor();assert((await page.locator('.pd-ai-confirm').innerText()).includes('AI-enabled subscription'));await page.keyboard.press('Escape');assert.equal(calls.execute.length,0);
|
|
allowed=true;remaining=0;await page.locator('[data-name-verify]').click();await page.locator('.pd-ai-confirm').waitFor();assert((await page.locator('.pd-ai-confirm').innerText()).includes('Insufficient'));await page.keyboard.press('Escape');assert.equal(calls.execute.length,0);
|
|
remaining=5;await page.locator('[data-name-verify]').click();await page.locator('.pd-ai-confirm').waitFor();assert((await page.locator('.pd-ai-confirm').innerText()).includes('3 textual matches across 2'));await page.getByRole('button',{name:'Cancel',exact:true}).click();assert.equal(calls.execute.length,0);
|
|
await page.locator('[data-name-verify]').click();await page.getByRole('button',{name:'Continue · 1 credit',exact:true}).click();await page.locator('[data-name-verification-fragment][data-verification-id="77"]').waitFor();assert.equal(calls.execute.length,1);assert.equal(calls.execute[0].expectedCredits,1);assert.match(calls.execute[0].requestID,/^[a-f0-9-]{36}$/i);assert.equal(await page.locator('[data-name-verification-findings] .names-occurrence').count(),2);assert((await page.locator('[data-name-verification-fragment]').innerText()).includes('3 examined'));assert((await page.locator('[data-name-details-fragment]').innerText()).includes('Available:'));
|
|
await page.locator('[data-name-verify]').click();await page.waitForTimeout(150);assert.equal(calls.execute.length,1,'cache reuse makes no new execution');
|
|
fs.mkdirSync('/tmp/pd-name-verification',{recursive:true});for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';},theme);await page.screenshot({path:`/tmp/pd-name-verification/${installed?'pwa':'browser'}-${theme}.png`});}
|
|
for(const width of [1280,1920,2560,3840,1366,768,390]){await page.setViewportSize({width,height:1080});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));}
|
|
await page.setViewportSize({width:1920,height:1080});outdated=true;await page.locator('[data-names-inspect]').click();await page.getByText(/Potentially out of date:/).waitFor();assert.equal(calls.execute.length,1);outdated=false;
|
|
interrupted=true;await page.locator('[data-names-inspect]').click();await page.getByRole('button',{name:'✦ Retry interrupted verification…',exact:true}).waitFor();assert((await page.locator('[data-name-verification-fragment]').innerText()).includes('1 examined'));await page.getByRole('button',{name:'✦ Retry interrupted verification…',exact:true}).click();await page.getByRole('button',{name:'Continue · 1 credit',exact:true}).click();assert((await page.locator('[data-name-verification-fragment]').innerText()).includes('1 examined'));await page.waitForFunction(()=>document.querySelector('[data-name-verification-fragment]')?.textContent.includes('3 examined'));assert.equal(calls.execute.length,2);
|
|
await page.locator('[name=Search]').fill('NoSuchSyntheticName');await page.locator('[data-names-inspect]').click();await page.locator('[data-name-details-fragment] h2').filter({hasText:'NoSuchSyntheticName'}).waitFor();remaining=0;await page.locator('[data-name-verify]').click();await page.waitForFunction(()=>document.querySelector('[data-name-verification-fragment][data-verification-id]')?.textContent.includes('0 examined'));assert.equal(calls.execute.at(-1).expectedCredits,0);assert.equal(await page.locator('.pd-ai-confirm').count(),0);
|
|
await page.goto(base+'/Writing/Context?pinned=true');await page.locator('[data-context-tab]').first().selectOption('names');const pane=page.locator('[data-context-pane="0"]');await pane.locator('[name=Search]').fill('Rose');await pane.locator('[data-names-inspect]').click();await pane.locator('[data-name-verification-fragment][data-verification-id="77"]').waitFor();const position=await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position),before=calls.execute.length;await pane.locator('[data-name-verify]').click();await page.waitForTimeout(100);assert.equal(calls.execute.length,before,'Context reuses the shared saved result');
|
|
await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate({kind:'names',projectId:7}));await pane.locator('[data-name-verification-fragment][data-verification-id="77"]').waitFor();assert.equal(await pane.locator('[name=Search]').inputValue(),'Rose');assert.deepEqual(await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position),position);assert.equal(await page.evaluate(()=>contextConnections.filter(c=>c.url==='/hubs/native-companion').length),1);
|
|
for(const width of [2560,768,390]){await page.setViewportSize({width,height:1080});assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await page.screenshot({path:`/tmp/pd-name-verification/context-${installed?'pwa':'browser'}-${width}.png`});}
|
|
assert.deepEqual(errors,[]);console.log('PASS explicit name verification: deferred textual lookup, restrictions/allowance, scope+cost/cancel, qualified findings, no usage reassignment, cache reuse, stale state, zero-credit no-match, themes and Held Context reuse without focus or extra connections');
|
|
}finally{if(installed){await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await persistent.close();fs.rmSync(profile,{recursive:true,force:true});}else await browser.close();}
|
|
})().catch(error=>{console.error(error);process.exitCode=1;});
|