READ-ONLY PACKAGE PREVIEW

router-query/examples/run_fixture.mjs

Version 663282b0ebbc.bb1 · MIT. This preview displays packaged text and does not execute code. Treat the contents as untrusted instructions.

← Return to resource and package checksum

import './deny_network.mjs';
import { networkAttempts } from './deny_network.mjs';
import { readFile, writeFile } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import assert from 'node:assert/strict';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { QueryClient, QueryObserver, QueryClientProvider } from '@tanstack/react-query';
import { RouterProvider, createMemoryHistory } from '@tanstack/react-router';
import { attachRouterServerSsrUtils } from '@tanstack/router-core/ssr/server';

const checks=[],clients=[],routers=[],syntheticRequests=[],unhandled=[];
process.on('unhandledRejection',reason=>unhandled.push(String(reason)));
const check=(id,condition,evidence={})=>{assert.ok(condition,id);checks.push({id,passed:true,evidence});};
const tick=()=>new Promise(r=>setTimeout(r,0));
const deferred=()=>{let resolve,reject;const promise=new Promise((a,b)=>{resolve=a;reject=b;});return{promise,resolve,reject};};
const bounded=async(p,label)=>{let timer;try{return await Promise.race([p,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('Guard timeout: '+label)),4000);})]);}finally{clearTimeout(timer);}};
const q=()=>{const client=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:Infinity}}});clients.push(client);return client;};
const native=async(name)=>import(`../output/modules/${name}.mjs`);
let payload=[{id:'alpha',title:'Synthetic Alpha'}],responseStatus=200,failFetch=false;
globalThis.fetch=async(url)=>{
 if(typeof url!=='string'||!(url==='/api/posts'||/^\/api\/posts\/[a-z]+$/.test(url))) {networkAttempts.push({method:'synthetic-fetch-rejected'});throw Error('Denied non-fixture request');}
 syntheticRequests.push({path:url,status:responseStatus});
 if(failFetch)throw Error('Synthetic transport failure');
 return new Response(JSON.stringify(url==='/api/posts'?payload:{id:url.split('/').at(-1),title:`Synthetic ${url.split('/').at(-1)}`,content:'Fixture content'}),{status:responseStatus,headers:{'Content-Type':'application/json'}});
};
const tracked=(router)=>{routers.push(router);clients.push(router.options.context.queryClient);router.options.context.queryClient?.setDefaultOptions({queries:{retry:false,gcTime:Infinity}});return router;};
const prepareRouter=(router,path)=>{tracked(router);router.update({history:createMemoryHistory({initialEntries:[path]}),isServer:true});attachRouterServerSsrUtils({router,manifest:undefined});return router;};
const render=(router)=>renderToString(React.createElement(RouterProvider,{router}));
let failure;
try{
 const plan=JSON.parse(await readFile('native-extraction-plan.json','utf8'));
 const raw=await readFile('repository-context/'+plan.source_path);
 check('primary-source-sha256-preserved',createHash('sha256').update(raw).digest('hex')===plan.primary_sha256);
 const compilation=JSON.parse(await readFile('native-compilation.json','utf8'));
 check('three-whole-contrast-blocks-rejected',compilation.blocks.filter(x=>x.status==='parse-rejected').map(x=>x.block).join(',')==='10,11,13');
 const labelled=await native('labelled-contrasts');
 check('labelled-loader-fragment-parses-but-exports-no-loader',compilation.blocks.find(x=>x.block===12).status==='transpiled'&&Object.keys(labelled).length===0);
 check('source-install-command-not-executed',compilation.blocks.find(x=>x.block===3).status==='not-executed-source-command');

 const posts=await native('posts'),post=await native('post');
 const cache=q();let start=syntheticRequests.length;
 const first=await posts.Route.options.loader({context:{queryClient:cache}});
 check('static-loader-miss-fetches',syntheticRequests.length===start+1&&first[0].title==='Synthetic Alpha');
 payload=[{id:'alpha',title:'Changed synthetic value'}];
 const second=await posts.Route.options.loader({context:{queryClient:cache}});
 check('static-loader-hit-reuses-cache',syntheticRequests.length===start+1&&second[0].title==='Synthetic Alpha');
 await cache.invalidateQueries({queryKey:['posts'],refetchType:'none'});
 const third=await posts.Route.options.loader({context:{queryClient:cache}});
 check('static-loader-after-invalidation-still-reuses-cache',syntheticRequests.length===start+1&&third[0].title==='Synthetic Alpha');
 const observer=new QueryObserver(cache,{...posts.postsQueryOptions,staleTime:Infinity,retry:false,gcTime:Infinity});
 const stop=observer.subscribe(()=>{});
 await tick();
 check('nonstatic-observer-mount-refetches-invalidated-cache',syntheticRequests.length===start+2&&cache.getQueryData(['posts'])[0].title==='Changed synthetic value');
 payload=[{id:'alpha',title:'Active refreshed synthetic value'}];start=syntheticRequests.length;
 await cache.invalidateQueries({queryKey:['posts']});
 check('active-nonstatic-observer-refetches',syntheticRequests.length===start+1&&cache.getQueryData(['posts'])[0].title==='Active refreshed synthetic value');
 stop();observer.destroy();
 const staticObserver=new QueryObserver(cache,{...posts.postsQueryOptions,staleTime:'static',retry:false,gcTime:Infinity});
 const stopStatic=staticObserver.subscribe(()=>{});start=syntheticRequests.length;
 await cache.invalidateQueries({queryKey:['posts']});
 check('static-observer-invalidation-does-not-refetch',syntheticRequests.length===start);stopStatic();staticObserver.destroy();
 const html=renderToString(React.createElement(QueryClientProvider,{client:cache},React.createElement(posts.PostsPage)));
 check('original-posts-component-renders-cached-query',html.includes('<li>Active refreshed synthetic value</li>'));
 const dynamic=q();start=syntheticRequests.length;
 const a=await post.Route.options.loader({context:{queryClient:dynamic},params:{postId:'alpha'}});
 const b=await post.Route.options.loader({context:{queryClient:dynamic},params:{postId:'beta'}});
 check('dynamic-parameters-have-separate-query-keys',a.id==='alpha'&&b.id==='beta'&&dynamic.getQueryCache().getAll().length===2);
 await post.Route.options.loader({context:{queryClient:dynamic},params:{postId:'alpha'}});
 check('dynamic-repeat-reuses-only-matching-key',syntheticRequests.length===start+2);

 // This response-status observation is a limitation in the unchanged queryFn.
 const statusClient=q();responseStatus=503;payload=[{id:'alpha',title:'JSON body from synthetic 503'}];
 const statusData=await posts.Route.options.loader({context:{queryClient:statusClient}});
 check('original-fetch-does-not-check-response-ok',statusData[0].title==='JSON body from synthetic 503'&&statusClient.getQueryState(['posts']).status==='success',{synthetic_http_status:503,production_http_tested:false});responseStatus=200;
 const errors=await native('errors');const errorClient=q();failFetch=true;
 await assert.rejects(errors.Route.options.loader({context:{queryClient:errorClient}}),/Synthetic transport failure/);
 check('original-error-loader-propagates-transport-rejection',errorClient.getQueryState(['posts']).status==='error');failFetch=false;

 const safe=await native('factory');const r1=tracked(safe.createAppRouter()),r2=tracked(safe.createAppRouter());
 check('original-ssr-factory-creates-distinct-clients',r1.options.context.queryClient!==r2.options.context.queryClient);
 r1.options.context.queryClient.setQueryData(['synthetic-member'],{name:'Synthetic A'});
 check('original-ssr-factory-does-not-share-synthetic-cache',r2.options.context.queryClient.getQueryData(['synthetic-member'])===undefined,{real_authentication_tested:false});
 const shared=await native('shared-factory');const s1=tracked(shared.createAppRouter()),s2=tracked(shared.createAppRouter());
 s1.options.context.queryClient.setQueryData(['synthetic-member'],{name:'Synthetic A'});
 check('wrong-module-singleton-shares-client',s1.options.context.queryClient===s2.options.context.queryClient);
 check('wrong-module-singleton-exposes-synthetic-cache',s2.options.context.queryClient.getQueryData(['synthetic-member']).name==='Synthetic A',{real_authentication_tested:false});
 const fresh=await native('fresh-factory');const f1=tracked(fresh.createAppRouter()),f2=tracked(fresh.createAppRouter());
 check('correct-contrast-factory-creates-distinct-clients',f1.options.context.queryClient!==f2.options.context.queryClient);
 const manual=await native('manual');const m1=tracked(manual.createAppRouter()),m2=tracked(manual.createAppRouter());
 m1.options.context.queryClient.setQueryData(['roundtrip'],{label:'Synthetic hydration value'});
 const state=m1.options.dehydrate();m2.options.hydrate(state);
 check('manual-original-dehydrate-hydrate-roundtrip',m2.options.context.queryClient.getQueryData(['roundtrip']).label==='Synthetic hydration value');
 check('manual-hydration-keeps-client-identity-separate',m1.options.context.queryClient!==m2.options.context.queryClient);

 const dashboard=await native('dashboard');const critical=deferred(),analytics=deferred();globalThis.__bbUser=()=>critical.promise;globalThis.__bbAnalytics=()=>analytics.promise;
 const dc=q();let settled=false;const dp=dashboard.Route.options.loader({context:{queryClient:dc}}).then(v=>{settled=true;return v;});await tick();
 check('dashboard-loader-waits-for-critical-user',!settled&&dc.getQueryState(['user']).status==='pending');
 critical.resolve({name:'Synthetic Reader'});await bounded(dp,'dashboard critical data');
 check('dashboard-loader-does-not-await-analytics',settled&&dc.getQueryState(['analytics']).status==='pending');
 const dashHtml=renderToString(React.createElement(QueryClientProvider,{client:dc},React.createElement(dashboard.Dashboard)));
 check('original-dashboard-renders-user-and-skeleton',dashHtml.includes('Synthetic Reader')&&dashHtml.includes('Loading analytics'));
 analytics.reject(Error('Synthetic optional analytics failure'));await tick();
 check('background-analytics-rejection-is-handled',dc.getQueryState(['analytics']).status==='error'&&unhandled.length===0);
 const awaited=await native('awaited-loader');let gate=deferred();globalThis.__bbAnalytics=()=>gate.promise;settled=false;
 const aq=q();const ap=awaited.fixture.loader({context:{queryClient:aq}}).then(()=>{settled=true;});await tick();
 check('awaited-contrast-blocks-until-optional-query-settles',!settled);gate.resolve({value:'synthetic analytics'});await bounded(ap,'awaited analytics');check('awaited-contrast-resumes-after-resolution',settled);
 const background=await native('background-loader');gate=deferred();globalThis.__bbAnalytics=()=>gate.promise;const bq=q();
 const returnValue=background.fixture.loader({context:{queryClient:bq}});await tick();
 check('background-contrast-returns-before-resolution',returnValue===undefined&&bq.getQueryState(['analytics']).status==='pending');
 gate.reject(Error('Synthetic background failure'));await tick();check('background-contrast-catches-rejection',bq.getQueryState(['analytics']).status==='error'&&unhandled.length===0);
 const required=await native('critical-loader');gate=deferred();globalThis.__bbCritical=()=>gate.promise;const cq=q();settled=false;
 const cp=required.fixture.loader({context:{queryClient:cq}}).then(value=>{settled=true;return value;});await tick();check('critical-contrast-returns-blocking-promise',!settled);gate.resolve({value:'Critical fixture'});
 check('critical-contrast-resolves-required-data',(await bounded(cp,'required data')).value==='Critical fixture');

 const wrongRoot=await native('wrong-root'),correctRoot=await native('correct-root');
 check('wrong-root-call-produces-factory-function',typeof wrongRoot.rootRoute==='function'&&typeof wrongRoot.rootRoute.addChildren==='undefined');
 check('correct-root-double-call-produces-route',typeof correctRoot.rootRoute.addChildren==='function',{full_typecheck:false});
 const basic=await native('basic');prepareRouter(basic.router,'/posts');payload=[{id:'alpha',title:'SSR <script>synthetic</script>'}];
 await bounded(basic.router.load(),'original basic SSR load');const basicHtml=renderToString(React.createElement(basic.App));
 check('original-basic-app-renders-through-real-router',basicHtml.includes('SSR &lt;script&gt;synthetic&lt;/script&gt;'),{server_render_only:true});
 check('react-escapes-synthetic-html-title',!basicHtml.includes('<script>synthetic</script>'));
 const dynamicRouter=prepareRouter(safe.createAppRouter(),'/posts/beta');await bounded(dynamicRouter.load(),'dynamic SSR load');
 check('original-dynamic-route-renders-real-params',render(dynamicRouter).includes('<article>Synthetic beta</article>'));
 const integration=await native('integration');const ir=prepareRouter(integration.createAppRouter(),'/posts');payload=[{id:'alpha',title:'SSR integration fixture'}];await bounded(ir.load(),'SSR integration load');
 check('original-ssr-integration-installs-provider',render(ir).includes('SSR integration fixture'));
 check('original-ssr-integration-installs-native-callbacks',typeof ir.options.dehydrate==='function'&&Array.isArray(ir.serverSsrLifecycle.onServerSsrAttach));
 const dehydrated=await ir.options.dehydrate();
 check('native-integration-dehydrates-initial-query',dehydrated.query.initial.some(x=>x.queryKey[0]==='posts'&&x.state.data[0].title==='SSR integration fixture'));
 check('native-integration-provides-readable-stream',dehydrated.query.stream instanceof ReadableStream);
 const streamGate=deferred();const late=ir.options.context.queryClient.query({queryKey:['late-fixture'],queryFn:()=>streamGate.promise});
 const reader=dehydrated.query.stream.getReader();let readSettled=false;const read=reader.read().then(value=>{readSettled=true;return value;});await tick();
 check('native-integration-no-chunk-before-late-resolution',!readSettled&&ir.options.context.queryClient.getQueryState(['late-fixture']).status==='pending');
 streamGate.resolve({label:'Late fixture data'});await bounded(late,'late native query');
 const chunk=await bounded(read,'SSR native resolved-query stream');
 check('native-integration-streams-resolved-query',!chunk.done&&chunk.value.some(x=>x.queryKey[0]==='late-fixture'));
 const streamed=chunk.value.find(x=>x.queryKey[0]==='late-fixture');
 check('streamed-query-contains-resolved-native-data',streamed.state.data.label==='Late fixture data',{http_transport_and_browser_hydration_tested:false});
 ir.serverSsr.setRenderFinished();
 check('native-render-finished-closes-query-stream',(await bounded(reader.read(),'native render-finished close')).done===true);
 reader.releaseLock();
 // Native cleanup is inspected and invoked below, rather than mocked.
 check('native-server-ssr-has-cleanup',typeof ir.serverSsr.cleanup==='function');
 ir.serverSsr.cleanup();
 check('native-integration-cleanup-clears-request-cache',ir.options.context.queryClient.getQueryCache().getAll().length===0);
 await tick();check('no-unhandled-promise-rejections',unhandled.length===0);
 check('zero-js-network-attempts',networkAttempts.length===0,{os_level_network_audit:false});
}catch(error){failure={name:error.name,message:error.message,stack:error.stack};}
finally{
 for(const router of routers){try{router.serverSsr?.cleanup?.();}catch{}}
 for(const client of new Set(clients)){try{client?.clear();}catch{}}
}
const result={checked_at:new Date().toISOString(),node:process.version,phase:'native-local-fixture',passed:!failure,observations:checks,observation_count:checks.length,synthetic_requests:syntheticRequests,network_attempts:networkAttempts,unhandled_rejections:unhandled,failure,limits:{full_ai_client_execution:false,full_typecheck:false,browser_execution:false,real_authentication:false,production_database:false,http_stream_transport:false,browser_hydration:false,performance_benchmark:false,os_level_network_audit:false},source_command_executed:false};
await writeFile('native-runtime-results.json',JSON.stringify(result,null,2)+'\n');
console.log(JSON.stringify({passed:result.passed,observations:checks.length,synthetic_requests:syntheticRequests.length,js_network_attempts:networkAttempts.length,failure:failure?.message}));
if(failure)process.exitCode=1;