@smart-cloud/publisher-exporter 1.1.45 → 1.1.47
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/dist/content-sync.js +8 -8
- package/dist/crawl.js +6 -6
- package/dist/invalidate.js +2 -2
- package/package.json +5 -2
package/dist/content-sync.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import A from'fs/promises';import es from'http';import Rn from'https';import S from'path';import zn,{createHash}from'crypto';import {request,chromium}from'playwright';import {gunzipSync}from'zlib';import Rs from'fast-glob';import {availableParallelism}from'os';import {Worker}from'worker_threads';import {S3Client,ListObjectsV2Command,HeadObjectCommand,GetObjectCommand,DeleteObjectsCommand}from'@aws-sdk/client-s3';import {Upload}from'@aws-sdk/lib-storage';import Do from'mime-types';import {CloudFrontClient,waitUntilInvalidationCompleted,CreateInvalidationCommand}from'@aws-sdk/client-cloudfront';var Gr=new Set(["post-type","taxonomy","author","date","posts-page","listing"]);function be(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function Zr(e){return new URL(e).pathname.split("/").filter(Boolean).some(n=>{try{return decodeURIComponent(n).endsWith("__trashed")}catch{return n.endsWith("__trashed")}})}function At(e){return Array.isArray(e)?e.map(At):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,At(n)])):e}function Yr(e){return JSON.stringify(At(e))}function oe(e){return createHash("sha256").update(Yr(e)).digest("hex")}function yn(e){return oe({schemaVersion:1,wordpressFingerprint:e.wordpressFingerprint,targetFingerprint:e.targetFingerprint,sourceOrigin:e.sourceOrigin,sitemapPaths:[...e.sitemapPaths].sort(),blockedPathPrefixes:[...e.blockedPathPrefixes].sort(),assetPathPrefixes:[...e.assetPathPrefixes].sort(),noJavaScriptRenderPathPrefixes:[...e.noJavaScriptRenderPathPrefixes].sort(),urlRewriteMode:e.urlRewriteMode})}function Tt(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`Unsupported source origin protocol: ${t.protocol}`);return t.hash="",t.search="",t.pathname=t.pathname.replace(/\/+$/,""),t.toString().replace(/\/$/,"")}function ge(e,t){let n=new URL(Tt(e)),s=new URL(t,`${n.toString().replace(/\/$/,"")}/`);if(s.origin!==n.origin)throw new Error(`Content-sync URL is outside the source origin: ${t}`);let r=n.pathname.replace(/\/+$/,"");if(r&&s.pathname!==r&&!s.pathname.startsWith(`${r}/`))throw new Error(`Content-sync URL is outside the source site path: ${t}`);return s.hash="",s.toString()}function qe(e){let t=be((e.postTypes??[]).map(s=>String(s).toLowerCase().replace(/[^a-z0-9_-]/g,"")));if(t.length===0)throw new Error("Content-sync requires at least one public post type.");let n=be((e.listingPaths??[]).map(s=>{let r=String(s).trim();if(!r)return "";let i=new URL(r,"https://content-sync.invalid/");if(i.origin!=="https://content-sync.invalid"&&/^https?:\/\//i.test(r))throw new Error("Content-sync listing routes must be same-site paths.");let a=`/${i.pathname.replace(/^\/+|\/+$/g,"")}`;return a==="/"?"/":`${a}/`}));return {postTypes:t,listingPaths:n,includeSubsites:e.includeSubsites===true,includePostTypeArchives:e.includePostTypeArchives!==false,includeTaxonomyArchives:e.includeTaxonomyArchives!==false,includeAuthorArchives:e.includeAuthorArchives===true,includeDateArchives:e.includeDateArchives===true,includePostsPage:e.includePostsPage!==false,includeSitemapChain:e.includeSitemapChain!==false}}function Sn(e,t,n){return oe({schemaVersion:1,sourceOrigin:Tt(e),ruleId:t.trim(),scope:qe(n)})}function Pn(e){return oe({schemaVersion:1,...e})}function bn(e){let t=String(e.siteId??"").trim()||String(e.accountId??"").trim()||Tt(e.sourceOrigin);return `content-sync:${oe({siteIdentity:t,ruleId:e.ruleId.trim(),targetFingerprint:e.targetFingerprint}).slice(0,48)}`}function vn(e){let t=[...e].sort((r,i)=>r.sequence-i.sequence),n=new Map,s=-1;for(let r of t){if(!Number.isSafeInteger(r.sequence)||r.sequence<=s)throw new Error("Content-sync journal events are not strictly ordered.");if(s=r.sequence,!Number.isSafeInteger(r.blogId)||r.blogId<1)throw new Error("Content-sync journal event has an invalid multisite identity.");let i=`${r.blogId}:${r.postType}:${r.postId}`,a=n.get(i);if(!a){n.set(i,{postId:r.postId,blogId:r.blogId,postType:r.postType,fromSequence:r.sequence,toSequence:r.sequence,before:r.before,after:r.after,operations:[r.operation],correlationIds:r.correlationId?[r.correlationId]:[]});continue}a.toSequence=r.sequence,a.after=r.after,a.operations.push(r.operation),r.correlationId&&!a.correlationIds.includes(r.correlationId)&&a.correlationIds.push(r.correlationId);}return [...n.values()].sort((r,i)=>r.fromSequence-i.fromSequence)}function wn(e){return e?.status==="publish"&&!!e.url}function Xr(e,t){return e==="post-type"?t.includePostTypeArchives:e==="taxonomy"?t.includeTaxonomyArchives:e==="author"?t.includeAuthorArchives:e==="date"?t.includeDateArchives:e==="posts-page"?t.includePostsPage:e==="listing"}function kt(e){let t=qe(e.scope),n=new Map;vn(e.events);for(let s of e.events)for(let r of [s.before,s.after])for(let i of r?.archiveFamilies??[]){if(!Gr.has(i.kind)||!Xr(i.kind,t))continue;let a={...i,url:ge(e.sourceOrigin,i.url)};n.set(`${a.kind}|${a.url}`,a);}for(let s of t.listingPaths){let r=ge(e.sourceOrigin,s);n.set(`listing|${r}`,{kind:"listing",url:r});}return [...n.values()].sort((s,r)=>s.url.localeCompare(r.url))}function Cn(e){let t=qe(e.scope),n=vn(e.events),s=new Set,r=new Set,i=new Map(kt({events:e.events,scope:t,sourceOrigin:e.sourceOrigin}).map(d=>[`${d.kind}|${d.url}`,d]));for(let d of n){let p=d.before,g=d.after,f=wn(p),w=wn(g);w&&g.url&&s.add(ge(e.sourceOrigin,g.url)),f&&p.url&&(!w||p.url!==g.url)&&r.add(ge(e.sourceOrigin,p.url));}let a=new Map(e.resolvedArchiveFamilies.map(d=>[`${d.kind}|${ge(e.sourceOrigin,d.url)}`,{...d,url:ge(e.sourceOrigin,d.url),pageUrls:be(d.pageUrls.map(p=>ge(e.sourceOrigin,p)))}])),c=[...i.entries()].map(([d,p])=>{let g=a.get(d);if(!g)throw new Error(`WordPress did not resolve archive family ${d}.`);return {...p,...g}}).sort((d,p)=>d.url.localeCompare(p.url)),o=be(c.flatMap(d=>d.pageUrls)),u=t.includeSitemapChain?be(e.sitemapUrls.map(d=>ge(e.sourceOrigin,d))):[],l={schemaVersion:1,generatedAt:new Date().toISOString(),jobId:e.jobId,ruleId:e.ruleId,consumerId:e.consumerId,coalesceKey:e.coalesceKey,scopeFingerprint:e.scopeFingerprint,targetFingerprint:e.targetFingerprint,baselineId:e.baselineId,fromSequence:e.fromSequence,toSequence:e.toSequence,eventCount:e.events.length,foldedCount:n.length,directRenderUrls:be([...s]),archiveFamilyUrls:o,sitemapUrls:u,deleteUrls:be([...r]),archiveFamilies:c};return {...l,impactHash:oe(l)}}function _e(e){let{impactHash:t,...n}=e;if(e.schemaVersion!==1||!t)throw new Error("Invalid content-sync impact plan schema.");if(oe(n)!==t)throw new Error("Content-sync impact plan hash mismatch.");for(let s of [...e.directRenderUrls,...e.deleteUrls])if(Zr(s))throw new Error(`Content-sync impact contains a WordPress trash alias instead of the last public URL: ${s}`)}var ts="wp-json/smartcloud-static-publisher/v1/content-sync/",ns=25*1024*1024,et=class extends Error{status;code;constructor(t,n,s){super(s),this.name="ContentSyncApiError",this.status=t,this.code=n;}},tt=class{options;constructor(t){if(!t.runtimeToken.trim())throw new Error("Content-sync requires a WordPress runtime token.");this.options={...t,timeoutMs:t.timeoutMs??6e4};}endpoint(t){let n=this.options.sourceOrigin.replace(/\/+$/,"")+"/";return new URL(`${ts}${t}`,n)}async post(t,n){let s=this.endpoint(t),r=Buffer.from(JSON.stringify(n),"utf8"),i=s.protocol==="https:"?Rn:es,a=s.protocol==="https:"?new Rn.Agent({rejectUnauthorized:!this.options.ignoreHttpsErrors}):void 0;return new Promise((c,o)=>{let u=i.request(s,{method:"POST",agent:a,headers:{"content-type":"application/json","content-length":String(r.byteLength),"x-static-publisher-token":this.options.runtimeToken},timeout:this.options.timeoutMs},l=>{let d=[],p=0;l.on("data",g=>{if(p+=g.byteLength,p>ns){l.destroy(new Error("Content-sync API response exceeded the size limit."));return}d.push(g);}),l.on("error",o),l.on("end",()=>{let g=Buffer.concat(d).toString("utf8"),f;try{f=g?JSON.parse(g):{};}catch{o(new et(l.statusCode??500,"invalid-json","Content-sync API returned invalid JSON."));return}let w=l.statusCode??500;if(w<200||w>=300){o(new et(w,String(f.code??"request-failed"),String(f.message??`Content-sync API request failed (${w}).`)));return}c(f);});});u.on("timeout",()=>u.destroy(new Error(`Content-sync API request timed out: ${t}`))),u.on("error",o),u.end(r);})}async head(t){return this.post("head",t)}async unboundHead(t,n){return this.post("head",{postTypes:t,includeSubsites:n})}async events(t){let n=[],s=t.afterSequence,r=new Set(t.postTypes);for(;s<t.throughSequence;){let i=await this.post("events",{...t,afterSequence:s,limit:250});if(i.fromSequence!==s||i.throughSequence!==t.throughSequence||i.nextSequence<s||i.nextSequence>t.throughSequence)throw new Error("Content-sync API returned an inconsistent event page.");if(!Array.isArray(i.items))throw new Error("Content-sync API returned a malformed event page.");let a=s;for(let c of i.items){if(!Number.isSafeInteger(c.sequence)||c.sequence<=a||c.sequence>t.throughSequence||!Number.isSafeInteger(c.postId)||c.postId<=0||!Number.isSafeInteger(c.blogId)||c.blogId<=0||!r.has(c.postType)||typeof c.operation!="string"||!c.operation)throw new Error("Content-sync API returned an invalid or out-of-scope journal event.");a=c.sequence;}if(i.items.length>0&&i.nextSequence!==a)throw new Error("Content-sync API event cursor does not match the final returned event.");if(n.push(...i.items),!i.hasMore)break;if(i.nextSequence===s)throw new Error("Content-sync API event pagination did not advance.");s=i.nextSequence;}if(t.throughSequence>t.afterSequence&&n.at(-1)?.sequence!==t.throughSequence)throw new Error("Content-sync API omitted the claimed journal high-water event.");return n}async resolveImpactFamilies(t,n){let s=await this.post("impact",{families:t,includeSubsites:n});return Array.isArray(s.families)?s.families:[]}async releaseFingerprint(t=false){let n=await this.post("fingerprint",{includeSubsites:t}),s=String(n.fingerprint||"").trim();if(!/^[a-f0-9]{64}$/.test(s))throw new Error("WordPress returned an invalid release fingerprint.");return s}async establishBaseline(t){return this.post("baseline",t)}async acknowledge(t){return this.post("ack",t)}};function nt(e){let t=S.resolve(e);return {state:S.join(t,"content-sync-state.json"),current:S.join(t,"content-sync-current.json"),impact:S.join(t,"content-sync-impact-plan.json"),checkpoint:S.join(t,"content-sync-checkpoint.json"),baseline:S.join(t,"content-sync-baseline.json"),releaseCutoff:S.join(t,"content-sync-release-cutoff.json"),candidateManifest:S.join(t,"content-sync-candidate-manifest.json"),trustedManifest:S.join(t,"crawl-manifest.json"),invalidation:S.join(t,"content-sync-invalidation.json"),deployPlan:S.join(t,"deploy-plan.json")}}async function $t(e){let t=await Ne(e.releaseCutoff);if(t===null)return {schemaVersion:1,updatedAt:"",entries:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.entries||typeof n.entries!="object"||Array.isArray(n.entries))throw new Error("Invalid content-sync release-cutoff store.");return n}async function In(e,t){await Ae(e.releaseCutoff,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Ae(e,t){await A.mkdir(S.dirname(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await A.writeFile(n,JSON.stringify(t,null,2),"utf8"),await A.rename(n,e);}async function Ne(e){try{return JSON.parse(await A.readFile(e,"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw new Error(`Invalid or unreadable content-sync state file ${e}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async function Et(e){let t=await Ne(e.baseline);if(t===null)return {schemaVersion:1,updatedAt:"",entries:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.entries||typeof n.entries!="object"||Array.isArray(n.entries))throw new Error("Invalid content-sync baseline store.");return n}async function xn(e,t){await Ae(e.baseline,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Mt(e){let t=await Ne(e.current);if(t===null)return null;let n=t;if(n.schemaVersion!==1||typeof n.jobId!="string"||typeof n.phase!="string"||!Number.isSafeInteger(n.fromSequence)||!Number.isSafeInteger(n.toSequence))throw new Error("Invalid content-sync current-range state.");return n}async function An(e,t){await Ae(e.current,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Tn(e){let t=await Ne(e.impact);if(t===null)return null;let n=t;return _e(n),n}async function kn(e,t){_e(t),await Ae(e.impact,t);}async function $n(e,t){await Ae(e.checkpoint,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function rt(e){let t=await Ne(e.state);if(t===null)return {schemaVersion:1,updatedAt:"",rules:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.rules||typeof n.rules!="object"||Array.isArray(n.rules))throw new Error("Invalid content-sync state store.");return n}async function st(e,t){await Ae(e.state,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Ft(e){await Promise.all([e.current,e.checkpoint].map(async t=>{try{await A.unlink(t);}catch(n){if(n.code!=="ENOENT")throw n}}));}async function En(e,t){let n=await Mt(e);return !n||n.coalesceKey!==t?false:(await Promise.all([e.current,e.checkpoint,e.impact,e.candidateManifest,e.invalidation,e.deployPlan].map(async s=>{try{await A.unlink(s);}catch(r){if(r.code!=="ENOENT")throw r}})),true)}function Fn(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function os(e){let t=String(e??"").trim();if(!t)return "";let n=t;if(/^https?:\/\//i.test(n))try{n=new URL(n).pathname;}catch{return ""}if(n=n.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!n)return "";let s=n.endsWith("/"),r=n.replace(/^\/+/,"").split("/").map(a=>a.replace(/[^A-Za-z0-9._-]/g,"")).filter(a=>a.length>0&&a!=="."&&a!=="..");if(r.length===0)return "";let i=`/${r.join("/")}`;return s&&S.extname(i)===""&&(i+="/"),i==="/"?"":i}function Dt(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[t.trim(),String(n??"")]).filter(([t])=>t.length>0))}function as(e){if(!e||typeof e!="object")return {};let t={};for(let[n,s]of Object.entries(e)){let r=n.trim();if(!r||!s||typeof s!="object")continue;let i=s,a={};if(typeof i.targetOrigin=="string"){let o=Fn(i.targetOrigin);o&&(a.targetOrigin=o);}let c=Dt(i.extraReplacements);if(Object.keys(c).length>0&&(a.extraReplacements=c),i.s3&&typeof i.s3=="object"){let o={},u=i.s3;typeof u.bucket=="string"&&(o.bucket=u.bucket.trim()),typeof u.prefix=="string"&&(o.prefix=u.prefix.trim()),typeof u.region=="string"&&(o.region=u.region.trim()),typeof u.htmlCacheControl=="string"&&(o.htmlCacheControl=u.htmlCacheControl.trim()),typeof u.assetCacheControl=="string"&&(o.assetCacheControl=u.assetCacheControl.trim()),Object.keys(o).length>0&&(a.s3=o);}if(i.cloudFront&&typeof i.cloudFront=="object"){let o={},u=i.cloudFront;typeof u.distributionId=="string"&&(o.distributionId=u.distributionId.trim()),Array.isArray(u.invalidationPaths)&&(o.invalidationPaths=u.invalidationPaths.map(l=>String(l??"").trim()).filter(l=>l.length>0)),Object.keys(o).length>0&&(a.cloudFront=o);}t[r]=a;}return t}function jt(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function cs(e,t){if(!e||typeof e!="object")return null;let n=e,s=n.command;if(s!=="publish"&&s!=="crawl"&&s!=="deploy"&&s!=="invalidate"&&s!=="retry-timeouts"&&s!=="url"&&s!=="content-sync")return null;let r=Number.parseInt(String(n.intervalMinutes??"0"),10);if(!Number.isFinite(r)||r<1)return null;let i=String(n.id??`${s}-${t+1}`).trim();if(!i)return null;let a=String(n.deploymentProfile??"").trim(),c=String(n.url??"").trim(),o=Array.isArray(n.postTypes)?[...new Set(n.postTypes.map(l=>String(l??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],u=Array.isArray(n.listingPaths)?[...new Set(n.listingPaths.map(l=>String(l??"").trim()).filter(Boolean))]:[];return s==="content-sync"&&o.length===0?null:{id:i,enabled:n.enabled!==false,command:s,intervalMinutes:r,...s==="publish"||s==="crawl"?{crawlMode:n.crawlMode==="incremental"?"incremental":"full"}:{},...(s==="publish"||s==="deploy"||s==="invalidate"||s==="content-sync")&&a?{deploymentProfile:a}:{},...c?{url:c}:{},...o.length>0?{postTypes:o}:{},...u.length>0?{listingPaths:u}:{},...typeof n.includeSubsites=="boolean"?{includeSubsites:n.includeSubsites}:{},...typeof n.includePostTypeArchives=="boolean"?{includePostTypeArchives:n.includePostTypeArchives}:{},...typeof n.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:n.includeTaxonomyArchives}:{},...typeof n.includeAuthorArchives=="boolean"?{includeAuthorArchives:n.includeAuthorArchives}:{},...typeof n.includeDateArchives=="boolean"?{includeDateArchives:n.includeDateArchives}:{},...typeof n.includePostsPage=="boolean"?{includePostsPage:n.includePostsPage}:{},...typeof n.includeSitemapChain=="boolean"?{includeSitemapChain:n.includeSitemapChain}:{}}}function Dn(e){let t=e&&typeof e=="object"?e:{},n=Array.isArray(t.rules)?t.rules.map((s,r)=>cs(s,r)).filter(s=>!!s):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:n}}function us(e){if(!e||typeof e!="object")return;let t=e,n={};for(let r of ["accountId","siteId"]){let i=t[r];typeof i=="string"&&i.trim()!==""&&(n[r]=i.trim());}let s=Number(t.lastUpdate??0);return Number.isFinite(s)&&s>0&&(n.lastUpdate=Math.floor(s)),t.subscriber===true&&(n.subscriber=true),Object.keys(n).length>0?n:void 0}function Ut(e){let t=e&&typeof e=="object"?e:{},n=String(t.accountId??"").trim(),s=String(t.siteId??"").trim(),r=t.subscriber===true,i=us(t.siteSettings),a={...i??{},...n?{accountId:i?.accountId??n}:{},...s?{siteId:i?.siteId??s}:{},...i?.subscriber===true||r?{subscriber:true}:{}},c={},o=String(t.apiBase??"").trim();o&&(c.apiBase=o);let u=String(t.runtimeToken??t.nonce??"").trim();u&&(c.runtimeToken=u);let l=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();l&&(c.virtualAssetBaseUrl=l),Object.keys(a).length>0&&(c.siteSettings=a);let d=jt(t.subscriptionType);return d&&(c.subscriptionType=d),c}function ls(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function On(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function ds(e,t){let n=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[s,r]of new Headers(t.headers).entries())n.set(s,r);return n}async function jn(e,t,n=5){let s=new URL(On(e)),r=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),i=s.protocol==="http:"?es:Rn,a=ds(e,t);return await new Promise((c,o)=>{let u=i.request(s,{method:r,headers:Object.fromEntries(a.entries()),...s.protocol==="https:"?{rejectUnauthorized:false}:{}},l=>{let d=[];l.on("data",p=>{d.push(Buffer.isBuffer(p)?p:Buffer.from(p));}),l.on("error",o),l.on("end",()=>{let p=l.statusCode??0,g=l.headers.location;if(n>0&&g&&[301,302,303,307,308].includes(p)){c(jn(new URL(g,s),{method:p===303?"GET":r},n-1));return}let f=new Headers;for(let[w,m]of Object.entries(l.headers))Array.isArray(m)?f.set(w,m.join(", ")):typeof m=="string"&&f.set(w,m);c(new Response(Buffer.concat(d),{status:p,statusText:l.statusMessage??"",headers:f}));});});u.on("error",o),u.end();})}function ps(e){let t=Ut(e.wpsuite),n={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},s=String(n.accountId??"").trim(),r=String(n.siteId??"").trim(),i=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...i?{virtualAssetBaseUrl:i}:{},...Object.keys(n).length>0?{siteSettings:n}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!s||!r||!i)return false;ls(e.sourceOrigin);let a=globalThis,o={...a.WpSuite??{},siteSettings:n,uploadUrl:i};return t.apiBase&&(o.apiBase=t.apiBase),a.WpSuite=o,true}async function gs(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!ps(e)){let r=e.wpsuite?.siteSettings,i=[String(r?.accountId??"").trim()?"":"accountId",String(r?.siteId??"").trim()?"":"siteId",t?"":"virtualAssetBaseUrl"].filter(Boolean);return {remote:null,diagnostic:{status:"invalid-runtime",virtualAssetBaseUrl:t,subscriptionType:null,error:`Missing WP Suite runtime field(s): ${i.join(", ")}.`,requests:[]}}}let n=globalThis.fetch,s=[];try{typeof n=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(o,u)=>{let l=On(o);if(l.startsWith(t)){let d=(()=>{try{return new URL(l).pathname}catch{return l}})();try{let p=e.ignoreHttpsErrors&&l.startsWith("https://")?await jn(o,u):await n(o,u);return s.push({path:d,status:p.status,ok:p.ok,error:null}),p}catch(p){throw s.push({path:d,status:null,ok:!1,error:p instanceof Error?p.message:String(p)}),p}}return n(o,u)}));let{getConfig:r}=await import('@smart-cloud/wpsuite-core'),i=await r("publisher"),a=i&&typeof i=="object"?i:null,c=jt(a?.subscriptionType);return {remote:a,diagnostic:{status:a?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:c??null,error:a?null:"WP Suite publisher config loader returned no configuration.",requests:s}}}catch(r){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:r instanceof Error?r.message:String(r),requests:s}}}finally{typeof n=="function"&&(globalThis.fetch=n);}}function fs(e,t){let n=as(t?.deploymentProfiles),s=String(t?.defaultDeploymentProfile??"").trim(),r=n[s]?s:"",i=jt(t?.subscriptionType),a=Ut(e.wpsuite);return {...e,scheduler:Dn(t?.scheduler),deploymentProfiles:n,defaultDeploymentProfile:r,...i?{subscriptionType:i}:{},wpsuite:{...a,...a.siteSettings||i?{siteSettings:{...a.siteSettings??{},...a.siteSettings?.subscriber===true||i==="PROFESSIONAL"||i==="AGENCY"?{subscriber:true}:{}}}:{},...i?{subscriptionType:i}:{}}}}function Ot(e,t){let s=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!s)return t;let r=s.split("/").map(i=>i.trim()).filter(i=>i.length>0&&i!=="."&&i!=="..");return r.length>0?r.join("/"):t}function ms(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function Mn(e,t,n){let s=String(t||"").trim();return s&&S.isAbsolute(s)?S.resolve(s):S.resolve(e,Ot(s,n))}async function ne(e,t={}){let n=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",s=await A.readFile(n,"utf8"),r=JSON.parse(s);r.sourceOrigin=r.sourceOrigin.replace(/\/$/,""),r.targetOrigin=Fn(r.targetOrigin),r.ignoreHttpsErrors??=false,r.outputDir=String(r.outputDir||"export").trim()||"export",r.urlRewriteMode||=r.targetOrigin==="."?"relative":"absolute",r.noJavaScriptRenderPathPrefixes||=[],r.seedPaths||=[],r.generated404RequestPath=os(r.generated404RequestPath),r.sitemapPaths||=["/sitemap_index.xml","/sitemap.xml"],r.allowedAssetHosts||=[],r.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],r.blockedPathPrefixes||=[],r.blockedSearchFragments||=[],r.concurrency||=1,r.maxPages||=0,r.extraReplacements=Dt(r.extraReplacements),r.postCrawlCopyMap=Dt(r.postCrawlCopyMap),r.logDir=String(r.logDir||"logs").trim()||"logs",r.verbose??=false,r.logLevel||=r.verbose?"debug":"info",r.s3SyncMode||="sdk-upload-delete",r.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},r.readiness.timeoutMs??=1500,r.readiness.fallbackWaitMs??=1500,r.viewport||={width:1440,height:1200},r.navigationTimeoutMs||=3e4,r.assetDownloadConcurrency=Number(r.assetDownloadConcurrency)>0?Number(r.assetDownloadConcurrency):r.concurrency,r.rewriteConcurrency=Number(r.rewriteConcurrency)>0?Number(r.rewriteConcurrency):r.assetDownloadConcurrency,r.wpsuite=Ut(r.wpsuite),r.scheduler=Dn(void 0),r.deploymentProfiles={},r.defaultDeploymentProfile="",r.deploymentTargetOverride=String(r.deploymentTargetOverride??"").trim();let i=await gs(r);t.onRemotePublisherConfigDiagnostic?.(i.diagnostic);let a=fs(r,i.remote),c=ms(),o=c?S.resolve(c,".."):"";return o?(a.outputDir=Mn(o,a.outputDir,"export"),a.logDir=Mn(o,a.logDir,"logs")):(S.isAbsolute(a.outputDir)||(a.outputDir=Ot(a.outputDir,"export")),S.isAbsolute(a.logDir)||(a.logDir=Ot(a.logDir,"logs"))),a}var hs=".deploy-plan.json",ws="deploy-plan.json",ys=".crawl-incomplete.json",Ss="crawl-incomplete.json";function Un(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function Ln(e){let t=String(e||"").replace(/\\/g,"/").replace(/^\/+/,"").trim(),n=S.posix.normalize(t);return !t||!n||n==="."||/^[a-zA-Z]:/.test(n)||n.startsWith("../")||n===".."?null:n}function Ps(e){let t=String(e||"").trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("*")||t.includes("#"))return null;try{let n=new URL(t,"https://content-sync.invalid");return n.origin!=="https://content-sync.invalid"?null:`${S.posix.normalize(n.pathname)}${n.search}`}catch{return null}}function me(e){return [...new Set(e.map(Ln).filter(t=>t!==null))]}function qn(e,t){let n={generatedAt:String(t.generatedAt||new Date().toISOString()),outputDir:S.resolve(e.outputDir),runMode:t.runMode,crawlMode:t.crawlMode,fullSyncRequired:!!t.fullSyncRequired,changedFiles:me(t.changedFiles||[]),deletedFiles:me(t.deletedFiles||[]),rewriteTargets:me(t.rewriteTargets||[])};return t.schemaVersion===2?{...n,schemaVersion:2,runMode:"content-sync",crawlMode:"incremental",fullSyncRequired:false,consumerId:String(t.consumerId||"").trim(),fromSequence:Math.max(0,Number(t.fromSequence)||0),toSequence:Math.max(0,Number(t.toSequence)||0),impactHash:String(t.impactHash||"").trim(),uploadGroups:{assets:me(t.uploadGroups?.assets||[]),content:me(t.uploadGroups?.content||[]),listings:me(t.uploadGroups?.listings||[]),sitemapLeaves:me(t.uploadGroups?.sitemapLeaves||[]),sitemapIndexes:me(t.uploadGroups?.sitemapIndexes||[])},invalidationPaths:[...new Set((t.invalidationPaths||[]).map(Ps).filter(s=>s!==null))].sort()}:{schemaVersion:1,...n,runMode:t.runMode}}function bs(e){if(!e||typeof e!="object")return false;let t=e;if(t.schemaVersion===2){let n=t;return n.runMode==="content-sync"&&n.crawlMode==="incremental"&&n.fullSyncRequired===false&&typeof n.generatedAt=="string"&&typeof n.outputDir=="string"&&typeof n.consumerId=="string"&&n.consumerId.trim()!==""&&Number.isSafeInteger(n.fromSequence)&&Number.isSafeInteger(n.toSequence)&&Number(n.toSequence)>=Number(n.fromSequence)&&typeof n.impactHash=="string"&&/^[a-f0-9]{64}$/.test(n.impactHash)&&Array.isArray(n.changedFiles)&&Array.isArray(n.deletedFiles)&&Array.isArray(n.rewriteTargets)&&!!n.uploadGroups&&Array.isArray(n.uploadGroups.assets)&&Array.isArray(n.uploadGroups.content)&&Array.isArray(n.uploadGroups.listings)&&Array.isArray(n.uploadGroups.sitemapLeaves)&&Array.isArray(n.uploadGroups.sitemapIndexes)&&Array.isArray(n.invalidationPaths)}return t.schemaVersion===1&&typeof t.generatedAt=="string"&&typeof t.outputDir=="string"&&(t.runMode==="full"||t.runMode==="retry-timeouts"||t.runMode==="single-url")&&(t.crawlMode==="full"||t.crawlMode==="incremental")&&typeof t.fullSyncRequired=="boolean"&&Array.isArray(t.changedFiles)&&Array.isArray(t.deletedFiles)&&Array.isArray(t.rewriteTargets)}function Lt(e){let t=S.join(S.resolve(e.outputDir),hs),n=Un();return n?[S.join(n,ws),t]:[t]}function qt(e){let t=S.join(S.resolve(e.outputDir),ys),n=Un();return n?[S.join(n,Ss),t]:[t]}function he(e,t){let n=S.resolve(e),s=S.resolve(t),r=S.relative(n,s).replace(/\\/g,"/");return Ln(r)}async function it(e){let t=S.resolve(e.outputDir);for(let n of Lt(e))try{let s=await A.readFile(n,"utf8"),r=JSON.parse(s);if(!bs(r)||S.resolve(r.outputDir)!==t)continue;return qn(e,r)}catch{}return null}async function _t(e,t){let n=qn(e,t);for(let s of Lt(e)){await A.mkdir(S.dirname(s),{recursive:true});let r=`${s}.${process.pid}.${Date.now()}.tmp`;await A.writeFile(r,JSON.stringify(n,null,2),"utf8"),await A.rename(r,s);}}async function Te(e){for(let t of Lt(e))try{await A.unlink(t);}catch(n){if(n.code!=="ENOENT")throw n}}async function _n(e,t){let n={schemaVersion:1,startedAt:String(t.startedAt||new Date().toISOString()),outputDir:S.resolve(e.outputDir)};for(let s of qt(e)){await A.mkdir(S.dirname(s),{recursive:true});let r=`${s}.${process.pid}.tmp`;await A.writeFile(r,JSON.stringify(n,null,2),"utf8"),await A.rename(r,s);}}async function Nn(e){let t=S.resolve(e.outputDir);for(let n of qt(e)){let s;try{s=await A.readFile(n,"utf8");}catch(i){if(i.code==="ENOENT")continue;throw i}let r;try{r=JSON.parse(s);}catch{throw new Error(`Invalid incomplete crawl marker: ${n}`)}if(r.schemaVersion!==1||typeof r.startedAt!="string"||typeof r.outputDir!="string"||S.resolve(r.outputDir)!==t)throw new Error(`Invalid incomplete crawl marker: ${n}`);return {schemaVersion:1,startedAt:r.startedAt,outputDir:t}}return null}async function Bn(e){for(let t of qt(e))try{await A.unlink(t);}catch(n){if(n.code!=="ENOENT")throw n}}function He(e,t=10){return zn.createHash("sha1").update(e).digest("hex").slice(0,t)}async function vs(e){await A.mkdir(S.dirname(e),{recursive:true});}async function We(e,t,n){await vs(e);let s=S.join(S.dirname(e),`.${S.basename(e)}.${process.pid}.${Date.now()}.${zn.randomBytes(6).toString("hex")}.tmp`);try{typeof t=="string"?await A.writeFile(s,t,n??"utf8"):await A.writeFile(s,t),await A.rename(s,e);}catch(r){throw await A.unlink(s).catch(()=>{}),r}}function we(e){return [".html",".htm",".css",".js",".mjs",".json",".xml",".xsl",".txt",".svg",".map",".enc",".jws"].includes(S.extname(e).toLowerCase())}function ce(e){return e.replace(/"/g,'"').replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function ke(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function ot(e){return e.replace(/\//g,"\\/")}function Hn(e){return e.replace(/\//g,"\\\\/")}function Cs(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let n=t.pathname==="/"&&!t.search&&!t.hash?"":`${t.pathname}${t.search}${t.hash}`;return `//${t.host}${n}`}catch{return null}}function Wn(e,t,n){if(!t)return;e[t]=n;let s=ot(t),r=ot(n);e[s]=r;let i=Hn(t),a=Hn(n);e[i]=a;let c=ke(t),o=ke(n);e[c]=o;let u=ke(s),l=ke(r);e[u]=l;let d=ke(i),p=ke(a);e[d]=p;}function at(e,t,n){Wn(e,t,n);let s=Cs(t);s&&s!==t&&Wn(e,s,n);}function Nt(e,t){let n=t.startsWith("/")?t:`/${t}`,s=(e||"").replace(/\/$/,"");return !s||s==="."||s==="/"?n:`${s}${n}`}function Qn(e,t){try{return new URL(e,t==="."?"https://relative.invalid":t).pathname}catch{return e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}}function Jn(e,t,n){if(!t)return n;let s=S.dirname(S.resolve(t)),r=S.resolve(e,n.replace(/^\/+/,"")),i=S.relative(s,r).replace(/\\/g,"/");return i?(i.startsWith(".")||(i=`./${i}`),i):"."}var Ts=["wp-content/","wp-includes/","wp-admin/","wp-json/","_next/"],ks=new Set([".html",".htm"]),Vn="WPSuite.io Static Publisher",$s=Vn.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Es(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ms(e){return e.startsWith("//")||e.startsWith("\\/\\/")||e.startsWith("\\\\/\\\\/")}function Fs(e,t,n){return Ms(t)?e.replace(new RegExp(`(?<!:)${Es(t)}`,"g"),n):e.split(t).join(n)}function Ds(e,t,n){if(e.wpsuite?.siteSettings?.subscriber===true||e.wpsuite?.subscriptionType==="PROFESSIONAL"||e.wpsuite?.subscriptionType==="AGENCY"||!n)return false;let r=S.extname(n).toLowerCase();return ks.has(r)?/<head\b|<html\b|<!doctype html/i.test(t):false}function Os(e){if(new RegExp(`<meta\\b(?=[^>]*\\bname=(["'])generator\\1)(?=[^>]*\\bcontent=(["'])${$s}\\2)[^>]*\\/?>`,"i").test(e))return e;let t=`<meta name="generator" content="${Vn}" />`;if(e.match(/(\r?\n)([ \t]*)<\/head>/i))return e.replace(/(\r?\n)([ \t]*)<\/head>/i,`$1$2${t}$1$2</head>`);let s=e.includes(`\r
|
|
1
|
+
import A from'fs/promises';import ss from'http';import An from'https';import S from'path';import Vn,{createHash}from'crypto';import {request,chromium}from'playwright';import {gunzipSync}from'zlib';import Ts from'fast-glob';import {availableParallelism}from'os';import {Worker}from'worker_threads';import {S3Client,ListObjectsV2Command,HeadObjectCommand,GetObjectCommand,DeleteObjectsCommand}from'@aws-sdk/client-s3';import {Upload}from'@aws-sdk/lib-storage';import Uo from'mime-types';import {CloudFrontClient,waitUntilInvalidationCompleted,CreateInvalidationCommand}from'@aws-sdk/client-cloudfront';var es=new Set(["post-type","taxonomy","author","date","posts-page","listing"]);function Ce(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function ts(e){return new URL(e).pathname.split("/").filter(Boolean).some(n=>{try{return decodeURIComponent(n).endsWith("__trashed")}catch{return n.endsWith("__trashed")}})}function Et(e){return Array.isArray(e)?e.map(Et):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Et(n)])):e}function ns(e){return JSON.stringify(Et(e))}function oe(e){return createHash("sha256").update(ns(e)).digest("hex")}function bn(e){return oe({schemaVersion:1,wordpressFingerprint:e.wordpressFingerprint,targetFingerprint:e.targetFingerprint,sourceOrigin:e.sourceOrigin,sitemapPaths:[...e.sitemapPaths].sort(),blockedPathPrefixes:[...e.blockedPathPrefixes].sort(),assetPathPrefixes:[...e.assetPathPrefixes].sort(),noJavaScriptRenderPathPrefixes:[...e.noJavaScriptRenderPathPrefixes].sort(),urlRewriteMode:e.urlRewriteMode})}function Mt(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`Unsupported source origin protocol: ${t.protocol}`);return t.hash="",t.search="",t.pathname=t.pathname.replace(/\/+$/,""),t.toString().replace(/\/$/,"")}function fe(e,t){let n=new URL(Mt(e)),s=new URL(t,`${n.toString().replace(/\/$/,"")}/`);if(s.origin!==n.origin)throw new Error(`Content-sync URL is outside the source origin: ${t}`);let r=n.pathname.replace(/\/+$/,"");if(r&&s.pathname!==r&&!s.pathname.startsWith(`${r}/`))throw new Error(`Content-sync URL is outside the source site path: ${t}`);return s.hash="",s.toString()}function We(e){let t=Ce((e.postTypes??[]).map(s=>String(s).toLowerCase().replace(/[^a-z0-9_-]/g,"")));if(t.length===0)throw new Error("Content-sync requires at least one public post type.");let n=Ce((e.listingPaths??[]).map(s=>{let r=String(s).trim();if(!r)return "";let i=new URL(r,"https://content-sync.invalid/");if(i.origin!=="https://content-sync.invalid"&&/^https?:\/\//i.test(r))throw new Error("Content-sync listing routes must be same-site paths.");let a=`/${i.pathname.replace(/^\/+|\/+$/g,"")}`;return a==="/"?"/":`${a}/`}));return {postTypes:t,listingPaths:n,includeSubsites:e.includeSubsites===true,includePostTypeArchives:e.includePostTypeArchives!==false,includeTaxonomyArchives:e.includeTaxonomyArchives!==false,includeAuthorArchives:e.includeAuthorArchives===true,includeDateArchives:e.includeDateArchives===true,includePostsPage:e.includePostsPage!==false,includeSitemapChain:e.includeSitemapChain!==false}}function vn(e,t,n){return oe({schemaVersion:1,sourceOrigin:Mt(e),ruleId:t.trim(),scope:We(n)})}function Cn(e){return oe({schemaVersion:1,...e})}function Rn(e){let t=String(e.siteId??"").trim()||String(e.accountId??"").trim()||Mt(e.sourceOrigin);return `content-sync:${oe({siteIdentity:t,ruleId:e.ruleId.trim(),targetFingerprint:e.targetFingerprint}).slice(0,48)}`}function In(e){let t=[...e].sort((r,i)=>r.sequence-i.sequence),n=new Map,s=-1;for(let r of t){if(!Number.isSafeInteger(r.sequence)||r.sequence<=s)throw new Error("Content-sync journal events are not strictly ordered.");if(s=r.sequence,!Number.isSafeInteger(r.blogId)||r.blogId<1)throw new Error("Content-sync journal event has an invalid multisite identity.");let i=`${r.blogId}:${r.postType}:${r.postId}`,a=n.get(i);if(!a){n.set(i,{postId:r.postId,blogId:r.blogId,postType:r.postType,fromSequence:r.sequence,toSequence:r.sequence,before:r.before,after:r.after,operations:[r.operation],correlationIds:r.correlationId?[r.correlationId]:[]});continue}a.toSequence=r.sequence,a.after=r.after,a.operations.push(r.operation),r.correlationId&&!a.correlationIds.includes(r.correlationId)&&a.correlationIds.push(r.correlationId);}return [...n.values()].sort((r,i)=>r.fromSequence-i.fromSequence)}function Pn(e){return e?.status==="publish"&&!!e.url}function rs(e,t){return e==="post-type"?t.includePostTypeArchives:e==="taxonomy"?t.includeTaxonomyArchives:e==="author"?t.includeAuthorArchives:e==="date"?t.includeDateArchives:e==="posts-page"?t.includePostsPage:e==="listing"}function Ft(e){let t=We(e.scope),n=new Map;In(e.events);for(let s of e.events)for(let r of [s.before,s.after])for(let i of r?.archiveFamilies??[]){if(!es.has(i.kind)||!rs(i.kind,t))continue;let a={...i,url:fe(e.sourceOrigin,i.url)};n.set(`${a.kind}|${a.url}`,a);}for(let s of t.listingPaths){let r=fe(e.sourceOrigin,s);n.set(`listing|${r}`,{kind:"listing",url:r});}return [...n.values()].sort((s,r)=>s.url.localeCompare(r.url))}function xn(e){let t=We(e.scope),n=In(e.events),s=new Set,r=new Set,i=new Map(Ft({events:e.events,scope:t,sourceOrigin:e.sourceOrigin}).map(d=>[`${d.kind}|${d.url}`,d]));for(let d of n){let p=d.before,g=d.after,f=Pn(p),w=Pn(g);w&&g.url&&s.add(fe(e.sourceOrigin,g.url)),f&&p.url&&(!w||p.url!==g.url)&&r.add(fe(e.sourceOrigin,p.url));}let a=new Map(e.resolvedArchiveFamilies.map(d=>[`${d.kind}|${fe(e.sourceOrigin,d.url)}`,{...d,url:fe(e.sourceOrigin,d.url),pageUrls:Ce(d.pageUrls.map(p=>fe(e.sourceOrigin,p)))}])),c=[...i.entries()].map(([d,p])=>{let g=a.get(d);if(!g)throw new Error(`WordPress did not resolve archive family ${d}.`);return {...p,...g}}).sort((d,p)=>d.url.localeCompare(p.url)),o=Ce(c.flatMap(d=>d.pageUrls)),u=t.includeSitemapChain?Ce(e.sitemapUrls.map(d=>fe(e.sourceOrigin,d))):[],l={schemaVersion:1,generatedAt:new Date().toISOString(),jobId:e.jobId,ruleId:e.ruleId,consumerId:e.consumerId,coalesceKey:e.coalesceKey,scopeFingerprint:e.scopeFingerprint,targetFingerprint:e.targetFingerprint,baselineId:e.baselineId,fromSequence:e.fromSequence,toSequence:e.toSequence,eventCount:e.events.length,foldedCount:n.length,directRenderUrls:Ce([...s]),archiveFamilyUrls:o,sitemapUrls:u,deleteUrls:Ce([...r]),archiveFamilies:c};return {...l,impactHash:oe(l)}}function He(e){let{impactHash:t,...n}=e;if(e.schemaVersion!==1||!t)throw new Error("Invalid content-sync impact plan schema.");if(oe(n)!==t)throw new Error("Content-sync impact plan hash mismatch.");for(let s of [...e.directRenderUrls,...e.deleteUrls])if(ts(s))throw new Error(`Content-sync impact contains a WordPress trash alias instead of the last public URL: ${s}`)}var is="wp-json/smartcloud-static-publisher/v1/content-sync/",os=25*1024*1024,nt=class extends Error{status;code;constructor(t,n,s){super(s),this.name="ContentSyncApiError",this.status=t,this.code=n;}},rt=class{options;constructor(t){if(!t.runtimeToken.trim())throw new Error("Content-sync requires a WordPress runtime token.");this.options={...t,timeoutMs:t.timeoutMs??6e4};}endpoint(t){let n=this.options.sourceOrigin.replace(/\/+$/,"")+"/";return new URL(`${is}${t}`,n)}async post(t,n){let s=this.endpoint(t),r=Buffer.from(JSON.stringify(n),"utf8"),i=s.protocol==="https:"?An:ss,a=s.protocol==="https:"?new An.Agent({rejectUnauthorized:!this.options.ignoreHttpsErrors}):void 0;return new Promise((c,o)=>{let u=i.request(s,{method:"POST",agent:a,headers:{"content-type":"application/json","content-length":String(r.byteLength),"x-static-publisher-token":this.options.runtimeToken},timeout:this.options.timeoutMs},l=>{let d=[],p=0;l.on("data",g=>{if(p+=g.byteLength,p>os){l.destroy(new Error("Content-sync API response exceeded the size limit."));return}d.push(g);}),l.on("error",o),l.on("end",()=>{let g=Buffer.concat(d).toString("utf8"),f;try{f=g?JSON.parse(g):{};}catch{o(new nt(l.statusCode??500,"invalid-json","Content-sync API returned invalid JSON."));return}let w=l.statusCode??500;if(w<200||w>=300){o(new nt(w,String(f.code??"request-failed"),String(f.message??`Content-sync API request failed (${w}).`)));return}c(f);});});u.on("timeout",()=>u.destroy(new Error(`Content-sync API request timed out: ${t}`))),u.on("error",o),u.end(r);})}async head(t){return this.post("head",t)}async unboundHead(t,n){return this.post("head",{postTypes:t,includeSubsites:n})}async events(t){let n=[],s=t.afterSequence,r=new Set(t.postTypes);for(;s<t.throughSequence;){let i=await this.post("events",{...t,afterSequence:s,limit:250});if(i.fromSequence!==s||i.throughSequence!==t.throughSequence||i.nextSequence<s||i.nextSequence>t.throughSequence)throw new Error("Content-sync API returned an inconsistent event page.");if(!Array.isArray(i.items))throw new Error("Content-sync API returned a malformed event page.");let a=s;for(let c of i.items){if(!Number.isSafeInteger(c.sequence)||c.sequence<=a||c.sequence>t.throughSequence||!Number.isSafeInteger(c.postId)||c.postId<=0||!Number.isSafeInteger(c.blogId)||c.blogId<=0||!r.has(c.postType)||typeof c.operation!="string"||!c.operation)throw new Error("Content-sync API returned an invalid or out-of-scope journal event.");a=c.sequence;}if(i.items.length>0&&i.nextSequence!==a)throw new Error("Content-sync API event cursor does not match the final returned event.");if(n.push(...i.items),!i.hasMore)break;if(i.nextSequence===s)throw new Error("Content-sync API event pagination did not advance.");s=i.nextSequence;}if(t.throughSequence>t.afterSequence&&n.at(-1)?.sequence!==t.throughSequence)throw new Error("Content-sync API omitted the claimed journal high-water event.");return n}async resolveImpactFamilies(t,n){let s=await this.post("impact",{families:t,includeSubsites:n});return Array.isArray(s.families)?s.families:[]}async releaseFingerprint(t=false){let n=await this.post("fingerprint",{includeSubsites:t}),s=String(n.fingerprint||"").trim();if(!/^[a-f0-9]{64}$/.test(s))throw new Error("WordPress returned an invalid release fingerprint.");return s}async establishBaseline(t){return this.post("baseline",t)}async acknowledge(t){return this.post("ack",t)}};function st(e){let t=S.resolve(e);return {state:S.join(t,"content-sync-state.json"),current:S.join(t,"content-sync-current.json"),impact:S.join(t,"content-sync-impact-plan.json"),checkpoint:S.join(t,"content-sync-checkpoint.json"),baseline:S.join(t,"content-sync-baseline.json"),releaseCutoff:S.join(t,"content-sync-release-cutoff.json"),candidateManifest:S.join(t,"content-sync-candidate-manifest.json"),trustedManifest:S.join(t,"crawl-manifest.json"),invalidation:S.join(t,"content-sync-invalidation.json"),deployPlan:S.join(t,"deploy-plan.json")}}async function Dt(e){let t=await ze(e.releaseCutoff);if(t===null)return {schemaVersion:1,updatedAt:"",entries:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.entries||typeof n.entries!="object"||Array.isArray(n.entries))throw new Error("Invalid content-sync release-cutoff store.");return n}async function Tn(e,t){await ke(e.releaseCutoff,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function ke(e,t){await A.mkdir(S.dirname(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await A.writeFile(n,JSON.stringify(t,null,2),"utf8"),await A.rename(n,e);}async function ze(e){try{return JSON.parse(await A.readFile(e,"utf8"))}catch(t){if(t.code==="ENOENT")return null;throw new Error(`Invalid or unreadable content-sync state file ${e}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async function Ot(e){let t=await ze(e.baseline);if(t===null)return {schemaVersion:1,updatedAt:"",entries:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.entries||typeof n.entries!="object"||Array.isArray(n.entries))throw new Error("Invalid content-sync baseline store.");return n}async function kn(e,t){await ke(e.baseline,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function jt(e){let t=await ze(e.current);if(t===null)return null;let n=t;if(n.schemaVersion!==1||typeof n.jobId!="string"||typeof n.phase!="string"||!Number.isSafeInteger(n.fromSequence)||!Number.isSafeInteger(n.toSequence))throw new Error("Invalid content-sync current-range state.");return n}async function $n(e,t){await ke(e.current,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function En(e){let t=await ze(e.impact);if(t===null)return null;let n=t;return He(n),n}async function Mn(e,t){He(t),await ke(e.impact,t);}async function Fn(e,t){await ke(e.checkpoint,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function it(e){let t=await ze(e.state);if(t===null)return {schemaVersion:1,updatedAt:"",rules:{}};let n=t;if(n.schemaVersion!==1||typeof n.updatedAt!="string"||!n.rules||typeof n.rules!="object"||Array.isArray(n.rules))throw new Error("Invalid content-sync state store.");return n}async function ot(e,t){await ke(e.state,{...t,schemaVersion:1,updatedAt:new Date().toISOString()});}async function Ut(e){await Promise.all([e.current,e.checkpoint].map(async t=>{try{await A.unlink(t);}catch(n){if(n.code!=="ENOENT")throw n}}));}async function Dn(e,t){let n=await jt(e);return !n||n.coalesceKey!==t?false:(await Promise.all([e.current,e.checkpoint,e.impact,e.candidateManifest,e.invalidation,e.deployPlan].map(async s=>{try{await A.unlink(s);}catch(r){if(r.code!=="ENOENT")throw r}})),true)}function jn(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function ls(e){let t=String(e??"").trim();if(!t)return "";let n=t;if(/^https?:\/\//i.test(n))try{n=new URL(n).pathname;}catch{return ""}if(n=n.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!n)return "";let s=n.endsWith("/"),r=n.replace(/^\/+/,"").split("/").map(a=>a.replace(/[^A-Za-z0-9._-]/g,"")).filter(a=>a.length>0&&a!=="."&&a!=="..");if(r.length===0)return "";let i=`/${r.join("/")}`;return s&&S.extname(i)===""&&(i+="/"),i==="/"?"":i}function Lt(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[t.trim(),String(n??"")]).filter(([t])=>t.length>0))}function ds(e){if(!e||typeof e!="object")return {};let t={};for(let[n,s]of Object.entries(e)){let r=n.trim();if(!r||!s||typeof s!="object")continue;let i=s,a={};if(typeof i.targetOrigin=="string"){let o=jn(i.targetOrigin);o&&(a.targetOrigin=o);}let c=Lt(i.extraReplacements);if(Object.keys(c).length>0&&(a.extraReplacements=c),i.s3&&typeof i.s3=="object"){let o={},u=i.s3;typeof u.bucket=="string"&&(o.bucket=u.bucket.trim()),typeof u.prefix=="string"&&(o.prefix=u.prefix.trim()),typeof u.region=="string"&&(o.region=u.region.trim()),typeof u.htmlCacheControl=="string"&&(o.htmlCacheControl=u.htmlCacheControl.trim()),typeof u.assetCacheControl=="string"&&(o.assetCacheControl=u.assetCacheControl.trim()),Object.keys(o).length>0&&(a.s3=o);}if(i.cloudFront&&typeof i.cloudFront=="object"){let o={},u=i.cloudFront;typeof u.distributionId=="string"&&(o.distributionId=u.distributionId.trim()),Array.isArray(u.invalidationPaths)&&(o.invalidationPaths=u.invalidationPaths.map(l=>String(l??"").trim()).filter(l=>l.length>0)),Object.keys(o).length>0&&(a.cloudFront=o);}t[r]=a;}return t}function _t(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function ps(e,t){if(!e||typeof e!="object")return null;let n=e,s=n.command;if(s!=="publish"&&s!=="crawl"&&s!=="deploy"&&s!=="invalidate"&&s!=="retry-timeouts"&&s!=="url"&&s!=="content-sync")return null;let r=Number.parseInt(String(n.intervalMinutes??"0"),10);if(!Number.isFinite(r)||r<1)return null;let i=String(n.id??`${s}-${t+1}`).trim();if(!i)return null;let a=String(n.deploymentProfile??"").trim(),c=String(n.url??"").trim(),o=Array.isArray(n.postTypes)?[...new Set(n.postTypes.map(l=>String(l??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],u=Array.isArray(n.listingPaths)?[...new Set(n.listingPaths.map(l=>String(l??"").trim()).filter(Boolean))]:[];return s==="content-sync"&&o.length===0?null:{id:i,enabled:n.enabled!==false,command:s,intervalMinutes:r,...s==="publish"||s==="crawl"?{crawlMode:n.crawlMode==="incremental"?"incremental":"full"}:{},...(s==="publish"||s==="deploy"||s==="invalidate"||s==="content-sync")&&a?{deploymentProfile:a}:{},...c?{url:c}:{},...o.length>0?{postTypes:o}:{},...u.length>0?{listingPaths:u}:{},...typeof n.includeSubsites=="boolean"?{includeSubsites:n.includeSubsites}:{},...typeof n.includePostTypeArchives=="boolean"?{includePostTypeArchives:n.includePostTypeArchives}:{},...typeof n.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:n.includeTaxonomyArchives}:{},...typeof n.includeAuthorArchives=="boolean"?{includeAuthorArchives:n.includeAuthorArchives}:{},...typeof n.includeDateArchives=="boolean"?{includeDateArchives:n.includeDateArchives}:{},...typeof n.includePostsPage=="boolean"?{includePostsPage:n.includePostsPage}:{},...typeof n.includeSitemapChain=="boolean"?{includeSitemapChain:n.includeSitemapChain}:{}}}function Un(e){let t=e&&typeof e=="object"?e:{},n=Array.isArray(t.rules)?t.rules.map((s,r)=>ps(s,r)).filter(s=>!!s):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:n}}function gs(e){if(!e||typeof e!="object")return;let t=e,n={};for(let r of ["accountId","siteId"]){let i=t[r];typeof i=="string"&&i.trim()!==""&&(n[r]=i.trim());}let s=Number(t.lastUpdate??0);return Number.isFinite(s)&&s>0&&(n.lastUpdate=Math.floor(s)),t.subscriber===true&&(n.subscriber=true),Object.keys(n).length>0?n:void 0}function Nt(e){let t=e&&typeof e=="object"?e:{},n=String(t.accountId??"").trim(),s=String(t.siteId??"").trim(),r=t.subscriber===true,i=gs(t.siteSettings),a={...i??{},...n?{accountId:i?.accountId??n}:{},...s?{siteId:i?.siteId??s}:{},...i?.subscriber===true||r?{subscriber:true}:{}},c={},o=String(t.apiBase??"").trim();o&&(c.apiBase=o);let u=String(t.runtimeToken??t.nonce??"").trim();u&&(c.runtimeToken=u);let l=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();l&&(c.virtualAssetBaseUrl=l),Object.keys(a).length>0&&(c.siteSettings=a);let d=_t(t.subscriptionType);return d&&(c.subscriptionType=d),c}function fs(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function Ln(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function ms(e,t){let n=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[s,r]of new Headers(t.headers).entries())n.set(s,r);return n}async function qn(e,t,n=5){let s=new URL(Ln(e)),r=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),i=s.protocol==="http:"?ss:An,a=ms(e,t);return await new Promise((c,o)=>{let u=i.request(s,{method:r,headers:Object.fromEntries(a.entries()),...s.protocol==="https:"?{rejectUnauthorized:false}:{}},l=>{let d=[];l.on("data",p=>{d.push(Buffer.isBuffer(p)?p:Buffer.from(p));}),l.on("error",o),l.on("end",()=>{let p=l.statusCode??0,g=l.headers.location;if(n>0&&g&&[301,302,303,307,308].includes(p)){c(qn(new URL(g,s),{method:p===303?"GET":r},n-1));return}let f=new Headers;for(let[w,m]of Object.entries(l.headers))Array.isArray(m)?f.set(w,m.join(", ")):typeof m=="string"&&f.set(w,m);c(new Response(Buffer.concat(d),{status:p,statusText:l.statusMessage??"",headers:f}));});});u.on("error",o),u.end();})}function hs(e){let t=Nt(e.wpsuite),n={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},s=String(n.accountId??"").trim(),r=String(n.siteId??"").trim(),i=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...i?{virtualAssetBaseUrl:i}:{},...Object.keys(n).length>0?{siteSettings:n}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!s||!r||!i)return false;fs(e.sourceOrigin);let a=globalThis,o={...a.WpSuite??{},siteSettings:n,uploadUrl:i};return t.apiBase&&(o.apiBase=t.apiBase),a.WpSuite=o,true}async function ws(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!hs(e)){let r=e.wpsuite?.siteSettings,i=[String(r?.accountId??"").trim()?"":"accountId",String(r?.siteId??"").trim()?"":"siteId",t?"":"virtualAssetBaseUrl"].filter(Boolean);return {remote:null,diagnostic:{status:"invalid-runtime",virtualAssetBaseUrl:t,subscriptionType:null,error:`Missing WP Suite runtime field(s): ${i.join(", ")}.`,requests:[]}}}let n=globalThis.fetch,s=[];try{typeof n=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(o,u)=>{let l=Ln(o);if(l.startsWith(t)){let d=(()=>{try{return new URL(l).pathname}catch{return l}})();try{let p=e.ignoreHttpsErrors&&l.startsWith("https://")?await qn(o,u):await n(o,u);return s.push({path:d,status:p.status,ok:p.ok,error:null}),p}catch(p){throw s.push({path:d,status:null,ok:!1,error:p instanceof Error?p.message:String(p)}),p}}return n(o,u)}));let{getConfig:r}=await import('@smart-cloud/wpsuite-core'),i=await r("publisher"),a=i&&typeof i=="object"?i:null,c=_t(a?.subscriptionType);return {remote:a,diagnostic:{status:a?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:c??null,error:a?null:"WP Suite publisher config loader returned no configuration.",requests:s}}}catch(r){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:r instanceof Error?r.message:String(r),requests:s}}}finally{typeof n=="function"&&(globalThis.fetch=n);}}function ys(e,t){let n=ds(t?.deploymentProfiles),s=String(t?.defaultDeploymentProfile??"").trim(),r=n[s]?s:"",i=_t(t?.subscriptionType),a=Nt(e.wpsuite);return {...e,scheduler:Un(t?.scheduler),deploymentProfiles:n,defaultDeploymentProfile:r,...i?{subscriptionType:i}:{},wpsuite:{...a,...a.siteSettings||i?{siteSettings:{...a.siteSettings??{},...a.siteSettings?.subscriber===true||i==="PROFESSIONAL"||i==="AGENCY"?{subscriber:true}:{}}}:{},...i?{subscriptionType:i}:{}}}}function qt(e,t){let s=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!s)return t;let r=s.split("/").map(i=>i.trim()).filter(i=>i.length>0&&i!=="."&&i!=="..");return r.length>0?r.join("/"):t}function Ss(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function On(e,t,n){let s=String(t||"").trim();return s&&S.isAbsolute(s)?S.resolve(s):S.resolve(e,qt(s,n))}async function ne(e,t={}){let n=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",s=await A.readFile(n,"utf8"),r=JSON.parse(s);r.sourceOrigin=r.sourceOrigin.replace(/\/$/,""),r.targetOrigin=jn(r.targetOrigin),r.ignoreHttpsErrors??=false,r.outputDir=String(r.outputDir||"export").trim()||"export",r.urlRewriteMode||=r.targetOrigin==="."?"relative":"absolute",r.noJavaScriptRenderPathPrefixes||=[],r.seedPaths||=[],r.generated404RequestPath=ls(r.generated404RequestPath),r.sitemapPaths||=["/sitemap_index.xml","/sitemap.xml"],r.allowedAssetHosts||=[],r.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],r.blockedPathPrefixes||=[],r.blockedSearchFragments||=[],r.concurrency||=1,r.maxPages||=0,r.extraReplacements=Lt(r.extraReplacements),r.postCrawlCopyMap=Lt(r.postCrawlCopyMap),r.logDir=String(r.logDir||"logs").trim()||"logs",r.verbose??=false,r.logLevel||=r.verbose?"debug":"info",r.s3SyncMode||="sdk-upload-delete",r.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},r.readiness.timeoutMs??=1500,r.readiness.fallbackWaitMs??=1500,r.viewport||={width:1440,height:1200},r.navigationTimeoutMs||=3e4,r.assetDownloadConcurrency=Number(r.assetDownloadConcurrency)>0?Number(r.assetDownloadConcurrency):r.concurrency,r.rewriteConcurrency=Number(r.rewriteConcurrency)>0?Number(r.rewriteConcurrency):r.assetDownloadConcurrency,r.wpsuite=Nt(r.wpsuite),r.scheduler=Un(void 0),r.deploymentProfiles={},r.defaultDeploymentProfile="",r.deploymentTargetOverride=String(r.deploymentTargetOverride??"").trim();let i=await ws(r);t.onRemotePublisherConfigDiagnostic?.(i.diagnostic);let a=ys(r,i.remote),c=Ss(),o=c?S.resolve(c,".."):"";return o?(a.outputDir=On(o,a.outputDir,"export"),a.logDir=On(o,a.logDir,"logs")):(S.isAbsolute(a.outputDir)||(a.outputDir=qt(a.outputDir,"export")),S.isAbsolute(a.logDir)||(a.logDir=qt(a.logDir,"logs"))),a}var Ps=".deploy-plan.json",bs="deploy-plan.json",vs=".crawl-incomplete.json",Cs="crawl-incomplete.json";function _n(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function Nn(e){let t=String(e||"").replace(/\\/g,"/").replace(/^\/+/,"").trim(),n=S.posix.normalize(t);return !t||!n||n==="."||/^[a-zA-Z]:/.test(n)||n.startsWith("../")||n===".."?null:n}function Rs(e){let t=String(e||"").trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("*")||t.includes("#"))return null;try{let n=new URL(t,"https://content-sync.invalid");return n.origin!=="https://content-sync.invalid"?null:`${S.posix.normalize(n.pathname)}${n.search}`}catch{return null}}function he(e){return [...new Set(e.map(Nn).filter(t=>t!==null))]}function Bn(e,t){let n={generatedAt:String(t.generatedAt||new Date().toISOString()),outputDir:S.resolve(e.outputDir),runMode:t.runMode,crawlMode:t.crawlMode,fullSyncRequired:!!t.fullSyncRequired,changedFiles:he(t.changedFiles||[]),deletedFiles:he(t.deletedFiles||[]),rewriteTargets:he(t.rewriteTargets||[])};return t.schemaVersion===2?{...n,schemaVersion:2,runMode:"content-sync",crawlMode:"incremental",fullSyncRequired:false,consumerId:String(t.consumerId||"").trim(),fromSequence:Math.max(0,Number(t.fromSequence)||0),toSequence:Math.max(0,Number(t.toSequence)||0),impactHash:String(t.impactHash||"").trim(),uploadGroups:{assets:he(t.uploadGroups?.assets||[]),content:he(t.uploadGroups?.content||[]),listings:he(t.uploadGroups?.listings||[]),sitemapLeaves:he(t.uploadGroups?.sitemapLeaves||[]),sitemapIndexes:he(t.uploadGroups?.sitemapIndexes||[])},invalidationPaths:[...new Set((t.invalidationPaths||[]).map(Rs).filter(s=>s!==null))].sort()}:{schemaVersion:1,...n,runMode:t.runMode}}function Is(e){if(!e||typeof e!="object")return false;let t=e;if(t.schemaVersion===2){let n=t;return n.runMode==="content-sync"&&n.crawlMode==="incremental"&&n.fullSyncRequired===false&&typeof n.generatedAt=="string"&&typeof n.outputDir=="string"&&typeof n.consumerId=="string"&&n.consumerId.trim()!==""&&Number.isSafeInteger(n.fromSequence)&&Number.isSafeInteger(n.toSequence)&&Number(n.toSequence)>=Number(n.fromSequence)&&typeof n.impactHash=="string"&&/^[a-f0-9]{64}$/.test(n.impactHash)&&Array.isArray(n.changedFiles)&&Array.isArray(n.deletedFiles)&&Array.isArray(n.rewriteTargets)&&!!n.uploadGroups&&Array.isArray(n.uploadGroups.assets)&&Array.isArray(n.uploadGroups.content)&&Array.isArray(n.uploadGroups.listings)&&Array.isArray(n.uploadGroups.sitemapLeaves)&&Array.isArray(n.uploadGroups.sitemapIndexes)&&Array.isArray(n.invalidationPaths)}return t.schemaVersion===1&&typeof t.generatedAt=="string"&&typeof t.outputDir=="string"&&(t.runMode==="full"||t.runMode==="retry-timeouts"||t.runMode==="single-url")&&(t.crawlMode==="full"||t.crawlMode==="incremental")&&typeof t.fullSyncRequired=="boolean"&&Array.isArray(t.changedFiles)&&Array.isArray(t.deletedFiles)&&Array.isArray(t.rewriteTargets)}function Bt(e){let t=S.join(S.resolve(e.outputDir),Ps),n=_n();return n?[S.join(n,bs),t]:[t]}function Wt(e){let t=S.join(S.resolve(e.outputDir),vs),n=_n();return n?[S.join(n,Cs),t]:[t]}function we(e,t){let n=S.resolve(e),s=S.resolve(t),r=S.relative(n,s).replace(/\\/g,"/");return Nn(r)}async function at(e){let t=S.resolve(e.outputDir);for(let n of Bt(e))try{let s=await A.readFile(n,"utf8"),r=JSON.parse(s);if(!Is(r)||S.resolve(r.outputDir)!==t)continue;return Bn(e,r)}catch{}return null}async function Ht(e,t){let n=Bn(e,t);for(let s of Bt(e)){await A.mkdir(S.dirname(s),{recursive:true});let r=`${s}.${process.pid}.${Date.now()}.tmp`;await A.writeFile(r,JSON.stringify(n,null,2),"utf8"),await A.rename(r,s);}}async function $e(e){for(let t of Bt(e))try{await A.unlink(t);}catch(n){if(n.code!=="ENOENT")throw n}}async function Wn(e,t){let n={schemaVersion:1,startedAt:String(t.startedAt||new Date().toISOString()),outputDir:S.resolve(e.outputDir)};for(let s of Wt(e)){await A.mkdir(S.dirname(s),{recursive:true});let r=`${s}.${process.pid}.tmp`;await A.writeFile(r,JSON.stringify(n,null,2),"utf8"),await A.rename(r,s);}}async function Hn(e){let t=S.resolve(e.outputDir);for(let n of Wt(e)){let s;try{s=await A.readFile(n,"utf8");}catch(i){if(i.code==="ENOENT")continue;throw i}let r;try{r=JSON.parse(s);}catch{throw new Error(`Invalid incomplete crawl marker: ${n}`)}if(r.schemaVersion!==1||typeof r.startedAt!="string"||typeof r.outputDir!="string"||S.resolve(r.outputDir)!==t)throw new Error(`Invalid incomplete crawl marker: ${n}`);return {schemaVersion:1,startedAt:r.startedAt,outputDir:t}}return null}async function zn(e){for(let t of Wt(e))try{await A.unlink(t);}catch(n){if(n.code!=="ENOENT")throw n}}function Je(e,t=10){return Vn.createHash("sha1").update(e).digest("hex").slice(0,t)}async function xs(e){await A.mkdir(S.dirname(e),{recursive:true});}async function Ve(e,t,n){await xs(e);let s=S.join(S.dirname(e),`.${S.basename(e)}.${process.pid}.${Date.now()}.${Vn.randomBytes(6).toString("hex")}.tmp`);try{typeof t=="string"?await A.writeFile(s,t,n??"utf8"):await A.writeFile(s,t),await A.rename(s,e);}catch(r){throw await A.unlink(s).catch(()=>{}),r}}function ye(e){return [".html",".htm",".css",".js",".mjs",".json",".xml",".xsl",".txt",".svg",".map",".enc",".jws"].includes(S.extname(e).toLowerCase())}function ce(e){return e.replace(/"/g,'"').replace(/"/g,'"').replace(/'/g,"'").replace(/'/g,"'").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Ee(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function ct(e){return e.replace(/\//g,"\\/")}function Qn(e){return e.replace(/\//g,"\\\\/")}function As(e){try{let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let n=t.pathname==="/"&&!t.search&&!t.hash?"":`${t.pathname}${t.search}${t.hash}`;return `//${t.host}${n}`}catch{return null}}function Jn(e,t,n){if(!t)return;e[t]=n;let s=ct(t),r=ct(n);e[s]=r;let i=Qn(t),a=Qn(n);e[i]=a;let c=Ee(t),o=Ee(n);e[c]=o;let u=Ee(s),l=Ee(r);e[u]=l;let d=Ee(i),p=Ee(a);e[d]=p;}function ut(e,t,n){Jn(e,t,n);let s=As(t);s&&s!==t&&Jn(e,s,n);}function zt(e,t){let n=t.startsWith("/")?t:`/${t}`,s=(e||"").replace(/\/$/,"");return !s||s==="."||s==="/"?n:`${s}${n}`}function Kn(e,t){try{return new URL(e,t==="."?"https://relative.invalid":t).pathname}catch{return e.startsWith("/")?e:`/${e.replace(/^\.\//,"")}`}}function Gn(e,t,n){if(!t)return n;let s=S.dirname(S.resolve(t)),r=S.resolve(e,n.replace(/^\/+/,"")),i=S.relative(s,r).replace(/\\/g,"/");return i?(i.startsWith(".")||(i=`./${i}`),i):"."}var Ms=["wp-content/","wp-includes/","wp-admin/","wp-json/","_next/"],Fs=new Set([".html",".htm"]),Zn="WPSuite.io Static Publisher",Ds=Zn.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Os(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function js(e){return e.startsWith("//")||e.startsWith("\\/\\/")||e.startsWith("\\\\/\\\\/")}function Us(e,t,n){return js(t)?e.replace(new RegExp(`(?<!:)${Os(t)}`,"g"),n):e.split(t).join(n)}function Ls(e,t,n){if(e.wpsuite?.siteSettings?.subscriber===true||e.wpsuite?.subscriptionType==="PROFESSIONAL"||e.wpsuite?.subscriptionType==="AGENCY"||!n)return false;let r=S.extname(n).toLowerCase();return Fs.has(r)?/<head\b|<html\b|<!doctype html/i.test(t):false}function qs(e){if(new RegExp(`<meta\\b(?=[^>]*\\bname=(["'])generator\\1)(?=[^>]*\\bcontent=(["'])${Ds}\\2)[^>]*\\/?>`,"i").test(e))return e;let t=`<meta name="generator" content="${Zn}" />`;if(e.match(/(\r?\n)([ \t]*)<\/head>/i))return e.replace(/(\r?\n)([ \t]*)<\/head>/i,`$1$2${t}$1$2</head>`);let s=e.includes(`\r
|
|
2
2
|
`)?`\r
|
|
3
3
|
`:`
|
|
4
|
-
`;return e.replace(/<head\b[^>]*>/i,r=>`${r}${s} ${t}`)}function
|
|
5
|
-
`,"utf8");}function
|
|
6
|
-
`,"utf8");});}enqueueJsonLine(t,n){this.enqueueTask(()=>
|
|
7
|
-
`,"utf8");});}enqueueJsonLine(t,n){this.enqueueTask(()=>Xn(t,n));}updateCurrentEvent(t,n,s){let r=Qs(t,n,s);this.enqueueTask(async()=>{await A.mkdir(this.logDir,{recursive:true}),await A.writeFile(this.currentEventPath,JSON.stringify(r,null,2),"utf8");});}push(t,n,s){let r=ve(n),i=pt(s),a=JSON.stringify({time:new Date().toISOString(),level:t,message:r,...i||{}});this.enqueueLine(a),this.updateCurrentEvent(t,r,i),t==="error"?console.error(r,i||""):t==="warn"?console.warn(r,i||""):(ie[this.level]>=ie.debug||["summary","page","sitemap","asset","timing"].includes(t))&&console.log(r);}info(t,n){this.push("info",t,n);}debug(t,n){ie[this.level]<ie.debug||this.push("debug",t,n);}progress(t,n){Yn("crawl.log.jsonl",t,n),this.updateCurrentEvent("progress",t,n);}checkpoint(t,n){this.updateCurrentEvent("checkpoint",t,n);}page(t,n){this.push("page",t,n);}sitemap(t,n){this.push("sitemap",t,n);}asset(t,n){this.push("asset",t,n);}warn(t,n){this.push("warn",t,n);}error(t,n){this.enqueueJsonLine(this.errorsPath,{message:t,...n||{}}),this.push("error",t,n);}summary(t,n){this.push("summary",t,n);}mark(t){this.marks.set(t,Date.now());}endMark(t,n){let s=this.marks.get(t);if(!s)return;let r=Date.now()-s,i={name:t,ms:r,seconds:Number((r/1e3).toFixed(2)),...n||{}};this.enqueueJsonLine(this.timingsPath,i),this.push("timing",`Timing ${t}: ${i.seconds}s`,i);}reject(t,n,s,r){let i={kind:t,url:n,reason:s,source:r};this.enqueueJsonLine(this.rejectedPath,i),ie[this.level]>=ie.debug&&this.push("reject",`Rejected ${t} ${n}: ${s}`,i);}ignore(t,n,s,r){let i={kind:t,url:n,reason:s,source:r};this.enqueueJsonLine(this.ignoredPath,i),ie[this.level]>=ie.debug&&this.push("ignore",`Ignored ${t} ${n}: ${s}`,i);}skip(t,n,s,r){let i={kind:t,url:n,status:s,source:r};this.enqueueJsonLine(this.skippedPath,i),this.push("warn",`Skipped ${t} ${n}: HTTP ${s}`,i);}async flush(){let t=Date.now()-this.startedAt,n={name:"total",ms:t,seconds:Number((t/1e3).toFixed(2))};if(this.enqueueJsonLine(this.timingsPath,n),await this.writeQueue,this.writeError)throw this.writeError}};var zt="(?:css|js|mjs|json|map|xml|xsl|rss|atom|txt|enc|jws|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf|eot|pdf|mp4|webm)";function er(e){return !!e&&/^(?:\.{1,2}\/)?[A-Za-z0-9@_][A-Za-z0-9@._/-]*\.(?:js|mjs)(?:[?#][^\s<>\\]*)?$/i.test(e)&&!e.startsWith("/")&&!e.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(e)&&!/(?:^|\/)node_modules(?:\/|$)|(?:^|\/)\.pnpm(?:\/|$)/i.test(e)}function tr(e){let t=new Set,n=[],s=/\bimport\s*\(\s*["'`]([^"'`\s<>\\]+)["'`]\s*\)/g,r=/\b(?:[A-Za-z_$][\w$]*\.)?u\s*=\s*(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>\s*["'`]([^"'`\s<>\\]+)["'`]/g;for(let i of e.matchAll(s))i[1]&&er(i[1])&&n.push({index:i.index??0,value:i[1]});for(let i of e.matchAll(r))i[1]&&er(i[1])&&n.push({index:i.index??0,value:i[1]});for(let i of n.sort((a,c)=>a.index-c.index))t.add(i.value);return [...t]}var Gs=["text/css","javascript","image/","font/","application/font","application/json","application/xml","text/xml","application/rss+xml","application/atom+xml","application/xslt+xml","text/xsl","image/svg+xml"],fr=new Set([".css",".js",".mjs",".json",".map",".xml",".xsl",".rss",".atom",".txt",".enc",".jws",".png",".jpg",".jpeg",".gif",".webp",".avif",".svg",".ico",".woff",".woff2",".ttf",".otf",".eot",".pdf",".mp4",".webm"]),mr=new Set(["",".html",".htm"]),Zs=new Set([".css",".xml",".xsl",".svg",".json",".html",".htm",".txt",".enc",".jws"]),Ys=["/wp-content/","/wp-includes/","/wp-admin/","/static/","/assets/","/build/","/_next/"];function Xs(e){let t=[],n="full",s="full",r=false,i=false,a="";for(let c=0;c<e.length;c++){let o=e[c];if(o==="--retry-timeouts")n="retry-timeouts",r=true;else if(o==="--resume")r=true;else if(o==="--resume-rewrite")r=true,i=true;else if(o==="--crawl-mode"){let u=e[++c];if(!u)throw new Error("--crawl-mode requires a value");s=u==="incremental"?"incremental":"full",r||=s==="incremental";}else if(o.startsWith("--crawl-mode="))s=o.slice(13)==="incremental"?"incremental":"full",r||=s==="incremental";else if(o==="--incremental")s="incremental",r=true;else if(o==="--url"){let u=e[++c];if(!u)throw new Error("--url requires a value");n="single-url",r=true,t.push(u);}else if(o.startsWith("--url="))n="single-url",r=true,t.push(o.slice(6));else if(o==="--urls"){let u=e[++c];if(!u)throw new Error("--urls requires a file path");n="single-url",r=true,t.push(`@${u}`);}else if(o==="--content-sync-plan"){let u=e[++c];if(!u)throw new Error("--content-sync-plan requires a file path");n="content-sync",s="incremental",r=true,a=S.resolve(u);}else o.startsWith("--content-sync-plan=")&&(n="content-sync",s="incremental",r=true,a=S.resolve(o.slice(20)));}return {mode:n,crawlMode:s,urls:t,preserveOutput:r,resumeRewrite:i,contentSyncPlanPath:a}}function Xt(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function ei(){let e=Xt();return e?S.resolve(e,".."):""}function ti(){let e=process.env.STATIC_PUBLISHER_WP_ROOT||process.env.WPSUITE_STATIC_PUBLISHER_WP_ROOT||"";return e.trim()?S.resolve(e):""}function ni(e){let t=e.trim(),n=[{alias:"@storage-root",root:ei(),requiredEnv:"STATIC_PUBLISHER_RUNTIME_DIR or WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR"},{alias:"@runtime",root:Xt(),requiredEnv:"STATIC_PUBLISHER_RUNTIME_DIR or WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR"},{alias:"@wp-root",root:ti(),requiredEnv:"STATIC_PUBLISHER_WP_ROOT or WPSUITE_STATIC_PUBLISHER_WP_ROOT"}];for(let s of n){if(t!==s.alias&&!t.startsWith(`${s.alias}/`))continue;if(!s.root)return {resolvedPath:null,alias:s.alias,requiredEnv:s.requiredEnv};let r=t.slice(s.alias.length).replace(/^\/+/,"");return {resolvedPath:r?S.resolve(s.root,r):s.root,alias:s.alias}}return {resolvedPath:S.resolve(t)}}function hr(e){let t=String(process.env.STATIC_PUBLISHER_CRAWL_MANIFEST_PATH||"").trim();if(t)return S.resolve(t);let n=Xt();return n?S.join(n,"crawl-manifest.json"):S.join(e.outputDir,".crawl-manifest.json")}function wr(){return {schemaVersion:3,updatedAt:"",pages:{},assets:{}}}function nr(e){return {url:String(e.url||""),outputPath:String(e.outputPath||""),contentType:typeof e.contentType=="string"&&e.contentType?e.contentType:null,changeToken:typeof e.changeToken=="string"?e.changeToken:null,tokenSource:typeof e.tokenSource=="string"?e.tokenSource:null,sitemapLastmod:typeof e.sitemapLastmod=="string"?e.sitemapLastmod:null,discoveredPages:Array.isArray(e.discoveredPages)?e.discoveredPages.map(t=>String(t)):[],discoveredAssets:Array.isArray(e.discoveredAssets)?e.discoveredAssets.map(t=>String(t)):[],lastCrawledAt:String(e.lastCrawledAt||""),lastSeenRunId:String(e.lastSeenRunId||""),rewriteComplete:e.rewriteComplete===true}}function ri(e){let t=e.isText===true;return {url:String(e.url||""),outputPath:String(e.outputPath||""),isText:t,contentType:typeof e.contentType=="string"&&e.contentType?e.contentType:null,discoveredAssets:Array.isArray(e.discoveredAssets)?e.discoveredAssets.map(n=>String(n)):[],lastCrawledAt:String(e.lastCrawledAt||""),lastSeenRunId:String(e.lastSeenRunId||""),rewriteComplete:e.rewriteComplete===true||!t}}function Vt(e){let t=e?.["content-type"]?.trim();return t||null}function si(){return {rewriteTargets:new Set,changedFiles:new Set,deletedFiles:new Set}}function Y(e,t,n){let s=he(t.outputDir,n);s&&(e.changedFiles.add(s),e.deletedFiles.delete(s));}function rr(e,t,n){let s=he(t.outputDir,n);s&&(e.deletedFiles.add(s),e.changedFiles.delete(s));}function Ce(e,t){e.rewriteTargets.add(S.resolve(t));}async function ii(e){try{let t=await A.readFile(hr(e),"utf8"),n=JSON.parse(t);if(n&&typeof n=="object"&&n.pages&&typeof n.pages=="object"){if((n.schemaVersion===2||n.schemaVersion===3)&&n.assets&&typeof n.assets=="object")return {schemaVersion:3,updatedAt:String(n.updatedAt||""),pages:Object.fromEntries(Object.entries(n.pages).map(([s,r])=>[s,nr(r)])),assets:Object.fromEntries(Object.entries(n.assets).map(([s,r])=>[s,ri(r)]))};if(n.schemaVersion===1)return {schemaVersion:3,updatedAt:String(n.updatedAt||""),pages:Object.fromEntries(Object.entries(n.pages).map(([s,r])=>[s,nr(r)])),assets:{}}}}catch{}return wr()}function Kt(e){return JSON.parse(JSON.stringify(e))}async function oi(e,t){let n=hr(e);await A.mkdir(S.dirname(n),{recursive:true}),await A.writeFile(n,JSON.stringify(t,null,2),"utf8");}async function ye(e,t){if(!t.trackManifest)return;let n=async()=>{let s=Kt(t.manifest);s.updatedAt=new Date().toISOString(),t.manifest.updatedAt=s.updatedAt,await oi(e,s);};t.manifestSaveChain=t.manifestSaveChain.then(n,n),await t.manifestSaveChain;}function Qe(e){if(!e)return null;let t=e.trim();return t||null}function ai(e,t){let n=new Set,s=new Set([...Object.keys(e),...Object.keys(t)]);for(let r of s){let i=e[r],a=t[r];!i||!a||i===a||n.add(r);}return n}async function ci(e,t,n,s){let r=[...new Set(n.map(c=>c.trim()).filter(Boolean))],i=String(e.wpsuite?.runtimeToken||"").trim();if(r.length===0||!i)return new Map;let a=new URL("/wp-json/smartcloud-static-publisher/v1/change-tokens",e.sourceOrigin).toString();try{let c=await t.post(a,{timeout:3e4,failOnStatusCode:!1,headers:{"content-type":"application/json","x-static-publisher-token":i},data:JSON.stringify({urls:r})});if(!c.ok())return s.warn(`Change token lookup failed with HTTP ${c.status()}`,{endpoint:a,status:c.status()}),new Map;let o=await c.json().catch(()=>null);if(!o||!Array.isArray(o.items))return new Map;let u=new Map;for(let l of o.items)!l||typeof l.url!="string"||u.set(l.url,l);return u}catch(c){return s.warn("Change token lookup failed; falling back to sitemap metadata",{endpoint:a,error:c instanceof Error?`${c.name}: ${c.message.split(/\r?\n/u,1)[0]}`:"Unknown change-token request failure"}),new Map}}async function Qt(e,t,n,s,r){if(!n.enabled&&!n.trackManifest)return null;if(n.changeTokenCache.has(s))return n.changeTokenCache.get(s)??null;let a=(await ci(e,t,[s],r)).get(s)??null;return nn(e,s)&&(!a||a.supported!==true||!a.token)&&(a=await di(e,t,s,r)),a=li(e,a),n.changeTokenCache.set(s,a),a}function ui(e){return `subscriber=${e.wpsuite?.siteSettings?.subscriber===true?"1":"0"}`}function li(e,t){if(!t?.supported||!t.token)return t;let n=ui(e);return {...t,token:He(`${t.token}
|
|
8
|
-
${n}`,40),tokenSource:t.tokenSource?`${t.tokenSource}+site-subscriber`:"site-subscriber"}}async function
|
|
4
|
+
`;return e.replace(/<head\b[^>]*>/i,r=>`${r}${s} ${t}`)}function _s(e){let t=ce(e).trim();return t.startsWith("{")||t.startsWith("[")||t.includes("\\/")||/"@context"|"@type"/.test(t)}function Ns(e,t){let n=[...new Set(t)].filter(i=>i.includes("/")&&!/\\+\//.test(i)).map(i=>[i,ct(i)]).filter(([i,a])=>i!==a).sort((i,a)=>a[0].length-i[0].length);if(!n.length)return e;let s=i=>{let a=i;for(let[c,o]of n)a=a.split(c).join(o);return a},r=e.replace(/(<script\b[^>]*\btype=["']application\/(?:ld\+)?json["'][^>]*>)([\s\S]*?)(<\/script>)/gi,(i,a,c,o)=>`${a}${s(c)}${o}`);return r=r.replace(/(<meta\b[^>]*\bcontent=(['"]))([\s\S]*?)(\2[^>]*>)/gi,(i,a,c,o,u)=>_s(o)?`${a}${s(o)}${u}`:i),r}function Bs(e,t){if(!t)return null;let n=S.dirname(S.resolve(t)),s=S.resolve(e.outputDir),r=S.relative(n,s).replace(/\\/g,"/");return r?(r.startsWith(".")||(r=`./${r}`),r.endsWith("/")?r:`${r}/`):"./"}function Ws(e,t,n){let s=Bs(t,n);if(!s)return e;let r=e;for(let i of Ms){let a=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`(?:\\.{1,}/)+${a}`,"g"),o=new RegExp(`(?<!\\.)/${a}`,"g");r=r.replace(c,`${s}${i}`).replace(o,`${s}${i}`);let u=i.replace(/\//g,"\\/"),l=s.replace(/\//g,"\\/"),d=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),p=new RegExp(`(?:\\.{1,}\\\\/)+${d}`,"g"),g=new RegExp(`(?:\\.{1,}(?:\\\\/|\\\\))+${d}`,"g"),f=new RegExp(`(?<![\\.\\\\])\\/${d}`,"g");r=r.replace(p,`${l}${u}`).replace(g,`${l}${u}`).replace(f,`${l}${u}`);}return r}function Jt(e,t,n){if(e.urlRewriteMode==="absolute")return t;let s=(()=>{try{return new URL(t,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin)}catch{return null}})(),r=s?s.pathname:Kn(t,e.targetOrigin),i=s?`${s.search}${s.hash}`:"";return e.urlRewriteMode==="root-relative"?`${r}${i}`:`${Gn(e.outputDir,n,r)}${i}`}function Qt(e,t,n,s,r){ut(e,n,Jt(t,s,r));}function Hs(e,t,n,s,r){if(!n||n===s)return;ut(e,n,s);let i=Jt(t,n,r),a=Jt(t,s,r);ut(e,i,a);}function Vt(e,t,n,s,r={}){let i=e,a={};Qt(a,t,t.sourceOrigin,t.targetOrigin,s);for(let[o,u]of Object.entries(t.extraReplacements))Qt(a,t,o,u,s);for(let[o,u]of Object.entries(n))Qt(a,t,o,u,s);for(let[o,u]of Object.entries(r)){let l=n[o];!l||l===u||Hs(a,t,u,l,s);}let c=Object.entries(a).sort((o,u)=>u[0].length-o[0].length);for(let[o,u]of c)i=Us(i,o,u);return t.urlRewriteMode!=="absolute"&&(i=Ws(i,t,s)),i=Ns(i,c.map(([,o])=>o)),Ls(t,i,s)&&(i=qs(i)),i}async function zs(e,t,n,s){let r=S.join(e.outputDir,s),i=S.extname(r).toLowerCase(),a;try{a=await A.readFile(r,"utf8");}catch(u){if(u.code!=="ENOENT")throw u;return {changed:false}}let o=Vt(a,e,t,i===".js"||i===".mjs"?void 0:r,n);return o!==a?(await Ve(r,o,"utf8"),{changed:true}):{changed:false}}async function Qs(e,t){return await new Promise((n,s)=>{let r=o=>{if(c(),o?.error){s(new Error(o.error));return}n({changed:!!o?.changed});},i=o=>{c(),s(o);},a=o=>{c(),o!==0&&s(new Error(`Rewrite worker exited with code ${o}.`));},c=()=>{e.off("message",r),e.off("error",i),e.off("exit",a);};e.on("message",r),e.on("error",i),e.on("exit",a),e.postMessage({file:t});})}async function lt(e,t,n={}){let r=(n.files?[...new Set(n.files)].map(p=>S.resolve(p)).filter(p=>p.startsWith(S.resolve(e.outputDir))).map(p=>S.relative(e.outputDir,p).replace(/\\/g,"/")).filter(p=>p.length>0):await Ts(["**/*"],{cwd:e.outputDir,onlyFiles:true,dot:true})).filter(p=>p!=="asset-map.json"&&ye(p)),i=0;if(r.length===0)return 0;let a=Math.max(1,Number(e.rewriteConcurrency||e.assetDownloadConcurrency||1)),c=Math.max(1,Math.min(a,r.length,availableParallelism()));await n.onStart?.({totalFiles:r.length,workerCount:c});let o=0,u=0,l=null;if(c===1){for(let p of r){let g=await zs(e,t,n.previousAssetMap??{},p);g.changed&&(i+=1),u+=1,await n.onProgress?.({index:u,totalFiles:r.length,changedTextFiles:i,file:p,changed:g.changed});}return i}let d=Array.from({length:c},async()=>{let p=new Worker(new URL("./rewrite-worker.js",import.meta.url),{workerData:{config:e,assetMap:t,previousAssetMap:n.previousAssetMap??{}}});try{for(;!l;){let g=o;if(g>=r.length)return;o+=1;let f=r[g],w=await Qs(p,f);w.changed&&(i+=1),u+=1,await n.onProgress?.({index:u,totalFiles:r.length,changedTextFiles:i,file:f,changed:w.changed});}}catch(g){throw l=g instanceof Error?g:new Error(String(g)),l}finally{await p.terminate().catch(()=>{});}});return await Promise.all(d),i}var ie={error:0,warn:1,info:2,debug:3},Js=/^(?:authorization|proxyAuthorization|runtimeToken|siteKey|nonce|accessToken|refreshToken|accessKeyId|secretAccessKey|sessionToken|xStaticPublisherToken|xApiKey)$/i;function Re(e){return e.replace(/((?:x-static-publisher-token|authorization|proxy-authorization|x-api-key|aws-access-key-id|aws-secret-access-key|aws-session-token)\s*:\s*)[^\r\n]+/gi,"$1[REDACTED]").replace(/\b(Basic|Bearer)\s+[^\s]+/gi,"$1 [REDACTED]").replace(/([?&](?:token|access_token|refresh_token|api_key|key|nonce)=)[^&\s]+/gi,"$1[REDACTED]").replace(/((?:"|')?(?:runtimeToken|siteKey|nonce|accessToken|refreshToken|accessKeyId|secretAccessKey|sessionToken)(?:"|')?\s*[:=]\s*(?:"|'))[^"']+/gi,"$1[REDACTED]")}function pt(e){return typeof e=="string"?Re(e):Array.isArray(e)?e.map(t=>pt(t)):e instanceof Error?{name:e.name,message:Re(e.message),...e.stack?{stack:Re(e.stack)}:{}}:e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Js.test(t)?"[REDACTED]":pt(n)])):e}function ft(e){return e?pt(e):void 0}var Yn=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",dt=Yn?S.join(Yn,"current-progress.json"):"",Xn=Promise.resolve();function er(e){return e.includes("crawl")?"crawl":e.includes("deploy")?"deploy":e.includes("invalidate")?"invalidate":e}function Vs(e,t){let n={...e},s=new Set(["pagesQueued","pagesRendered","assetsQueued","sitemapsQueued","pagesDiscovered","assetsDiscovered","sitemapsDiscovered","pagesSaved","assetsSaved","donePages","doneAssets","doneSitemaps","changedTextFiles","uploaded","failed","index","totalFiles","pageQueue","assetQueue","sitemapQueue"]);for(let[r,i]of Object.entries(t)){let a=n[r];if(typeof a=="number"&&typeof i=="number"&&s.has(r)){n[r]=Math.max(a,i);continue}n[r]=i;}return n}function tr(e,t,n){dt&&(Xn=Xn.then(async()=>{let s=new Date,r=s.toISOString();await A.mkdir(S.dirname(dt),{recursive:true});let i=await A.readFile(dt,"utf8").then(h=>JSON.parse(h)).catch(()=>null),a=i&&typeof i.details=="object"&&i.details?i.details:{},c=er(e),o=i?.currentStep||er(i?.source||""),u=i?.startedAt||r,l={...i?.stepDurationsSec??{}},d=i?.stepStartedAt||r;if(o&&o!==c&&i?.stepStartedAt){let h=Math.max(0,Math.round((s.getTime()-new Date(i.stepStartedAt).getTime())/1e3));l[o]=(l[o]??0)+h,d=r;}let p=Math.max(0,Math.round((s.getTime()-new Date(d).getTime())/1e3)),g=Math.max(0,Math.round((s.getTime()-new Date(u).getTime())/1e3)),f=Re(t),w=ft(n)??{},m={checkedAt:r,source:e,message:f,details:Vs(a,w),startedAt:u,currentStep:c,stepStartedAt:d,stepElapsedSec:p,totalElapsedSec:g,stepDurationsSec:l};await A.writeFile(dt,JSON.stringify(m,null,2),"utf8");}).catch(()=>{}));}async function nr(e,t){await A.mkdir(S.dirname(e),{recursive:true}),await A.appendFile(e,`${JSON.stringify(pt(t))}
|
|
5
|
+
`,"utf8");}function Ks(e,t){let n=typeof t?.phase=="string"?t.phase.trim():"";return n||(e==="page"?"render-pages":e==="asset"?"download-assets":e==="sitemap"?"discovery":e==="timing"&&typeof t?.name=="string"&&t.name.trim()||"crawl")}function Gs(e,t,n){let s=ft(n);return {checkedAt:new Date().toISOString(),currentStep:Ks(e,s),level:e,message:Re(t),details:s??{}}}var Me=class{constructor(t,n,s="info"){this.logDir=t;this.logFile=n;this.level=s;this.ensureLogFileReady();}logDir;logFile;level;startedAt=Date.now();marks=new Map;initPromise=null;writeQueue=Promise.resolve();writeError=null;get logPath(){return S.join(this.logDir,this.logFile)}artifactPath(t){return this.logFile.endsWith(".log.jsonl")?S.join(this.logDir,this.logFile.replace(/\.log\.jsonl$/u,`${t}.jsonl`)):S.join(this.logDir,`${this.logFile}${t}.jsonl`)}get errorsPath(){return this.artifactPath(".errors")}get rejectedPath(){return this.artifactPath(".rejected")}ensureLogFileReady(){return this.initPromise||(this.initPromise=(async()=>{await A.mkdir(this.logDir,{recursive:true}),await A.writeFile(this.logPath,"","utf8");})()),this.initPromise}enqueueTask(t){this.writeQueue=this.writeQueue.then(t).catch(n=>{this.writeError=n instanceof Error?n:new Error(String(n));});}enqueueLine(t){this.enqueueTask(async()=>{await this.ensureLogFileReady(),await A.appendFile(this.logPath,`${t}
|
|
6
|
+
`,"utf8");});}enqueueJsonLine(t,n){this.enqueueTask(()=>nr(t,n));}accepts(t){return ie[t]<=ie[this.level]}push(t,n,s){if(!this.accepts(t))return;let r=Re(n),i=ft(s),a=JSON.stringify({time:new Date().toISOString(),level:t,message:r,...i||{}});this.enqueueLine(a),t==="error"?console.error(`[ERROR] ${r}`,i?JSON.stringify(i):""):t==="warn"?console.warn(`[WARN] ${r}`,i?JSON.stringify(i):""):console.log(`[${t.toUpperCase().padEnd(5)}] ${r}`);}info(t,n){this.push("info",t,n);}progress(t,n){tr(this.logFile,t,n);}debug(t,n){this.push("debug",t,n);}warn(t,n){this.push("warn",t,n);}reject(t,n,s,r,i){let a={kind:t,url:n,reason:s,...r?{source:r}:{},...i||{}};this.enqueueJsonLine(this.rejectedPath,a),this.accepts("debug")&&this.push("debug",`Rejected ${t} ${n}: ${s}`,a);}error(t,n){this.enqueueJsonLine(this.errorsPath,{message:t,...n||{}}),this.push("error",t,n);}mark(t){this.marks.set(t,Date.now());}endMark(t,n){let s=this.marks.get(t);if(!s)return;let r=Date.now()-s,i=Number((r/1e3).toFixed(2));this.push("info",`Timing ${t}: ${i}s`,{name:t,ms:r,seconds:i,...n||{}});}async flush(){let t=Date.now()-this.startedAt,n=Number((t/1e3).toFixed(2));if(this.push("info",`Total time: ${n}s`,{name:"total",ms:t,seconds:n}),await this.writeQueue,this.writeError)throw this.writeError}},gt=class{constructor(t,n="info"){this.logDir=t;this.level=typeof n=="boolean"?n?"debug":"info":n,this.ensureLogFileReady();}logDir;startedAt=Date.now();marks=new Map;initPromise=null;writeQueue=Promise.resolve();writeError=null;level;get logPath(){return S.join(this.logDir,"crawl.log.jsonl")}get currentEventPath(){return S.join(this.logDir,"current-crawl-event.json")}get rejectedPath(){return S.join(this.logDir,"rejected.jsonl")}get ignoredPath(){return S.join(this.logDir,"ignored.jsonl")}get skippedPath(){return S.join(this.logDir,"skipped-http.jsonl")}get errorsPath(){return S.join(this.logDir,"errors.jsonl")}get timingsPath(){return S.join(this.logDir,"timings.jsonl")}ensureLogFileReady(){return this.initPromise||(this.initPromise=(async()=>{await A.mkdir(this.logDir,{recursive:true}),await A.writeFile(this.logPath,"","utf8");})()),this.initPromise}enqueueTask(t){this.writeQueue=this.writeQueue.then(t).catch(n=>{this.writeError=n instanceof Error?n:new Error(String(n));});}enqueueLine(t){this.enqueueTask(async()=>{await this.ensureLogFileReady(),await A.appendFile(this.logPath,`${t}
|
|
7
|
+
`,"utf8");});}enqueueJsonLine(t,n){this.enqueueTask(()=>nr(t,n));}updateCurrentEvent(t,n,s){let r=Gs(t,n,s);this.enqueueTask(async()=>{await A.mkdir(this.logDir,{recursive:true}),await A.writeFile(this.currentEventPath,JSON.stringify(r,null,2),"utf8");});}push(t,n,s){let r=Re(n),i=ft(s),a=JSON.stringify({time:new Date().toISOString(),level:t,message:r,...i||{}});this.enqueueLine(a),this.updateCurrentEvent(t,r,i),t==="error"?console.error(r,i||""):t==="warn"?console.warn(r,i||""):(ie[this.level]>=ie.debug||["summary","page","sitemap","asset","timing"].includes(t))&&console.log(r);}info(t,n){this.push("info",t,n);}debug(t,n){ie[this.level]<ie.debug||this.push("debug",t,n);}progress(t,n){tr("crawl.log.jsonl",t,n),this.updateCurrentEvent("progress",t,n);}checkpoint(t,n){this.updateCurrentEvent("checkpoint",t,n);}page(t,n){this.push("page",t,n);}sitemap(t,n){this.push("sitemap",t,n);}asset(t,n){this.push("asset",t,n);}warn(t,n){this.push("warn",t,n);}error(t,n){this.enqueueJsonLine(this.errorsPath,{message:t,...n||{}}),this.push("error",t,n);}summary(t,n){this.push("summary",t,n);}mark(t){this.marks.set(t,Date.now());}endMark(t,n){let s=this.marks.get(t);if(!s)return;let r=Date.now()-s,i={name:t,ms:r,seconds:Number((r/1e3).toFixed(2)),...n||{}};this.enqueueJsonLine(this.timingsPath,i),this.push("timing",`Timing ${t}: ${i.seconds}s`,i);}reject(t,n,s,r){let i={kind:t,url:n,reason:s,source:r};this.enqueueJsonLine(this.rejectedPath,i),ie[this.level]>=ie.debug&&this.push("reject",`Rejected ${t} ${n}: ${s}`,i);}ignore(t,n,s,r){let i={kind:t,url:n,reason:s,source:r};this.enqueueJsonLine(this.ignoredPath,i),ie[this.level]>=ie.debug&&this.push("ignore",`Ignored ${t} ${n}: ${s}`,i);}skip(t,n,s,r){let i={kind:t,url:n,status:s,source:r};this.enqueueJsonLine(this.skippedPath,i),this.push("warn",`Skipped ${t} ${n}: HTTP ${s}`,i);}async flush(){let t=Date.now()-this.startedAt,n={name:"total",ms:t,seconds:Number((t/1e3).toFixed(2))};if(this.enqueueJsonLine(this.timingsPath,n),await this.writeQueue,this.writeError)throw this.writeError}};var Kt="(?:css|js|mjs|json|map|xml|xsl|rss|atom|txt|enc|jws|png|jpe?g|gif|webp|avif|svg|ico|woff2?|ttf|otf|eot|pdf|mp4|webm)";function rr(e){return !!e&&/^(?:\.{1,2}\/)?[A-Za-z0-9@_][A-Za-z0-9@._/-]*\.(?:js|mjs)(?:[?#][^\s<>\\]*)?$/i.test(e)&&!e.startsWith("/")&&!e.startsWith("//")&&!/^[a-z][a-z0-9+.-]*:/i.test(e)&&!/(?:^|\/)node_modules(?:\/|$)|(?:^|\/)\.pnpm(?:\/|$)/i.test(e)}function sr(e){let t=new Set,n=[],s=/\bimport\s*\(\s*["'`]([^"'`\s<>\\]+)["'`]\s*\)/g,r=/\b(?:[A-Za-z_$][\w$]*\.)?u\s*=\s*(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>\s*["'`]([^"'`\s<>\\]+)["'`]/g;for(let i of e.matchAll(s))i[1]&&rr(i[1])&&n.push({index:i.index??0,value:i[1]});for(let i of e.matchAll(r))i[1]&&rr(i[1])&&n.push({index:i.index??0,value:i[1]});for(let i of n.sort((a,c)=>a.index-c.index))t.add(i.value);return [...t]}function ir(e,t){return typeof e=="string"&&e.length>0&&t?.supported===true&&typeof t.token=="string"&&t.token.length>0&&e===t.token}function or(e,t){try{let n=new URL(e),s=new URL(t,n);if(s.origin!==n.origin)return !1;let r=n.pathname.replace(/\/+$/,"");if(r&&s.pathname!==r&&!s.pathname.startsWith(`${r}/`))return !1;let i=r?s.pathname.slice(r.length)||"/":s.pathname;return ["/wp-includes/","/wp-content/plugins/","/wp-content/themes/","/wp-content/mu-plugins/"].some(a=>i.startsWith(a))}catch{return false}}var ei=["text/css","javascript","image/","font/","application/font","application/json","application/xml","text/xml","application/rss+xml","application/atom+xml","application/xslt+xml","text/xsl","image/svg+xml"],Sr=new Set([".css",".js",".mjs",".json",".map",".xml",".xsl",".rss",".atom",".txt",".enc",".jws",".png",".jpg",".jpeg",".gif",".webp",".avif",".svg",".ico",".woff",".woff2",".ttf",".otf",".eot",".pdf",".mp4",".webm"]),Pr=new Set(["",".html",".htm"]),ti=new Set([".css",".xml",".xsl",".svg",".json",".html",".htm",".txt",".enc",".jws"]),ni=["/wp-content/","/wp-includes/","/wp-admin/","/static/","/assets/","/build/","/_next/"];function ri(e){let t=[],n="full",s="full",r=false,i=false,a="";for(let c=0;c<e.length;c++){let o=e[c];if(o==="--retry-timeouts")n="retry-timeouts",r=true;else if(o==="--resume")r=true;else if(o==="--resume-rewrite")r=true,i=true;else if(o==="--crawl-mode"){let u=e[++c];if(!u)throw new Error("--crawl-mode requires a value");s=u==="incremental"?"incremental":"full",r||=s==="incremental";}else if(o.startsWith("--crawl-mode="))s=o.slice(13)==="incremental"?"incremental":"full",r||=s==="incremental";else if(o==="--incremental")s="incremental",r=true;else if(o==="--url"){let u=e[++c];if(!u)throw new Error("--url requires a value");n="single-url",r=true,t.push(u);}else if(o.startsWith("--url="))n="single-url",r=true,t.push(o.slice(6));else if(o==="--urls"){let u=e[++c];if(!u)throw new Error("--urls requires a file path");n="single-url",r=true,t.push(`@${u}`);}else if(o==="--content-sync-plan"){let u=e[++c];if(!u)throw new Error("--content-sync-plan requires a file path");n="content-sync",s="incremental",r=true,a=S.resolve(u);}else o.startsWith("--content-sync-plan=")&&(n="content-sync",s="incremental",r=true,a=S.resolve(o.slice(20)));}return {mode:n,crawlMode:s,urls:t,preserveOutput:r,resumeRewrite:i,contentSyncPlanPath:a}}function nn(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.resolve(e):""}function si(){let e=nn();return e?S.resolve(e,".."):""}function ii(){let e=process.env.STATIC_PUBLISHER_WP_ROOT||process.env.WPSUITE_STATIC_PUBLISHER_WP_ROOT||"";return e.trim()?S.resolve(e):""}function oi(e){let t=e.trim(),n=[{alias:"@storage-root",root:si(),requiredEnv:"STATIC_PUBLISHER_RUNTIME_DIR or WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR"},{alias:"@runtime",root:nn(),requiredEnv:"STATIC_PUBLISHER_RUNTIME_DIR or WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR"},{alias:"@wp-root",root:ii(),requiredEnv:"STATIC_PUBLISHER_WP_ROOT or WPSUITE_STATIC_PUBLISHER_WP_ROOT"}];for(let s of n){if(t!==s.alias&&!t.startsWith(`${s.alias}/`))continue;if(!s.root)return {resolvedPath:null,alias:s.alias,requiredEnv:s.requiredEnv};let r=t.slice(s.alias.length).replace(/^\/+/,"");return {resolvedPath:r?S.resolve(s.root,r):s.root,alias:s.alias}}return {resolvedPath:S.resolve(t)}}function br(e){let t=String(process.env.STATIC_PUBLISHER_CRAWL_MANIFEST_PATH||"").trim();if(t)return S.resolve(t);let n=nn();return n?S.join(n,"crawl-manifest.json"):S.join(e.outputDir,".crawl-manifest.json")}function vr(){return {schemaVersion:4,updatedAt:"",pages:{},assets:{}}}function ar(e){return {url:String(e.url||""),outputPath:String(e.outputPath||""),contentType:typeof e.contentType=="string"&&e.contentType?e.contentType:null,changeToken:typeof e.changeToken=="string"?e.changeToken:null,tokenSource:typeof e.tokenSource=="string"?e.tokenSource:null,sitemapLastmod:typeof e.sitemapLastmod=="string"?e.sitemapLastmod:null,discoveredPages:Array.isArray(e.discoveredPages)?e.discoveredPages.map(t=>String(t)):[],discoveredAssets:Array.isArray(e.discoveredAssets)?e.discoveredAssets.map(t=>String(t)):[],lastCrawledAt:String(e.lastCrawledAt||""),lastSeenRunId:String(e.lastSeenRunId||""),rewriteComplete:e.rewriteComplete===true}}function ai(e){let t=e.isText===true;return {url:String(e.url||""),outputPath:String(e.outputPath||""),isText:t,contentType:typeof e.contentType=="string"&&e.contentType?e.contentType:null,changeToken:typeof e.changeToken=="string"?e.changeToken:null,tokenSource:typeof e.tokenSource=="string"?e.tokenSource:null,discoveredAssets:Array.isArray(e.discoveredAssets)?e.discoveredAssets.map(n=>String(n)):[],lastCrawledAt:String(e.lastCrawledAt||""),lastSeenRunId:String(e.lastSeenRunId||""),rewriteComplete:e.rewriteComplete===true||!t}}function Zt(e){let t=e?.["content-type"]?.trim();return t||null}function ci(){return {rewriteTargets:new Set,changedFiles:new Set,deletedFiles:new Set}}function Y(e,t,n){let s=we(t.outputDir,n);s&&(e.changedFiles.add(s),e.deletedFiles.delete(s));}function cr(e,t,n){let s=we(t.outputDir,n);s&&(e.deletedFiles.add(s),e.changedFiles.delete(s));}function Ie(e,t){e.rewriteTargets.add(S.resolve(t));}async function ui(e){try{let t=await A.readFile(br(e),"utf8"),n=JSON.parse(t);if(n&&typeof n=="object"&&n.pages&&typeof n.pages=="object"){if((n.schemaVersion===2||n.schemaVersion===3||n.schemaVersion===4)&&n.assets&&typeof n.assets=="object")return {schemaVersion:4,updatedAt:String(n.updatedAt||""),pages:Object.fromEntries(Object.entries(n.pages).map(([s,r])=>[s,ar(r)])),assets:Object.fromEntries(Object.entries(n.assets).map(([s,r])=>[s,ai(r)]))};if(n.schemaVersion===1)return {schemaVersion:4,updatedAt:String(n.updatedAt||""),pages:Object.fromEntries(Object.entries(n.pages).map(([s,r])=>[s,ar(r)])),assets:{}}}}catch{}return vr()}function Yt(e){return JSON.parse(JSON.stringify(e))}async function li(e,t){let n=br(e);await A.mkdir(S.dirname(n),{recursive:true}),await A.writeFile(n,JSON.stringify(t,null,2),"utf8");}async function Se(e,t){if(!t.trackManifest)return;let n=async()=>{let s=Yt(t.manifest);s.updatedAt=new Date().toISOString(),t.manifest.updatedAt=s.updatedAt,await li(e,s);};t.manifestSaveChain=t.manifestSaveChain.then(n,n),await t.manifestSaveChain;}function Ke(e){if(!e)return null;let t=e.trim();return t||null}function di(e,t){let n=new Set,s=new Set([...Object.keys(e),...Object.keys(t)]);for(let r of s){let i=e[r],a=t[r];!i||!a||i===a||n.add(r);}return n}async function Cr(e,t,n,s){let r=[...new Set(n.map(c=>c.trim()).filter(Boolean))],i=String(e.wpsuite?.runtimeToken||"").trim();if(r.length===0||!i)return new Map;let a=new URL("/wp-json/smartcloud-static-publisher/v1/change-tokens",e.sourceOrigin).toString();try{let c=await t.post(a,{timeout:3e4,failOnStatusCode:!1,headers:{"content-type":"application/json","x-static-publisher-token":i},data:JSON.stringify({urls:r})});if(!c.ok())return s.warn(`Change token lookup failed with HTTP ${c.status()}`,{endpoint:a,status:c.status()}),new Map;let o=await c.json().catch(()=>null);if(!o||!Array.isArray(o.items))return new Map;let u=new Map;for(let l of o.items)!l||typeof l.url!="string"||u.set(l.url,l);return u}catch(c){return s.warn("Change token lookup failed; falling back to sitemap metadata",{endpoint:a,error:c instanceof Error?`${c.name}: ${c.message.split(/\r?\n/u,1)[0]}`:"Unknown change-token request failure"}),new Map}}async function wt(e,t,n,s,r){if(!n.enabled&&!n.trackManifest)return null;if(n.changeTokenCache.has(s))return n.changeTokenCache.get(s)??null;let a=(await Cr(e,t,[s],r)).get(s)??null;return on(e,s)&&(!a||a.supported!==true||!a.token)&&(a=await fi(e,t,s,r)),a=Rr(e,a),n.changeTokenCache.set(s,a),a}async function pi(e,t,n,s,r){if(!n.trackManifest)return;let i=[...new Set(s.map(a=>a.trim()).filter(Boolean))].filter(a=>!n.changeTokenCache.has(a));for(let a=0;a<i.length;a+=250){let c=i.slice(a,a+250),o=await Cr(e,t,c,r);for(let u of c)n.changeTokenCache.set(u,Rr(e,o.get(u)??null));}}function gi(e){return `subscriber=${e.wpsuite?.siteSettings?.subscriber===true?"1":"0"}`}function Rr(e,t){if(!t?.supported||!t.token||t.tokenSource==="wp-media-file")return t;let n=gi(e);return {...t,token:Je(`${t.token}
|
|
8
|
+
${n}`,40),tokenSource:t.tokenSource?`${t.tokenSource}+site-subscriber`:"site-subscriber"}}async function fi(e,t,n,s){try{let r=await t.get(n,{timeout:Math.min(e.navigationTimeoutMs,15e3),failOnStatusCode:!1});if(r.status()!==404)return s.warn(`Generated 404 fallback token skipped for ${n}`,{url:n,status:r.status(),requestPath:e.generated404RequestPath,source:"generated-404-change-token-fallback"}),null;let i=await r.text().catch(()=>""),a=Je(`${n}
|
|
9
9
|
404
|
|
10
|
-
${i}`,40);return s.info(`Using generated 404 fallback change token for ${n}`,{url:n,requestPath:e.generated404RequestPath,source:"generated-404-change-token-fallback"}),{url:n,supported:!0,token:a,tokenSource:"generated-404-response-hash",postId:null,dependencyPostIds:[],reason:null}}catch(r){return s.warn(`Generated 404 fallback token lookup failed for ${n}`,{url:n,error:String(r),requestPath:e.generated404RequestPath,source:"generated-404-change-token-fallback"}),null}}async function pi(e,t,n,s,r,i){let a=nn(e,r);if(!s.enabled)return {action:"render",changeToken:s.trackManifest?await Qt(e,t,s,r,i):null};let c=s.manifest.pages[r];if(!c)return {action:"render",changeToken:await Qt(e,t,s,r,i)};let o=await Qt(e,t,s,r,i);if(o?.supported&&o.token)return c.changeToken===o.token?a&&!await gi(e,t,r,i)?{action:"render",changeToken:o}:{action:"reuse",changeToken:o}:{action:"render",changeToken:o};let u=Qe(n.sitemapLastmodByPage[r]);return u&&c.sitemapLastmod&&c.sitemapLastmod===u?{action:"reuse",changeToken:o}:{action:"render",changeToken:o}}async function gi(e,t,n,s){try{let i=(await t.get(n,{timeout:Math.min(e.navigationTimeoutMs,15e3),failOnStatusCode:!1})).status();return i===404?!0:(s.warn(`Generated 404 request path no longer returns 404 for ${n}`,{url:n,status:i,requestPath:e.generated404RequestPath,source:"generated-404-status-probe"}),!1)}catch(r){return s.warn(`Generated 404 status probe failed for ${n}`,{url:n,error:String(r),requestPath:e.generated404RequestPath,source:"generated-404-status-probe"}),false}}async function fi(e,t,n,s,r){let i=sr(n.previousManifest,void 0,s,"previous-manifest"),a=0;for(let[p,g]of Object.entries(n.manifest.pages))if(!n.seenPages.has(p)){rr(r,e,g.outputPath);try{await A.unlink(g.outputPath);}catch(f){(f.code||"")!=="ENOENT"&&s.warn(`Failed to remove stale incremental page output for ${p}`,{url:p,outputPath:g.outputPath,error:String(f)});}delete n.manifest.pages[p],a++;}let c=sr(n.manifest,n.runId,s,"active-manifest"),o=new Set,u=new Set;for(let p of c){for(let w of Je(e,p))o.add(w);let g=n.manifest.assets[p]?.outputPath;g&&u.add(g);let f=Ee(e,t.assetMap,p);f&&u.add(f);}for(let p of Object.keys(n.manifest.assets))c.has(p)||delete n.manifest.assets[p];let l=0,d=0;for(let p of i){let g=new Set,f=n.previousManifest.assets[p]?.outputPath;f&&g.add(f);let w=Ee(e,t.assetMap,p);if(!c.has(p)&&w)g.add(w);else if(!c.has(p)){let m=Ei(e,p,s,"incremental-cleanup");m&&(g.add(m.originalFilePath),m.hashedFilePath&&g.add(m.hashedFilePath));}for(let m of g)if(!u.has(m)){rr(r,e,m);try{await A.unlink(m),l++;}catch(h){(h.code||"")!=="ENOENT"&&s.warn(`Failed to remove stale incremental asset output for ${p}`,{url:p,outputPath:m,error:String(h)});}}for(let m of Je(e,p))o.has(m)||Object.prototype.hasOwnProperty.call(t.assetMap,m)&&(delete t.assetMap[m],d++);}(a>0||l>0||d>0)&&s.info(`Incremental cleanup removed ${a} stale pages, ${l} stale assets, ${d} stale asset mappings`,{removedPages:a,removedAssets:l,removedAssetMappings:d,phase:"incremental-cleanup"});}function sr(e,t,n,s){let r=new Set,i=a=>{let c=a.trim();if(c){if(n){let o=Se(c,n,"asset",s??"manifest");if(!o)return;r.add(o.toString());return}r.add(c);}};for(let a of Object.values(e.pages))for(let c of a.discoveredAssets||[])i(c);for(let[a,c]of Object.entries(e.assets||{}))t&&c.lastSeenRunId!==t||i(a);return r}function ir(e,t,n){for(let s of t)for(let r of Je(e,s))if(n.has(r))return true;return false}function mi(e,t,n,s,r){let i=new Set(n.rewriteTargets);for(let c of Object.values(t.manifest.pages))c.rewriteComplete||i.add(S.resolve(c.outputPath));for(let c of Object.values(t.manifest.assets))c.isText&&!c.rewriteComplete&&i.add(S.resolve(c.outputPath));let a=ai(s,r);if(a.size===0)return [...i];for(let c of Object.values(t.manifest.pages))ir(e,c.discoveredAssets,a)&&i.add(S.resolve(c.outputPath));for(let[c,o]of Object.entries(t.manifest.assets)){o.isText&&ir(e,o.discoveredAssets,a)&&i.add(S.resolve(o.outputPath));for(let u of Je(e,c))if(a.has(u)){Y(n,e,o.outputPath),o.isText&&i.add(S.resolve(o.outputPath));break}}return [...i]}function hi(e,t){let n=t?new Set(Array.from(t,r=>S.resolve(r))):null,s=r=>n===null||n.has(S.resolve(r));for(let r of Object.values(e.manifest.pages))s(r.outputPath)&&(r.rewriteComplete=true);for(let r of Object.values(e.manifest.assets)){if(!r.isText){r.rewriteComplete=true;continue}s(r.outputPath)&&(r.rewriteComplete=true);}}function wi(e,t,n){let s=new Set,r=i=>{if(!i)return;let a=he(e.outputDir,i);a&&s.add(a);};for(let i of t.donePages)r(le(e,i));for(let i of Object.values(n.manifest.pages))i.lastSeenRunId===n.runId&&r(i.outputPath);for(let i of t.doneAssets)r(Ee(e,t.assetMap,i));for(let i of Object.values(n.manifest.assets))i.lastSeenRunId===n.runId&&r(i.outputPath);return s}async function yi(e,t,n,s,r){let i=[...s.deletedFiles].sort(),a=wi(e,t,n),c=0;for(let l of [...a].sort()){try{if((await A.stat(S.join(e.outputDir,l))).isFile())continue}catch{}c++,r.warn(`Active output is missing after crawl: ${l}`,{phase:"deploy-plan",file:l,outputPath:S.join(e.outputDir,l)});}if(c>0&&r.warn(`Detected ${c} active output file(s) missing before deploy plan save.`,{phase:"deploy-plan",missingActiveOutputs:c}),i.length===0)return [];let o=[],u=0;for(let l of i){if(!a.has(l)){o.push(l);continue}u++;let d=S.join(e.outputDir,l),p;try{p=(await A.stat(d)).isFile();}catch{p=false;}r.warn(`Deploy plan protected active output from deletion: ${l}`,{phase:"deploy-plan",file:l,outputPath:d,exists:p});}return u>0&&r.info(`Deploy plan skipped ${u} active output deletion(s).`,{phase:"deploy-plan",protectedDeletes:u,deletedFiles:o.length}),o}function Je(e,t){let n=new Set([t]);try{let s=new URL(t),i=[new URL(e.sourceOrigin).origin,...Object.keys(e.extraReplacements||{})];if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{i.push(new URL(e.targetOrigin).origin);}catch{}for(let a of i)try{n.add(new URL(a).origin+s.pathname+s.search);}catch{}n.add(s.pathname+s.search),n.add(s.pathname);}catch{}return [...n]}function Si(e,t){let n=new Set([t]);try{let s=new URL(t),i=[new URL(e.sourceOrigin).origin,...Object.keys(e.extraReplacements||{})];if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{i.push(new URL(e.targetOrigin).origin);}catch{}for(let a of i)try{n.add(new URL(a).origin+s.pathname+s.search);}catch{}n.add(s.pathname+s.search);}catch{}return [...n]}function yr(e,t){let n=e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/"?e.targetOrigin:"https://relative.invalid/";try{let s=new URL(t,n);return S.join(e.outputDir,tn(s.pathname))}catch{return null}}function Pi(e,t,n){for(let s of Si(e,n)){let r=t[s];if(!r)continue;let i=yr(e,r);if(i)return {outputPath:i,publicUrl:r}}return null}function bi(e,t,n){for(let s of Je(e,n)){let r=t[s];if(!r)continue;let i=yr(e,r);if(i)return i}return null}function Ee(e,t,n){let s=bi(e,t,n);if(s)return s;try{return yt(e,n).originalFilePath}catch{return null}}function vi(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.join(S.resolve(e),"queue-runner-heartbeat.json"):""}async function or(e){let t=vi();if(t)try{let n=await A.readFile(t,"utf8"),s=JSON.parse(n);if(!s||typeof s!="object")return;await A.writeFile(t,JSON.stringify({...s,checkedAt:new Date().toISOString(),status:"running",currentStep:"rewrite",message:e},null,2),"utf8");}catch{}}function Ci(e,t){let n=new Set;for(let s of t.donePages)n.add(S.resolve(le(e,s)));for(let s of t.doneAssets){let r=Ee(e,t.assetMap,s);!r||!we(r)||n.add(S.resolve(r));}for(let s of t.doneSitemaps){let r=Ee(e,t.assetMap,s);!r||!we(r)||n.add(S.resolve(r));}return [...n]}var ht="re:",gt=new Map;function Ri(e){if(!e.startsWith(ht))return null;let t=gt.get(e);if(t!==void 0)return t||null;let n=e.slice(ht.length).trim();if(!n)return gt.set(e,false),null;try{let s=new RegExp(n);return gt.set(e,s),s}catch{return console.warn(`[crawl] Ignoring invalid path matcher regex: ${e}`),gt.set(e,false),null}}function en(e,t){let n=Ri(t);return n?n.test(e):t.startsWith(ht)?false:e.startsWith(t)}function Ii(e,t){return t.find(n=>en(e,n))}function Sr(e,t){let n=Ii(t.pathname,e.blockedPathPrefixes);if(n)return n.startsWith(ht)?`blocked path regex: ${n}`:`blocked path prefix: ${n}`;let s=e.blockedSearchFragments.find(r=>t.search.includes(r));return s?`blocked search fragment: ${s}`:null}function xi(e){let t=new URL(e.sourceOrigin),n=new Set([t.hostname,...e.allowedAssetHosts]);if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{n.add(new URL(e.targetOrigin).hostname);}catch{}for(let s of Object.keys(e.extraReplacements||{}))try{n.add(new URL(s).hostname);}catch{}return n}function Ai(e,t){return xi(e).has(t.hostname)}function Ti(e){let t=ce(e.trim()).replace(/\\\//g,"/").replace(/^['"]|['"]$/g,"").trim();return t=t.replace(/[)]+$/g,"").trim(),t=t.replace(/;.*$/g,"").trim(),t}function Gt(e){let t=ce(e).replace(/\\\//g,"/");return /[{}]|\bwindow\.|\blocation\.|\bincludes\(|\?\?null|\+|%7B|%7D|%22|<|>|\s/.test(t)||/[()[\]'"]/.test(t)}function ki(e){let t=ce(e).replace(/\\\//g,"/").trim(),n=S.extname(t).toLowerCase();return fr.has(n)||mr.has(n)?false:/^(?:this|[A-Za-z_$][\w$]*)\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(t)}function Me(e){return Ys.some(t=>e.pathname.startsWith(t))}function H(e,t,n=e.sourceOrigin,s,r="url"){let i=Ti(t);if(!i||i.startsWith("data:")||i.startsWith("blob:")||i.startsWith("mailto:")||i.startsWith("tel:")||i.startsWith("#"))return s?.ignore(r,t,"empty or unsupported scheme",n),null;if(Gt(i))return s?.ignore(r,t,"looks like JavaScript/code fragment",n),null;if(ki(i))return s?.ignore(r,t,"looks like JavaScript property access",n),null;try{let a=new URL(i,n);if(Pr(a))return s?.reject(r,t,"malformed URL encoding",n),null;if(!["http:","https:"].includes(a.protocol))return s?.ignore(r,t,"unsupported protocol: ",n),null;if(!Ai(e,a))return s?.ignore(r,a.toString(),"host not allowed",n),null;let c=Sr(e,a);if(c)return s?.reject(r,a.toString(),c,n),null;let o=new URL(e.sourceOrigin);return a.protocol=o.protocol,a.host=o.host,a.hash="",a}catch{return s?.reject(r,t,"invalid URL",n),null}}function Pr(e){try{return decodeURIComponent(e.pathname),decodeURIComponent(e.search),decodeURIComponent(e.hash),!1}catch{return true}}function Se(e,t,n,s){try{let r=new URL(e);return Pr(r)?(t.reject(n,e,"malformed URL encoding",s),null):r.protocol!=="http:"&&r.protocol!=="https:"?(t.reject(n,e,`unsupported protocol: ${r.protocol}`,s),null):r}catch{return t.reject(n,e,"invalid URL",s),null}}function br(e){return fr.has(S.extname(e.pathname).toLowerCase())}function Pe(e){return Me(e)?false:mr.has(S.extname(e.pathname).toLowerCase())}function Fe(e){let t=e.pathname.toLowerCase();return t.endsWith(".xml")&&(t.includes("sitemap")||t.endsWith("/sitemap.xml"))}function q(e,t){return !!(Fe(t)||t.pathname==="/robots.txt"||t.pathname==="/llms.txt"||t.pathname.toLowerCase().endsWith(".xsl")||e.assetPathPrefixes.length>0&&e.assetPathPrefixes.some(n=>en(t.pathname,n))||br(t)||!Pe(t)&&!Me(t))}function le(e,t){let n=new URL(t),s=tn(n.pathname);return s.endsWith("/")?s+="index.html":S.extname(s)||(s+="/index.html"),S.join(e.outputDir,s)}function tn(e){try{return decodeURIComponent(e)}catch{return e}}function $i(e){if(!e.generated404RequestPath)return null;try{let t=new URL(e.generated404RequestPath,e.sourceOrigin);return !t.pathname.endsWith("/")&&S.extname(t.pathname)===""&&(t.pathname+="/"),t.hash="",t.toString()}catch{return null}}function nn(e,t){let n=$i(e);if(!n)return false;try{return new URL(t,e.sourceOrigin).toString()===n}catch{return false}}function yt(e,t){let n=new URL(t),s=tn(n.pathname);s.endsWith("/")&&(s+="index.html");let r=!!n.search,i=s,a=S.join(e.outputDir,i),c=Nt(e.targetOrigin,i),o=`${c}${n.search}`;if(!r)return {originalPathname:i,originalFilePath:a,originalPublicUrl:c,originalPublicUrlWithSearch:o,preferQueryHashed:r};let u=S.extname(s),d=`${u?s.slice(0,-u.length):s}.${He(n.search)}${u||".bin"}`;return {originalPathname:i,originalFilePath:a,originalPublicUrl:c,originalPublicUrlWithSearch:o,preferQueryHashed:r,hashedPathname:d,hashedFilePath:S.join(e.outputDir,d),hashedPublicUrl:Nt(e.targetOrigin,d)}}function Ei(e,t,n,s){let r=Se(t,n,"asset",s);return r?yt(e,r.toString()):null}function Mi(e,t,n,s,r){t[n]=s;try{let i=new URL(n),c=[new URL(e.sourceOrigin).origin,...Object.keys(e.extraReplacements||{})];if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{c.push(new URL(e.targetOrigin).origin);}catch{}for(let o of c)try{let u=new URL(o);t[u.origin+i.pathname+i.search]=s;}catch{}try{let o=(()=>{let u=new URL(s,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin);return `${u.pathname}${u.search}`})();t[i.pathname+i.search]=o;}catch{}try{let o=new URL(s,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin).pathname;t[i.pathname]=o;}catch{}try{let o=new URL(r,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin).pathname;t[i.pathname]=o;}catch{}}catch{}}async function vr(e){try{return await A.readFile(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Ve(e){try{return await A.stat(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function Fi(e){let t=String(e["content-length"]||"").trim();if(!t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)&&n>=0?n:null}function Cr(e){let t=String(e["last-modified"]||"").trim();if(!t)return null;let n=Date.parse(t);return Number.isFinite(n)?n:null}function Di(e,t){let n=Cr(t),s=Fi(t),r=e?.mtime.getTime();return n!==null&&Math.abs((r??0)-n)>=1e3||s!==null&&e?.size!==s?false:n!==null||s!==null}async function Oi(e,t){if(!t)return;let n=Cr(t);if(n===null)return;let s=await Ve(e);if(!s)return;let r=new Date(n);await A.utimes(e,s.atime,r).catch(()=>{});}function ar(e,t){let n=S.extname(e.pathname).toLowerCase(),s=t["content-type"]||"";return Zs.has(n)||Gs.some(r=>s.includes(r))&&!s.startsWith("image/")&&!s.includes("font")}function ji(e){try{let t=S.extname(new URL(e).pathname).toLowerCase();return t===".js"||t===".mjs"}catch{return false}}function ze(e,t){(e.doneAssets.size%25===0||e.doneAssets.size===1||e.doneAssets.size===e.stats.assetsQueued)&&t.progress(`Asset download progress: processed ${e.doneAssets.size}, discovered ${e.stats.assetsQueued}.`,{doneAssets:e.doneAssets.size,assetsQueued:e.stats.assetsQueued,phase:"download-assets"});}function Ui(e){return He(e.toString("base64"),40)}function Li(e,t,n){let s=e.assetVariantDigestsByOriginalPath.get(t);if(!s||s.size===0)return false;for(let r of s)if(r!==n)return true;return false}function qi(e,t,n){let s=e.assetVariantDigestsByOriginalPath.get(t);s||(s=new Set,e.assetVariantDigestsByOriginalPath.set(t,s)),s.add(n);}async function Zt(e,t,n,s,r,i,a){let c=yt(e,n),o=Ui(s),u=c.originalFilePath,l=c.originalPublicUrlWithSearch;if(c.preferQueryHashed&&c.hashedFilePath&&c.hashedPublicUrl&&Li(r,c.originalFilePath,o)){let f=Pi(e,t,n);f?(u=f.outputPath,l=f.publicUrl):(u=c.hashedFilePath,l=c.hashedPublicUrl);}Mi(e,t,n,l,c.originalPublicUrl);let d=we(u)?Buffer.from(Wt(s.toString("utf8"),e,t,u),"utf8"):s,p=await vr(u),g=false;return (p===null||!p.equals(d))&&(await We(u,d),g=true),i?.debug(`${g?"Saved":"Skipped unchanged"} asset output ${n}`,{phase:"download-assets",url:n,outputPath:u,bytes:d.length,wroteFile:g}),qi(r,c.originalFilePath,o),await Oi(u,a),r.stats.assetsSaved++,i&&(r.stats.assetsSaved%50===0||r.stats.assetsSaved===1)&&i.progress(`Asset progress: saved ${r.stats.assetsSaved}, discovered ${r.stats.assetsQueued}, pending ${r.assetQueue.length}.`,{assetsSaved:r.stats.assetsSaved,assetsQueued:r.stats.assetsQueued,assetQueue:r.assetQueue.length,phase:"download-assets"}),{outputPath:u,publicUrl:l,wroteFile:g}}function Ke(e,t,n,s,r){let i=()=>{let d=String(r??"").trim();if(!d)return {discoveredFrom:"",discoveredFromType:"unknown"};if(d==="seed-path"||d==="cli"||d==="generated-404-request-path")return {discoveredFrom:d,discoveredFromType:d};if(/^https?:\/\//i.test(d))try{let p=new URL(d);return Fe(p)?{discoveredFrom:d,discoveredFromType:"sitemap"}:q(e,p)?{discoveredFrom:d,discoveredFromType:"asset"}:Pe(p)&&!Me(p)?{discoveredFrom:d,discoveredFromType:"page"}:{discoveredFrom:d,discoveredFromType:"url"}}catch{return {discoveredFrom:d,discoveredFromType:"url"}}return {discoveredFrom:d,discoveredFromType:"url"}},a=r&&/^https?:\/\//i.test(r)?r:e.sourceOrigin,c=H(e,n,a,s,"page");if(!c)return;if(!Pe(c)||br(c)){if(q(e,c)){s.info(`Seeded/non-page URL queued as asset: ${c.toString()}`,{url:c.toString(),source:r}),J(e,t,c.toString(),s,r);return}s.reject("page",c.toString(),Me(c)?"asset/internal path cannot be page":"not page-like",r);return}let o=c.toString(),{discoveredFrom:u,discoveredFromType:l}=i();u&&!t.pageDiscoverySources.has(o)&&t.pageDiscoverySources.set(o,u),!t.donePages.has(o)&&!t.queuedPages.has(o)&&(t.queuedPages.add(o),t.pageQueue.push(o),t.stats.pagesQueued++,s.debug(`Queued discovered page ${o}`,{phase:"discovery",url:o,discoveredFrom:u,discoveredFromType:l,outputPath:le(e,o)}),(t.stats.pagesQueued%25===0||t.stats.pagesQueued===1)&&s.progress(`Discovery progress: pages ${t.stats.pagesQueued}, assets ${t.stats.assetsQueued}, sitemaps ${t.stats.sitemapsQueued}.`,{pagesQueued:t.stats.pagesQueued,assetsQueued:t.stats.assetsQueued,sitemapsQueued:t.stats.sitemapsQueued,pageQueue:t.pageQueue.length,phase:"discovery"}));}function J(e,t,n,s,r){let i=r&&/^https?:\/\//i.test(r)?r:e.sourceOrigin,a=H(e,n,i,s,"asset");if(!a)return;if(!q(e,a)){s.reject("asset",a.toString(),"not a safe asset path/prefix",r);return}let c=a.toString();!t.doneAssets.has(c)&&!t.queuedAssets.has(c)&&(t.queuedAssets.add(c),t.assetQueue.push(c),t.stats.assetsQueued++,(t.stats.assetsQueued%100===0||t.stats.assetsQueued===1)&&s.progress(`Discovery progress: pages ${t.stats.pagesQueued}, assets ${t.stats.assetsQueued}, sitemaps ${t.stats.sitemapsQueued}.`,{pagesQueued:t.stats.pagesQueued,assetsQueued:t.stats.assetsQueued,sitemapsQueued:t.stats.sitemapsQueued,assetQueue:t.assetQueue.length,phase:"discovery"}));}function wt(e,t,n,s,r){let i=r&&/^https?:\/\//i.test(r)?r:e.sourceOrigin,a=H(e,n,i,s,"sitemap");if(!a)return;if(!Fe(a)){s.reject("sitemap",a.toString(),"not sitemap-like",r);return}let c=a.toString();!t.doneSitemaps.has(c)&&!t.queuedSitemaps.has(c)&&(t.queuedSitemaps.add(c),t.sitemapQueue.push(c),t.stats.sitemapsQueued++,(t.stats.sitemapsQueued%10===0||t.stats.sitemapsQueued===1)&&s.progress(`Discovery progress: pages ${t.stats.pagesQueued}, assets ${t.stats.assetsQueued}, sitemaps ${t.stats.sitemapsQueued}.`,{pagesQueued:t.stats.pagesQueued,assetsQueued:t.stats.assetsQueued,sitemapsQueued:t.stats.sitemapsQueued,sitemapQueue:t.sitemapQueue.length,phase:"discovery"}));}function _i(e){let t=ce(e),n=[...t.matchAll(/<url>\s*([\s\S]*?)\s*<\/url>/gi)].map(s=>s[1]);return n.length>0?n.map(s=>{let r=s.match(/<loc>\s*([^<]+?)\s*<\/loc>/i);if(!r?.[1])return null;let i=s.match(/<lastmod>\s*([^<]+?)\s*<\/lastmod>/i);return {loc:r[1].trim(),lastmod:Qe(i?.[1]??null)}}).filter(s=>!!s):[...t.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/gi)].map(s=>({loc:s[1].trim(),lastmod:null})).filter(s=>s.loc)}function Ni(e){return e.split(",").map(t=>t.trim().split(/\s+/)[0]).filter(Boolean)}function Bi(e){let t=[],n=/url\(\s*(?:"([^"]+)"|'([^']+)'|([^)]*?))\s*\)/gi;for(let s of e.matchAll(n)){let r=e.slice(Math.max(0,s.index-8),s.index);if(/\bnew\s+$/i.test(r))continue;let i=(s[1]||s[2]||s[3]||"").trim();i&&t.push(i);}return t}function Hi(e){return e.replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi,"")}function Wi(e,t){if(t==="dom-style")return true;let n=(()=>{try{return S.extname(new URL(e).pathname).toLowerCase()}catch{return ""}})();return !(n===".js"||n===".mjs"||n===".map"||t.includes("javascript"))}function Jt(e){return e.trim().replace(/\\/g,"/").replace(/^https?:\/\/[^/]+/i,"").replace(/^\/+/,"")}async function Rr(e,t,n,s){let r=[];await A.mkdir(t,{recursive:true});let i=await A.readdir(e,{withFileTypes:true});for(let a of i){let c=S.join(e,a.name),o=S.join(t,a.name);if(a.isDirectory()){r.push(...await Rr(c,o,n,s));continue}await Ir(c,o,n,s)&&r.push(o);}return r}async function zi(e,t){try{let[n,s]=await Promise.all([A.stat(e),A.stat(t)]);if(n.size!==s.size)return !1;let[r,i]=await Promise.all([A.readFile(e),A.readFile(t)]);return r.equals(i)}catch{return false}}async function Ir(e,t,n,s){let r=S.resolve(t);return n.has(r)?(s.debug("Skipped post-crawl copy over crawled page output",{phase:"copy-extra-paths",sourcePath:e,targetPath:t}),false):await zi(e,t)?(s.debug("Skipped unchanged post-crawl copy target",{phase:"copy-extra-paths",sourcePath:e,targetPath:t}),false):(await A.mkdir(S.dirname(t),{recursive:true}),await A.copyFile(e,t),true)}async function Qi(e,t,n){let s=Object.entries(e.postCrawlCopyMap||{}).map(([c,o])=>({sourcePath:c.trim(),prefix:String(o||"").trim()}));if(s.length===0)return [];let r=0,i=[],a=new Set([...t.donePages].map(c=>S.resolve(le(e,c))));n.mark("copy-extra-paths");for(let c of s){let o=c.sourcePath,u=c.prefix;if(!o||!u){n.warn("Skipped post-crawl copy mapping with empty key/value",{sourcePath:o,prefixPath:u});continue}let l=ni(o);if(!l.resolvedPath){n.warn("Skipped post-crawl copy source because alias root is not configured",{sourcePath:o,alias:l.alias||"",requiredEnv:l.requiredEnv||"",prefixPath:u});continue}let d=l.resolvedPath,p=Jt(u);if(!p){n.warn("Skipped post-crawl copy mapping with invalid export prefix",{sourcePath:o,prefixPath:u});continue}let g;try{g=await A.stat(d);}catch{n.warn("Skipped post-crawl copy source because it does not exist",{sourcePath:o,sourceAbs:d,prefixPath:u});continue}let f=S.resolve(e.outputDir,p);if(g.isDirectory()){let v=await Rr(d,f,a,n);i.push(...v),r+=v.length,v.length>0&&n.progress(`Copied static directory to export: ${d} -> /${p}`,{phase:"copy-extra-paths",sourcePath:d,targetPath:`/${p}`,copiedItems:r,changedFiles:v.length});continue}let w=S.basename(d),m=u.endsWith("/")?S.join(f,w):f;await Ir(d,m,a,n)&&(i.push(m),r++,n.progress(`Copied static file to export: ${d} -> /${Jt(u.endsWith("/")?`${u}${w}`:u)}`,{phase:"copy-extra-paths",sourcePath:d,targetPath:`/${Jt(u.endsWith("/")?`${u}${w}`:u)}`,copiedItems:r}));}return n.endMark("copy-extra-paths",{mappedSources:s.length,copiedItems:r}),i}function Ge(e,t,n,s,r){let i=new Set,a=ce(n).replace(/\\\//g,"/"),c=r==="page-html"?Hi(a):a,o=Wi(t,r);if(o){for(let l of Bi(c)){let d=H(e,l,t,s,`${r}:css-url`);d&&q(e,d)&&i.add(d.toString());}for(let l of c.matchAll(/@import\s+(?:url\()?\s*['"]?([^'"\s;]+)['"]?\s*\)?/gi)){let d=H(e,l[1],t,s,`${r}:css-import`);d&&q(e,d)&&i.add(d.toString());}}if(o||r==="page-html")for(let l of c.matchAll(/<\?xml-stylesheet[^>]+href=["']([^"']+)["'][^>]*\?>/gi)){let d=H(e,l[1],t,s,`${r}:xml-stylesheet`);d&&q(e,d)&&i.add(d.toString());}let u=new RegExp(`(?:https?:)?//[^\\s'"<>\\);]+\\.${zt}(?:\\?[^\\s'"<>\\);]*)?|(?<!\\.)/[^\\s'"<>\\);]+\\.${zt}(?:\\?[^\\s'"<>\\);]*)?`,"gi");if(r==="page-html")for(let l of a.matchAll(u)){let d=l[0].startsWith("//")?`${new URL(e.sourceOrigin).protocol}${l[0]}`:l[0];if(Gt(d)){s.ignore(`${r}:serialized-url`,d,"looks like JavaScript/code fragment",t);continue}let p=H(e,d,t,s,`${r}:serialized-url`);p&&q(e,p)?i.add(p.toString()):p&&s.ignore("asset",p.toString(),"serialized URL did not pass safe asset path filter",t);}if(r!=="page-html"&&ji(t))for(let l of tr(a)){if(Gt(l)||!/\.(?:js|mjs)(?:[?#]|$)/i.test(l))continue;let d=H(e,l,t,s,`${r}:relative-asset`);d&&q(e,d)&&i.add(d.toString());}return [...i]}function Ji(e,t,n,s){let r=new Set,i=ce(n);for(let a of i.matchAll(/href=["']([^"'#\s][^"']*?)["']/gi)){let c=a[1],o=H(e,c,t,s,"page-link");o&&(Sr(e,o)||Pe(o)&&!Me(o)&&!q(e,o)&&r.add(o.toString()));}return [...r]}async function cr(e,t,n,s,r,i,a=false){let c=new Map,o=(u,l)=>{let d=[l],p=new Set;for(;d.length>0;){let g=d.pop();if(g===u)return true;p.has(g)||(p.add(g),d.push(...c.get(g)??[]));}return false};for(;n.sitemapQueue.length>0;){let u=n.sitemapQueue.shift();n.queuedSitemaps.delete(u);let l=Se(u,s,"sitemap","sitemap-queue");if(!l)continue;let d=l.toString();if(!n.doneSitemaps.has(d)){n.doneSitemaps.add(d),s.sitemap(`Fetching sitemap ${d}`,{url:d});try{let p=await t.get(d,{timeout:6e4});if(!p.ok()){if(s.skip("sitemap",d,p.status()),a)throw new Error(`Required content-sync sitemap returned HTTP ${p.status()}: ${d}`);continue}let g=await p.body(),f=p.url()||d,w=Se(f,s,"sitemap-response",d);if(!w)continue;let m=w.toString(),h=await Zt(e,n.assetMap,m,g,n,s);Y(r,e,h.outputPath),Ce(r,h.outputPath);let v=g.toString("utf8");/<sitemapindex(?:\s|>)/i.test(v)?n.sitemapIndexUrls.add(m):n.sitemapLeafUrls.add(m);let T=Ge(e,m,v,s,"sitemap");for(let F of T)J(e,n,F,s,m);let E=[];for(let F of _i(v)){let I=H(e,F.loc,m,s,"sitemap-loc");if(!I){if(a)throw new Error(`Content-sync sitemap contains an inadmissible location: ${F.loc}`);continue}if(Fe(I)){if(o(m,I.toString()))throw new Error(`Sitemap index cycle detected: ${m} -> ${I.toString()}`);c.has(m)||c.set(m,new Set),c.get(m).add(I.toString()),E.push(I.toString()),wt(e,n,I.toString(),s,m);}else if(a){if(Pe(I)&&!q(e,I)){let O=i.requiredUrls.has(I.toString()),b=i.manifest.pages[I.toString()],P=!!b&&!!await Ve(b.outputPath);if(!O&&!P)throw new Error(`Content-sync sitemap coverage is incomplete for ${I.toString()}.`)}s.ignore("sitemap-loc",I.toString(),"content-sync sitemap-only traversal does not enqueue urlset locations",m);}else q(e,I)?J(e,n,I.toString(),s,m):Pe(I)?(F.lastmod&&(n.sitemapLastmodByPage[I.toString()]=F.lastmod),Ke(e,n,I.toString(),s,m)):s.reject("sitemap-loc",I.toString(),"not page/sitemap/asset-like",m);}i.trackManifest&&(i.manifest.assets[m]={url:m,outputPath:h.outputPath,isText:!0,contentType:p.headers()["content-type"]??"application/xml",discoveredAssets:[...new Set([...T,...E])],lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!1},await ye(e,i));}catch(p){if(s.error(`Failed sitemap ${d}`,{url:d,error:String(p)}),a)throw p}}}}async function Vi(e,t,n,s,r,i,a){let c=H(e,s,e.sourceOrigin,r,"asset-fetch");if(!c||!q(e,c))return;let o=c.toString();if(n.doneAssets.has(o))return;let u=i.enabled||i.strictTargeted?i.previousManifest.assets[o]:void 0,l=i.strictTargeted?i.manifest.assets[o]:void 0;if(l?.lastSeenRunId===i.runId&&await Ve(l.outputPath)){n.doneAssets.add(o);for(let p of l.discoveredAssets||[])J(e,n,p,r,o);Y(a,e,l.outputPath),l.isText&&Ce(a,l.outputPath),r.info(`Resumed completed content-sync asset ${o}`,{url:o,source:"content-sync-checkpoint"}),ze(n,r);return}let d=(p,g={})=>{if(!u||i.strictTargeted)return false;i.manifest.assets[o]={...u,discoveredAssets:[...u.discoveredAssets||[]],lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId},delete i.manifest.pages[o],n.doneAssets.add(o);for(let f of u.discoveredAssets||[])J(e,n,f,r,o);return r.warn(`Keeping previous incremental asset ${o} after fetch issue.`,{url:o,reason:p,preservedFromPreviousManifest:true,...g,phase:"download-assets"}),ze(n,r),true};r.asset(`Fetching asset ${o}`,{url:o});try{let p=Ee(e,n.assetMap,o),g=p?await Ve(p):null;if(p&&g)try{let O=await _(`fetch asset headers ${o}`,6e4,()=>t.head(o,{timeout:6e4})),b=O.headers();if(O.ok()&&Di(g,b)){let P=await vr(p);if(P!==null){let C=O.url()||o,y=Se(C,r,"asset-response",o);if(!y)return;let x=y.toString(),j=await Zt(e,n.assetMap,x,P,n,r,b);j.wroteFile&&(Y(a,e,j.outputPath),we(j.outputPath)&&Ce(a,j.outputPath)),n.doneAssets.add(o),r.info(`Reused existing asset ${o} based on response headers.`,{url:o,filePath:p,lastModified:b["last-modified"]||"",contentLength:b["content-length"]||"",phase:"download-assets"}),ze(n,r);let L=ar(c,b),V=u?.discoveredAssets?[...u.discoveredAssets]:[];if(L||u?.isText){let B=P.toString("utf8"),K=Ge(e,x,B,r,"asset:cached");(K.length>0||!u)&&(V=K);for(let $ of V)J(e,n,$,r,x);}if(i.trackManifest){let B=L||!!u?.isText;i.manifest.assets[o]={url:o,outputPath:j.outputPath,isText:B,contentType:Vt(b)||u?.contentType||null,discoveredAssets:V,lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!B},delete i.manifest.pages[o],(i.enabled||i.strictTargeted)&&B&&await ye(e,i);}return}}}catch{}let f=await _(`fetch asset ${o}`,6e4,()=>t.get(o,{timeout:6e4}));if(!f.ok()){if(d(`http-${f.status()}`,{status:f.status()}))return;if(i.strictTargeted)throw new Error(`Required content-sync asset returned HTTP ${f.status()}: ${o}`);r.skip("asset",o,f.status());return}let w=await _(`read asset response ${o}`,6e4,()=>f.body()),m=f.url()||o,h=Se(m,r,"asset-response",o);if(!h)return;let v=h.toString(),T=f.headers(),E=await Zt(e,n.assetMap,v,w,n,r,T);E.wroteFile&&(Y(a,e,E.outputPath),we(E.outputPath)&&Ce(a,E.outputPath)),n.doneAssets.add(o),ze(n,r);let F=ar(c,T),I=[];if(F){let O=w.toString("utf8");I=Ge(e,v,O,r,`asset:${S.extname(c.pathname).toLowerCase()||T["content-type"]||"unknown"}`);for(let b of I)J(e,n,b,r,v);}i.trackManifest&&(i.manifest.assets[o]={url:o,outputPath:E.outputPath,isText:F,contentType:Vt(T),discoveredAssets:I,lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!F},delete i.manifest.pages[o],(i.enabled||i.strictTargeted)&&F&&await ye(e,i));}catch(p){if(d("fetch-error",{error:String(p)}))return;if(r.error(`Failed asset ${o}`,{url:o,error:String(p)}),i.strictTargeted)throw p}finally{n.doneAssets.has(o)||(n.doneAssets.add(o),ze(n,r));}}async function Ki(e,t,n,s,r,i){let a=Math.max(1,Number(e.assetDownloadConcurrency||e.concurrency||1)),c=Array.from({length:a},async()=>{for(;n.assetQueue.length>0;){let o=n.assetQueue.shift();o&&(n.queuedAssets.delete(o),await Vi(e,t,n,o,s,r,i));}});await Promise.all(c);}function Gi(e){let t=Math.ceil(e/1e3);return `${t} second${t===1?"":"s"}`}function ue(e){return Math.max(6e4,e.navigationTimeoutMs*2,e.readiness.timeoutMs+e.readiness.fallbackWaitMs+15e3)}function mt(e){return Math.max(15e3,Math.min(6e4,ue(e)))}function Zi(e){return Math.max(15e3,e.readiness.timeoutMs+e.readiness.fallbackWaitMs+1e4)}function rn(e){return e.stats.pagesCompleted}function xr(e){let n=e.options?.browserProcess;return {pid:typeof n?.process?.pid=="number"?n.process.pid:null,kill:typeof n?.kill=="function"?n.kill.bind(n):null}}async function Yi(e,t,n){let s=xr(e);try{if(s.kill){await s.kill(),t.warn(`Force-killed crawl worker browser after ${n}`,{browserPid:s.pid,reason:n});return}if(s.pid!==null){process.kill(s.pid,"SIGKILL"),t.warn(`Sent SIGKILL to crawl worker browser after ${n}`,{browserPid:s.pid,reason:n});return}t.warn(`Could not resolve crawl worker browser PID after ${n}`,{reason:n});}catch(r){t.error(`Failed to force-kill crawl worker browser after ${n}`,{browserPid:s.pid,reason:n,error:String(r)});}}async function _(e,t,n){let s;try{return await Promise.race([n(),new Promise((r,i)=>{s=globalThis.setTimeout(()=>{i(new Error(`${e} timed out after ${Gi(t)}.`));},t);})])}finally{s!==void 0&&globalThis.clearTimeout(s);}}async function Xi(e,t){let n=Zi(e);await t.evaluate(async s=>{await new Promise(r=>{let i=0,a=700,c=Date.now(),o=()=>{window.clearInterval(u),window.scrollTo(0,0),r();},u=window.setInterval(()=>{if(Date.now()-c>=s.maxDurationMs){o();return}window.scrollBy(0,a),i+=a;let l=document.body?.scrollHeight||0,d=document.documentElement?.scrollHeight||0,p=Math.max(l,d);i>=p+window.innerHeight&&o();},120);});},{maxDurationMs:n});}async function eo(e,t){await t.waitForLoadState("domcontentloaded",{timeout:e.readiness.timeoutMs}).catch(()=>{}),e.readiness.waitForSelector&&await t.waitForSelector(e.readiness.waitForSelector,{timeout:e.readiness.timeoutMs}).catch(()=>{}),e.readiness.waitForFunction&&await t.waitForFunction(e.readiness.waitForFunction,void 0,{timeout:e.readiness.timeoutMs}).catch(()=>{}),await Xi(e,t),await t.waitForTimeout(e.readiness.fallbackWaitMs);}async function to(e,t){await t.waitForLoadState("domcontentloaded",{timeout:e.readiness.timeoutMs}).catch(()=>{}),await t.waitForLoadState("load",{timeout:e.readiness.timeoutMs}).catch(()=>{}),e.readiness.waitForSelector&&await t.waitForSelector(e.readiness.waitForSelector,{timeout:e.readiness.timeoutMs}).catch(()=>{}),await t.waitForTimeout(e.readiness.fallbackWaitMs);}function no(e,t){return e.noJavaScriptRenderPathPrefixes.some(n=>en(t,n))}async function ro(e,t,n,s,r=true){let i=new Set;if(r){let c=await t.evaluate(()=>{let o=new Set,u=["href","src","poster","data-src","data-lazy-src","data-original","data-bg","data-background","data-href"],l=new Set,d=["srcset","data-srcset","data-lazy-srcset"];return document.querySelectorAll("*").forEach(p=>{for(let f of u){let w=p.getAttribute(f);w&&o.add(w);}for(let f of d){let w=p.getAttribute(f);w&&w.split(",").forEach(m=>{let h=m.trim().split(/\s+/)[0];h&&o.add(h);});}let g=p.getAttribute("style");g&&l.add(g);}),{attrs:[...o],styles:[...l]}});for(let o of c.attrs)for(let u of Ni(o)){let l=H(e,u,n,s,"dom-attr");l&&q(e,l)&&i.add(l.toString());}for(let o of c.styles)for(let u of Ge(e,n,o,s,"dom-style"))i.add(u);}let a=await t.content();for(let c of Ge(e,n,a,s,"page-html"))i.add(c);return [...i]}async function ur(e,t,n,s,r){let i=le(e,t);await We(i,n,"utf8");let a=await A.stat(i);r?.debug(`Saved page output ${t}`,{phase:"save-pages",url:t,outputPath:i,bytes:a.size}),s.stats.pagesSaved++;let c=Math.min(s.stats.pagesQueued,rn(s)+1);r&&(s.stats.pagesSaved%10===0||s.stats.pagesSaved===1)&&r.progress(`Page progress: processed ${c}, rendered ${s.stats.pagesRendered}, saved ${s.stats.pagesSaved}, discovered ${s.stats.pagesQueued}.`,{donePages:c,claimedPages:s.donePages.size,pagesRendered:s.stats.pagesRendered,pagesSaved:s.stats.pagesSaved,pagesQueued:s.stats.pagesQueued,pageQueue:s.pageQueue.length,phase:"save-pages"});}function so(e){let t=rn(e);return t%5===0||t===1||t===e.stats.pagesQueued}function io(e,t){let n=rn(e);t.progress(`Render progress: processed ${n}, rendered ${e.stats.pagesRendered}, saved ${e.stats.pagesSaved}, discovered ${e.stats.pagesQueued}.`,{donePages:n,claimedPages:e.donePages.size,pagesRendered:e.stats.pagesRendered,pagesSaved:e.stats.pagesSaved,pagesQueued:e.stats.pagesQueued,phase:"render-pages"});}async function oo(e){await e.addInitScript(()=>{Object.defineProperty(window,"__WPSUITE_STATIC_EXPORT__",{value:true,writable:false,configurable:true});let t=n=>{if(n==null||String(n)==="")return true;try{let s=new URL(String(n),window.location.href),r=new URL(window.location.href);return s.hash="",r.hash="",s.href===r.href}catch{return false}};try{let n=window.location.assign.bind(window.location),s=window.location.replace.bind(window.location),r=window.location.reload.bind(window.location);Object.defineProperty(window.location,"assign",{configurable:!0,value:i=>{if(t(i)){console.warn("[smartcloud-static-publisher] blocked same-page location.assign",i??"");return}return n(i)}}),Object.defineProperty(window.location,"replace",{configurable:!0,value:i=>{if(t(i)){console.warn("[smartcloud-static-publisher] blocked same-page location.replace",i??"");return}return s(i)}}),Object.defineProperty(window.location,"reload",{configurable:!0,value:()=>{console.warn("[smartcloud-static-publisher] blocked location.reload");}});}catch{}});}async function ao(e,t,n){let s=await e.newContext({viewport:t.viewport,userAgent:"WPSuiteStaticPublisher/0.8 Playwright SitemapOnly",ignoreHTTPSErrors:t.ignoreHttpsErrors,...n?{javaScriptEnabled:false}:{}});return n||await oo(s),s}async function co(e,t,n,s,r,i,a){let c=await chromium.launch({headless:true}),o=xr(c);o.pid!==null&&n.debug(`Launched crawl worker browser PID ${o.pid}`,{browserPid:o.pid});try{for(;t.pageQueue.length>0&&!(e.maxPages>0&&t.donePages.size>=e.maxPages);){let u=t.pageQueue.shift();if(!u)break;t.queuedPages.delete(u);let l=null,d=null;try{let p=Se(u,n,"page","page-queue");if(!p)continue;let g=p.toString();if(u=g,t.queuedPages.delete(u),t.donePages.has(u))continue;t.donePages.add(u),i.enabled&&i.seenPages.add(u);let f=nn(e,u),w=no(e,p.pathname);if(!Pe(p)||q(e,p)||Me(p)){if(q(e,p)){n.info(`Worker redirected non-page URL to asset queue: ${u}`,{url:u,source:"worker-guard"}),J(e,t,u,n,"worker-guard");continue}n.reject("page",u,"guard rejected non-page URL before rendering","worker");continue}let m=i.strictTargeted?i.manifest.pages[u]:void 0;if(m?.lastSeenRunId===i.runId&&await Ve(m.outputPath)){i.seenPages.add(u);for(let y of m.discoveredAssets||[])J(e,t,y,n,u);Y(a,e,m.outputPath),Ce(a,m.outputPath),n.info(`Resumed completed content-sync page ${u}`,{url:u,source:"content-sync-checkpoint"});continue}let h=await pi(e,r,t,i,u,n);if(i.enabled&&s!=="single-url"&&s!=="content-sync"){let y=i.manifest.pages[u];if(h.action==="reuse"&&y){for(let x of y.discoveredAssets)J(e,t,x,n,u);for(let x of y.discoveredPages)Ke(e,t,x,n,u);y.lastSeenRunId=i.runId,y.sitemapLastmod=Qe(t.sitemapLastmodByPage[u])??y.sitemapLastmod,h.changeToken?.supported&&(y.changeToken=h.changeToken.token,y.tokenSource=h.changeToken.tokenSource??y.tokenSource),n.info(`Incremental reuse skipped unchanged page ${u}`,{url:u,mode:"incremental",reason:h.changeToken?.supported===!0?"change-token-match":"sitemap-lastmod-match"});continue}}l=await _(`create page context ${u}`,ue(e),()=>ao(c,e,w)),d=await _(`create page ${u}`,ue(e),()=>l.newPage());let v=!1,T=new Set;await d.route("**/*",async y=>{let x=y.request();if(x.isNavigationRequest()&&x.frame()===d.mainFrame())try{let j=new URL(x.url()),L=new URL(g);if(j.hash="",L.hash="",j.href===L.href){if(v){n.warn(`Blocked same-page navigation/reload for ${u}`,{url:u,requestUrl:x.url()}),await y.abort("aborted");return}v=!0;}}catch{}await y.continue();}),d.on("response",y=>{try{let x=H(e,y.url(),e.sourceOrigin,n,"network-response");x&&q(e,x)&&(T.add(x.toString()),J(e,t,x.toString(),n,u));}catch{}}),n.page(`Rendering ${u}`,{url:u});let E=null,F=null;try{if(E=await d.goto(u,{waitUntil:"domcontentloaded",timeout:e.navigationTimeoutMs}),E&&E.ok())try{F=await _(`read response body ${u}`,ue(e),()=>E.text());}catch{F=null;}}catch(y){n.warn(`Navigation issue for ${u}; saving current DOM if available`,{url:u,error:String(y)});}if(s==="content-sync"&&E){let y=Se(E.url(),n,"content-sync-final-response",u)?.toString();if(y&&y!==g){if(i.deleteOnMissingUrls.has(u)){await Yt(e,i,a,u,i.deleteOnMissingUrls),n.info(`Removed stale content-sync archive route redirected to ${y}`,{url:u,finalResponseUrl:y,source:"content-sync-tombstone"});continue}throw new Error(`Required content-sync route redirected outside its planned URL: ${u} -> ${y}`)}}if(f){let y=E?.status()??null;if(y!==404){n.error(`Generated 404 request path returned unexpected status for ${u}`,{url:u,expectedStatus:404,status:y,requestPath:e.generated404RequestPath});continue}n.info(`Capturing rendered 404 page for ${u}`,{url:u,status:y,outputPath:le(e,u)});}else if(E&&!E.ok()){if(s==="content-sync"&&(E.status()===404||E.status()===410)&&i.deleteOnMissingUrls.has(u)){await Yt(e,i,a,u,i.deleteOnMissingUrls),n.info(`Removed stale content-sync archive page ${u}`,{url:u,status:E.status(),source:"content-sync-tombstone"}),await d.close();continue}if(s==="content-sync")throw new Error(`Required content-sync route returned HTTP ${E.status()}: ${u}`);n.skip("page",u,E.status(),t.pageDiscoverySources.get(u)),await d.close();continue}w?(n.info(`Rendering without JS execution for ${u}`,{url:u,mode:"no-js"}),await _(`wait for rendered page ${u}`,ue(e),()=>to(e,d))):await _(`wait for rendered page ${u}`,ue(e),()=>eo(e,d)),t.stats.pagesRendered++;let I=await _(`extract rendered assets ${u}`,ue(e),()=>ro(e,d,g,n,!w));for(let y of I)J(e,t,y,n,u);let O=[...new Set([...I,...T])],b=F??await _(`capture rendered html ${u}`,ue(e),()=>d.content()),P=s!=="single-url"&&s!=="content-sync"&&!f?Ji(e,u,b,n):[];if(s!=="single-url"&&s!=="content-sync"&&!f)for(let y of P)Ke(e,t,y,n,u);await ur(e,u,b,t,n);let C=le(e,u);if(Y(a,e,C),Ce(a,C),i.trackManifest){let y=E?.headers();i.manifest.pages[u]={url:u,outputPath:C,contentType:Vt(y),changeToken:h.changeToken?.supported?h.changeToken.token:null,tokenSource:h.changeToken?.supported?h.changeToken.tokenSource??null:null,sitemapLastmod:Qe(t.sitemapLastmodByPage[u])??null,discoveredPages:P,discoveredAssets:O,lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!1},(i.enabled||i.strictTargeted)&&await ye(e,i);}}catch(p){if(i.strictTargeted)throw n.error(`Failed required content-sync page ${u}`,{url:u,error:String(p)}),p;try{let g=d?await _(`capture partial html ${u}`,ue(e),()=>d.content()):"";if(g&&g.trim()){await ur(e,u,g,t,n);let f=le(e,u);if(Y(a,e,f),Ce(a,f),i.trackManifest){let w=i.manifest.pages[u]??i.previousManifest.pages[u];i.manifest.pages[u]={url:u,outputPath:f,contentType:w?.contentType??null,changeToken:null,tokenSource:null,sitemapLastmod:Qe(t.sitemapLastmodByPage[u])??w?.sitemapLastmod??null,discoveredPages:w?.discoveredPages?[...w.discoveredPages]:[],discoveredAssets:w?.discoveredAssets?[...w.discoveredAssets]:[],lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!1},(i.enabled||i.strictTargeted)&&await ye(e,i);}n.warn(`Saved partial DOM for ${u}`,{url:u,error:String(p)});}}catch(g){n.error(`Could not save partial DOM for ${u}`,{url:u,error:String(g)});}n.error(`Failed page ${u}`,{url:u,error:String(p)});}finally{t.stats.pagesCompleted++,so(t)&&io(t,n),d&&await _(`close page ${u}`,mt(e),()=>d.close()).catch(p=>{n.warn(`Timed out while closing page ${u}`,{url:u,browserPid:o.pid,error:String(p)});}),l&&await _(`close page context ${u}`,mt(e),()=>l.close()).catch(p=>{n.warn(`Timed out while closing page context for ${u}`,{url:u,browserPid:o.pid,error:String(p)});});}}}finally{await _("close worker browser",mt(e),()=>c.close()).catch(u=>(n.warn("Timed out while closing crawl worker browser",{browserPid:o.pid,error:String(u)}),Yi(c,n,"browser.close timeout")));}}async function uo(e){try{let t=await A.readFile(e),s=(e.endsWith(".gz")?gunzipSync(t):t).toString("utf8").trim();if(!s)return [];try{let r=JSON.parse(s);if(Array.isArray(r))return r;if(r&&typeof r=="object")return [r]}catch{return s.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).map(r=>{try{let i=JSON.parse(r);return i&&typeof i=="object"?i:null}catch{return null}}).filter(r=>r!==null)}return []}catch{return []}}function lr(e){let t=String(e||"").toLowerCase();return t.includes("timeout")||t.includes("timed out")||t.includes("navigation timeout")}function lo(e){let t=String(e?.job?.command||"").trim(),n=String(e?.job?.crawlMode||"full").trim();return t!=="publish"&&t!=="crawl"?false:n!=="incremental"}function po(e){let t=[e?.archivedAt,e?.job?.endedAt,e?.job?.startedAt];for(let n of t){let s=Date.parse(String(n||""));if(Number.isFinite(s))return s}return 0}async function Ar(e){try{let t=await A.readFile(e,"utf8"),n=JSON.parse(t);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function dr(e){let t=String(e.originalFileName||"").toLowerCase();return t.endsWith("errors.jsonl")?0:t.endsWith("errors.json")?1:2}function go(e,t){let n=Array.isArray(t?.artifacts)?t.artifacts.filter(s=>String(s?.role||"").trim()==="errors"&&String(s?.storedFileName||"").trim()!=="").sort((s,r)=>dr(s)-dr(r)).map(s=>S.join(e,String(s.storedFileName))):[];return [...new Set([...n,S.join(e,"errors.jsonl"),S.join(e,"errors.json"),S.join(e,"errors.jsonl.gz"),S.join(e,"errors.json.gz")])]}async function pr(e){let t=await Ar(S.join(e,"job.json"));for(let n of go(e,t)){let s=await uo(n);if(s.length>0)return s}return []}async function fo(e){let t=S.join(e.logDir,"archive"),n;try{n=await A.readdir(t);}catch{return ""}let s="",r=0;for(let i of n){let a=S.join(t,i);if(!(await A.stat(a).catch(()=>null))?.isDirectory())continue;let o=await Ar(S.join(a,"job.json"));if(!lo(o))continue;let u=po(o);u>=r&&(r=u,s=a);}return s}async function mo(e){let t=await fo(e),n=t!==""?await pr(t):await pr(e.logDir),s=new Set;for(let r of n)if(lr(r.error)||lr(r.message)){let i=r.url;typeof i=="string"&&i&&s.add(i);}return [...s]}async function ho(e){let t=[];for(let n of e)if(n.startsWith("@")){let s=n.slice(1),r=await A.readFile(s,"utf8");t.push(...r.split(/\r?\n/).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")));}else t.push(n);return t}async function wo(e){if(!e)throw new Error("Content-sync crawl requires an immutable impact plan.");let t=JSON.parse(await A.readFile(e,"utf8"));return _e(t),t}function yo(e,t){let n;try{n=new URL(e);}catch{return false}return t.archiveFamilies.some(s=>{let r=new URL(s.url);if(n.origin!==r.origin)return false;if(n.toString()===r.toString())return true;if(n.searchParams.has("paged")&&n.pathname===r.pathname)return /^\d+$/.test(n.searchParams.get("paged")||"");let i=r.pathname.replace(/\/+$/,""),a=n.pathname.slice(i.length).replace(/^\/+/,""),c=String(s.paginationBase||"page").replace(/^\/+|\/+$/g,"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return n.pathname.startsWith(`${i}/`)&&new RegExp(`^${c}/\\d+/?$`).test(a)})}function ft(e,t,n){let s=n==="page"?le(e,t):yt(e,t).originalFilePath;return he(e.outputDir,s)}async function Yt(e,t,n,s,r){let i=t.manifest.pages[s];if(!i)return;let a=he(e.outputDir,i.outputPath);if(!a)throw new Error(`Manifest-owned page path escaped output root: ${s}`);let c=S.resolve(i.outputPath);Object.entries(t.manifest.pages).some(([u,l])=>u!==s&&!r.has(u)&&S.resolve(l.outputPath)===c)||(await A.rm(i.outputPath,{force:true}),n.deletedFiles.add(a)),delete t.manifest.pages[s];}function So(e,t){let n=new Set,s=[...t];for(;s.length>0;){let r=s.shift();if(n.has(r))continue;n.add(r);let i=e.assets[r];for(let a of i?.discoveredAssets??[])try{Fe(new URL(a))&&s.push(a);}catch{}}return n}async function Po(e,t,n,s,r){let i=So(n.previousManifest,r);for(let a of i){if(t.doneSitemaps.has(a))continue;let c=n.previousManifest.assets[a];if(!c)continue;let o=he(e.outputDir,c.outputPath);if(!o)throw new Error(`Manifest-owned sitemap path escaped output root: ${a}`);await A.rm(c.outputPath,{force:true}),s.deletedFiles.add(o),delete n.manifest.assets[a];}await ye(e,n);}async function bo(e){try{let t=await A.readFile(S.join(e.outputDir,"asset-map.json"),"utf8");return JSON.parse(t)}catch{return {}}}async function vo(e){let t=["crawl.log.jsonl","current-crawl-event.json","rejected.jsonl","ignored.jsonl","skipped-http.jsonl","errors.jsonl","timings.jsonl","rejected.json","ignored.json","skipped-http.json","errors.json","timings.json"];await A.mkdir(e,{recursive:true}),await Promise.all(t.map(async n=>{try{await A.unlink(S.join(e,n));}catch(s){if(s.code!=="ENOENT")throw s}}));}function gr(e,t,n,s,r){let i=H(e,n,e.sourceOrigin,s,"manual-url");i&&(Fe(i)?wt(e,t,i.toString(),s,r):q(e,i)?J(e,t,i.toString(),s,r):Pe(i)?Ke(e,t,i.toString(),s,r):s.reject("manual-url",i.toString(),"not page/sitemap/asset-like",r));}async function Tr(e=process.argv.slice(2)){let t=[],n=await ne(void 0,{onRemotePublisherConfigDiagnostic:P=>{t.push(P);}}),s=t.at(-1)??null,r=Xs(e),i=r.mode==="content-sync"?await wo(r.contentSyncPlanPath):null;if(r.resumeRewrite&&r.mode!=="full")throw new Error("--resume-rewrite is only supported for full crawl/publish jobs.");let a=[];r.mode==="retry-timeouts"&&(a=await mo(n)),r.mode==="single-url"&&(a=await ho(r.urls)),i&&(a=[...i.directRenderUrls,...i.archiveFamilyUrls]);let c=r.crawlMode==="incremental"&&r.mode==="full",o=c&&typeof n.subscriptionType=="string"&&n.subscriptionType.trim()!=="";if(i&&n.subscriptionType!=="PROFESSIONAL"&&n.subscriptionType!=="AGENCY")throw new Error("Content-sync requires an active Professional or Agency subscription.");let u=(r.mode==="full"||r.mode==="single-url"||r.mode==="content-sync")&&!r.resumeRewrite,l=r.mode!=="full"||r.resumeRewrite||o,d=l?await bo(n):{},p=o||r.mode==="single-url"||r.mode==="content-sync"?await ii(n):wr(),g=new Set(a),f=new Set;if(i){for(let P of i.archiveFamilies)if(P.foundPosts===0)for(let C of P.pageUrls)f.add(C);for(let P of Object.keys(p.pages))yo(P,i)&&!g.has(P)&&(a.push(P),f.add(P));}let w={enabled:o,trackManifest:u,manifest:Kt(p),previousManifest:Kt(p),runId:i?.jobId??`${Date.now()}`,seenPages:new Set,changeTokenCache:new Map,manifestSaveChain:Promise.resolve(),strictTargeted:!!i,requiredUrls:g,deleteOnMissingUrls:f};await vo(n.logDir);let m=new dt(n.logDir,n.logLevel);if(s){let P={status:s.status,virtualAssetBaseUrl:s.virtualAssetBaseUrl,subscriptionType:s.subscriptionType??null,error:s.error,requests:s.requests,source:"remote-publisher-config"};s.status==="loaded"&&s.subscriptionType?m.info("Loaded remote WP Suite publisher configuration.",P):m.warn("Remote WP Suite publisher configuration is unavailable or has no active subscription type.",P);}if(c&&!o){let P="Incremental crawl requires an active remote publisher subscription; refusing to fall back to a destructive full crawl.";throw m.error(P,{requestedMode:r.crawlMode,subscriptionType:n.subscriptionType??null,source:"incremental-subscription-guard"}),await m.flush(),new Error(P)}let h={pageQueue:[],queuedPages:new Set,donePages:new Set,pageDiscoverySources:new Map,assetQueue:[],queuedAssets:new Set,doneAssets:new Set,sitemapQueue:[],queuedSitemaps:new Set,doneSitemaps:new Set,sitemapIndexUrls:new Set,sitemapLeafUrls:new Set,sitemapLastmodByPage:{},assetMap:{...d},assetVariantDigestsByOriginalPath:new Map,stats:{pagesQueued:0,pagesRendered:0,pagesCompleted:0,assetsQueued:0,sitemapsQueued:0,assetsSaved:0,pagesSaved:0}},v=si();if(await Te(n),await _n(n,{startedAt:new Date().toISOString(),outputDir:S.resolve(n.outputDir)}),l||await A.rm(n.outputDir,{recursive:true,force:true}),await A.mkdir(n.outputDir,{recursive:true}),i){let P=new Set([...i.deleteUrls,...w.deleteOnMissingUrls]);for(let C of i.deleteUrls)await Yt(n,w,v,C,P);}if(r.resumeRewrite)m.info("Resuming final rewrite from existing output.",{phase:"rewrite-text",mode:r.mode,crawlMode:r.crawlMode});else {let P=await request.newContext({ignoreHTTPSErrors:n.ignoreHttpsErrors});try{if(m.mark("discovery"),r.mode==="full"?(n.sitemapPaths.forEach(y=>wt(n,h,y,m)),await cr(n,P,h,m,v,w),n.seedPaths.forEach(y=>gr(n,h,y,m,"seed-path")),n.generated404RequestPath&&Ke(n,h,n.generated404RequestPath,m,"generated-404-request-path")):(a.forEach(y=>gr(n,h,y,m,"cli")),i?.sitemapUrls.forEach(y=>wt(n,h,y,m,"content-sync-impact")),await cr(n,P,h,m,v,w,r.mode==="content-sync"),i&&await Po(n,h,w,v,i.sitemapUrls)),m.endMark("discovery",{pages:h.pageQueue.length,assets:h.assetQueue.length,sitemaps:h.sitemapQueue.length}),m.summary(`Queued ${h.pageQueue.length} pages, ${h.assetQueue.length} assets, ${h.sitemapQueue.length} sitemaps.`,{mode:r.mode,crawlMode:r.crawlMode,queuedPages:h.pageQueue.length,queuedAssets:h.assetQueue.length,queuedSitemaps:h.sitemapQueue.length}),r.mode==="retry-timeouts"&&h.pageQueue.length===0&&h.assetQueue.length===0&&h.sitemapQueue.length===0){m.summary("No timed-out URLs were queued. Skipping retry crawl.",{mode:r.mode,crawlMode:r.crawlMode,queuedPages:0,queuedAssets:0,queuedSitemaps:0}),await m.flush();return}m.mark("render-pages");let C=Array.from({length:Math.max(1,n.concurrency)},()=>co(n,h,m,r.mode,P,w,v));if(await Promise.all(C),m.endMark("render-pages",{pages:h.stats.pagesCompleted}),m.mark("download-assets"),m.progress("Asset download phase started.",{phase:"download-assets",doneAssets:h.doneAssets.size,assetsQueued:h.stats.assetsQueued,assetQueue:h.assetQueue.length}),await Ki(n,P,h,m,w,v),m.endMark("download-assets",{assets:h.doneAssets.size}),w.enabled&&n.maxPages===0&&await fi(n,h,w,m,v),r.mode==="full"){let y=await Qi(n,h,m);for(let x of y)Y(v,n,x);}}finally{await _("dispose crawl request context",mt(n),()=>P.dispose()).catch(C=>{m.warn("Timed out while disposing crawl request context",{error:String(C)});});}}w.trackManifest&&await ye(n,w),await A.writeFile(S.join(n.outputDir,"asset-map.json"),JSON.stringify(h.assetMap,null,2),"utf8"),JSON.stringify(d,null,2)!==JSON.stringify(h.assetMap,null,2)&&Y(v,n,S.join(n.outputDir,"asset-map.json"));let T=r.mode==="single-url"||r.mode==="content-sync"?Ci(n,h):w.enabled&&!r.resumeRewrite?mi(n,w,v,d,h.assetMap):void 0;m.mark("rewrite-text");let E=r.mode==="single-url"||r.mode==="content-sync"?`Rewriting text files touched by URL crawl: 0/${T?.length??0}`:"Rewriting text files...";m.progress(E,{phase:"rewrite-text",index:0,totalFiles:T?.length,changedTextFiles:0}),await or(E);let F=Date.now(),I=await ct(n,h.assetMap,{files:T,previousAssetMap:d,onStart:({totalFiles:P,workerCount:C})=>{m.info(`Rewrite phase scanning ${P} text files.`,{phase:"rewrite-text",totalFiles:P,workerCount:C});},onProgress:async({index:P,totalFiles:C,changedTextFiles:y,file:x,changed:j})=>{j&&Y(v,n,S.join(n.outputDir,x)),m.checkpoint(`Rewriting text file ${P}/${C}`,{phase:"rewrite-text",index:P,totalFiles:C,changedTextFiles:y,file:x}),m.debug(`${j?"Rewrote":"Checked unchanged"} text file ${P}/${C}: ${x}`,{phase:"rewrite-text",index:P,totalFiles:C,changedTextFiles:y,file:x,changed:j});let L=Date.now();if(!(P===1||P===C||P%50===0||L-F>=5e3))return;F=L;let B=`Rewriting text files: ${P}/${C}`;m.progress(B,{phase:"rewrite-text",index:P,totalFiles:C,changedTextFiles:y,file:x}),await or(B);}});w.trackManifest&&(hi(w,T),await ye(n,w)),m.endMark("rewrite-text",{changedTextFiles:I});let O=i?[...v.deletedFiles].sort():w.enabled&&!r.resumeRewrite?await yi(n,h,w,v,m):[],b=[...new Set((T||[]).map(P=>he(n.outputDir,S.isAbsolute(P)?P:S.join(n.outputDir,P))).filter(P=>P!==null))].sort();if(i){let P=[...v.changedFiles].sort(),C=new Set(P),y=new Set(i.directRenderUrls.map($=>ft(n,$,"page")).filter($=>!!$&&C.has($))),x=new Set(i.archiveFamilyUrls.map($=>ft(n,$,"page")).filter($=>!!$&&C.has($))),j=new Set([...h.sitemapLeafUrls].map($=>ft(n,$,"asset")).filter($=>!!$&&C.has($))),L=new Set([...h.sitemapIndexUrls].map($=>ft(n,$,"asset")).filter($=>!!$&&C.has($))),V=new Set([...y,...x,...j,...L]),B=P.filter($=>!V.has($)),K=[...new Set([...i.directRenderUrls,...i.archiveFamilyUrls,...i.sitemapUrls,...h.sitemapLeafUrls,...h.sitemapIndexUrls,...i.deleteUrls].map($=>{let Ye=new URL($);return `${Ye.pathname}${Ye.search}`}))].sort();await _t(n,{schemaVersion:2,generatedAt:new Date().toISOString(),outputDir:S.resolve(n.outputDir),runMode:"content-sync",crawlMode:"incremental",fullSyncRequired:false,changedFiles:P,deletedFiles:O,rewriteTargets:b,consumerId:i.consumerId,fromSequence:i.fromSequence,toSequence:i.toSequence,impactHash:i.impactHash,uploadGroups:{assets:B,content:[...y].sort(),listings:[...x].sort(),sitemapLeaves:[...j].sort(),sitemapIndexes:[...L].reverse()},invalidationPaths:K});}else await _t(n,{schemaVersion:1,generatedAt:new Date().toISOString(),outputDir:S.resolve(n.outputDir),runMode:r.mode,crawlMode:r.crawlMode,fullSyncRequired:!(w.enabled&&!r.resumeRewrite),changedFiles:w.enabled&&!r.resumeRewrite?[...v.changedFiles].sort():[],deletedFiles:w.enabled&&!r.resumeRewrite?O:[],rewriteTargets:w.enabled&&!r.resumeRewrite?b:[]});await Bn(n),m.summary(r.resumeRewrite?`Done. Resumed final rewrite over existing output and changed ${I} text files.`:`Done. Rendered ${h.stats.pagesRendered} pages, processed ${h.doneSitemaps.size} sitemaps, downloaded ${h.doneAssets.size} assets.`,{mode:r.mode,crawlMode:r.crawlMode,resumeRewrite:r.resumeRewrite,...h.stats,pagesRendered:h.stats.pagesRendered,donePages:h.stats.pagesCompleted,claimedPages:h.donePages.size,doneSitemaps:h.doneSitemaps.size,doneAssets:h.doneAssets.size,changedTextFiles:I}),await m.flush();}function Co(e){let t=e/6e4;if(Number.isInteger(t)&&t>=1)return `${t} minute${t===1?"":"s"}`;let n=Math.ceil(e/1e3);return `${n} second${n===1?"":"s"}`}async function X(e,t,n){let s=new AbortController,r=globalThis.setTimeout(()=>{s.abort(new Error(`${e} timed out after ${Co(t)}.`));},t);try{return await n({abortController:s,httpOptions:{abortSignal:s.signal,requestTimeout:t}})}finally{globalThis.clearTimeout(r);}}function Ro(e){return typeof e.subscriptionType=="string"&&e.subscriptionType.trim()!==""}function St(e){let t="";for(let s=0;s<e.length;s++){let r=e[s];if(r==="--profile"){let i=(e[s+1]||"").trim();if(!i)throw new Error("Missing value for --profile.");t=i,s+=1;}else if(r.startsWith("--profile=")){let i=r.slice(10).trim();if(!i)throw new Error("Missing value for --profile.");t=i;}}let n=String(process.env.PUBLISHER_DEPLOY_PROFILE||process.env.PUBLISHER_DEPLOYMENT_PROFILE||"").trim();return t||n||null}function Io(e,t){return {...e,...t??{}}}function xo(e,t){return {...e,...t??{},invalidationPaths:[...(t?.invalidationPaths??e.invalidationPaths)||[]]}}function De(e,t){let n=String(t??e.deploymentTargetOverride??"").trim();if(!Ro(e)){if(n)throw new Error(`Deployment target "${n}" requires an active WPSuite subscription and remote publisher config.`);return {name:null,profile:null,config:e}}let s=String(n||e.defaultDeploymentProfile||"").trim();if(!s)return {name:null,profile:null,config:e};let r=e.deploymentProfiles?.[s];if(!r)throw new Error(`Unknown deployment profile "${s}". Check the linked WPSuite publisher configuration.`);return {name:s,profile:r,config:{...e,targetOrigin:r.targetOrigin??e.targetOrigin,s3:Io(e.s3,r.s3),cloudFront:xo(e.cloudFront,r.cloudFront)}}}var Mr="wpsuite-sha256",Fr="wpsuite-normalized-sha256",Oo=/(?:^|[-_:.])(id|uid|nonce|token|hash|instance)(?:$|[-_:.])/i,ln=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,jo=["SIGINT","SIGTERM"],vt=new Set,Pt=new Map,kr=null;function Uo(e){vt.add(e);let t=false;return ()=>{t||(t=true,vt.delete(e));}}async function Lo(){let e=[...vt];e.length!==0&&await Promise.allSettled(e.map(async t=>{vt.delete(t),await A.rm(t,{recursive:true,force:true});}));}function qo(){if(!(Pt.size>0))for(let e of jo){let t=()=>{kr||(kr=Lo().finally(()=>{for(let[n,s]of Pt)process.off(n,s);Pt.clear(),process.exit(1);}));};Pt.set(e,t),process.on(e,t);}}qo();function _o(e,t){let n=String(process.env.STATIC_PUBLISHER_CRAWL_MANIFEST_PATH||"").trim();if(n)return S.resolve(n);let s=t.trim();return s?S.join(S.resolve(s),"crawl-manifest.json"):S.join(S.resolve(e),".crawl-manifest.json")}function Dr(e){return S.normalize(e).split(S.sep).join("/")}function $r(e,t){let n=S.relative(S.resolve(e),S.resolve(t));return !n||n.startsWith("..")||S.isAbsolute(n)?null:Dr(n)}async function No(e,t,n){let s=_o(e.outputDir,t),r;try{r=await A.readFile(s,"utf8");}catch(l){return l.code==="ENOENT"?(n.warn("Deploy rewrite guard disabled because the crawl manifest is missing.",{manifestPath:s,source:"deploy-guard"}),null):(n.warn("Deploy rewrite guard disabled because the crawl manifest could not be read.",{manifestPath:s,error:l instanceof Error?l.message:String(l),source:"deploy-guard"}),null)}let i;try{i=JSON.parse(r);}catch(l){return n.warn("Deploy rewrite guard disabled because the crawl manifest is invalid JSON.",{manifestPath:s,error:l instanceof Error?l.message:String(l),source:"deploy-guard"}),null}let a=new Map,c=new Map,o=0,u=0;for(let[l,d]of Object.entries(i.pages||{})){let p=String(d?.outputPath||"").trim(),g=p?$r(e.outputDir,p):null;if(g){let f=typeof d?.contentType=="string"&&d.contentType?d.contentType:null;f&&c.set(g,f);}!p||d?.rewriteComplete===true||g&&(o++,a.has(g)||a.set(g,{kind:"page",sourceUrl:l,outputPath:S.resolve(p),relativePath:g}));}for(let[l,d]of Object.entries(i.assets||{})){let p=String(d?.outputPath||"").trim(),g=d?.isText===true,f=p?$r(e.outputDir,p):null;if(f){let w=typeof d?.contentType=="string"&&d.contentType?d.contentType:null;w&&c.set(f,w);}!p||!g||d?.rewriteComplete===true||f&&(u++,a.has(f)||a.set(f,{kind:"asset",sourceUrl:l,outputPath:S.resolve(p),relativePath:f}));}return {manifestPath:s,byRelativePath:a,contentTypeByRelativePath:c,pendingPages:o,pendingTextAssets:u}}function Bo(e){return e&&(ln.test(e)?"__uuid__":/^[0-9a-f]{6,}$/i.test(e)?"__hex__":/^[0-9]{8,}$/.test(e)?"__num__":/^(?=.*[a-z])(?=.*\d)[a-z0-9]{8,}$/i.test(e)?"__alnum__":e)}function on(e){return e.split(/([_:.\-/=?&#]+)/g).map((t,n)=>n%2===1?t:Bo(t)).join("")}function Ho(e){return e.split(/([_:.\-/=?&#]+)/g).map((t,n)=>n%2===1?t:ln.test(t)?"__uuid__":/^[0-9a-f]{6,}$/i.test(t)?"__hex__":/^[0-9]{6,}$/.test(t)?"__num__":/^[a-z0-9_-]{6,}$/i.test(t)?"__id__":t).join("")}function Ct(e,t){return Array.isArray(e)?e.map(n=>Ct(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Ct(s,n)])):typeof e!="string"?e:t&&Oo.test(t)?Ho(e):ln.test(e)?"__uuid__":/^[0-9a-f]{6,}$/i.test(e)||/^[0-9]{8,}$/.test(e)?on(e):e}function Wo(e){return e.replace(/((?:https?:\/\/[^"'\s>]+|\/)(?:wp-content|wp-includes)\/[^"'\s>?]+)\?ver=[A-Za-z0-9._-]+(?=$|[#"'])/gi,"$1")}function zo(e,t){let n=t.trim();if((n.startsWith("{")||n.startsWith("[")||n.startsWith('"'))&&e.startsWith("data-"))try{let r=JSON.parse(n);return JSON.stringify(Ct(r))}catch{}if(e.startsWith("data-")&&/^[A-Za-z0-9+/=]+$/.test(n))try{let r=Buffer.from(n,"base64").toString("utf8"),i=JSON.parse(r),a=JSON.stringify(Ct(i));return Buffer.from(a,"utf8").toString("base64")}catch{}return t}function Qo(e,t){let n=e.toLowerCase();return n==="class"?t.split(/(\s+)/).map((s,r)=>r%2===1?s:on(s)).join(""):n==="id"||n==="for"||n==="aria-controls"||n==="aria-labelledby"||n==="aria-describedby"||n==="aria-owns"||n==="aria-activedescendant"||n==="name"?on(t):n==="href"||n==="src"?Wo(t):zo(n,t)}function Jo(e){return e.replace(/<([a-z][^\s/>]*)([^<>]*?)>/gi,(t,n,s)=>{if(n.startsWith("/"))return t;let r=s.replace(/\s([:@a-zA-Z_][-:.a-zA-Z0-9_]*?)=(['"])([\s\S]*?)\2/g,(i,a,c,o)=>{let u=Qo(a,o);return ` ${a}=${c}${u}${c}`});return `<${n}${r}>`})}function sn(e){let t=S.extname(e).toLowerCase();return [".html",".htm",".xml",".xsl",".txt"].includes(t)||["robots.txt","sitemap.xml"].includes(S.basename(e))}function bt(e,t){return [e.replace(/^\/+|\/+$/g,""),t.replace(/^\/+/,"")].filter(Boolean).join("/")}async function Vo(e,t,n,s){let r=new Map,i,a=0;do{a++;let c=await X(`S3 list objects page ${a} for s3://${t}/${n||""}`,3e5,({httpOptions:o})=>e.send(new ListObjectsV2Command({Bucket:t,Prefix:n||void 0,ContinuationToken:i}),o));for(let o of c.Contents||[]){if(!o.Key)continue;let u=(o.ETag||"").replace(/^"|"$/g,"").toLowerCase(),l=Number(o.Size??0);r.set(o.Key,{etag:u,size:l});}i=c.NextContinuationToken,s.debug(`Listed S3 keys page ${a}: ${r.size} keys so far`);}while(i);return r}async function Ko(e,t,n,s){if(s.has(n))return s.get(n)??null;try{let r=await X(`S3 head object ${n}`,3e5,({httpOptions:a})=>e.send(new HeadObjectCommand({Bucket:t,Key:n}),a)),i={etag:(r.ETag||"").replace(/^"|"$/g,"").toLowerCase(),size:Number(r.ContentLength??0)};return s.set(n,i),i}catch{return s.set(n,null),null}}async function Go(e,t,n,s){let r=[...new Set(Array.from(n).filter(Boolean))];if(r.length===0)return s.info("No explicitly tombstoned S3 objects to delete."),[];s.info(`Deleting ${r.length} explicitly tombstoned S3 object(s)\u2026`);for(let i=0;i<r.length;i+=1e3){let a=r.slice(i,i+1e3);if(a.length===0)continue;let c=await X(`S3 delete objects batch ${Math.floor(i/1e3)+1}`,3e5,({httpOptions:o})=>e.send(new DeleteObjectsCommand({Bucket:t,Delete:{Objects:a.map(u=>({Key:u}))}}),o));if(c.Errors&&c.Errors.length>0){let o=c.Errors.map(u=>`${u.Key||"(unknown)"}: ${u.Code||"DeleteFailed"}`);throw new Error(`S3 reported ${o.length} object deletion error(s): ${o.join(", ")}`)}s.info(`Deleted batch of ${a.length} object(s).`);for(let o of a)s.debug(` deleted: ${o}`);}return r}function Zo(e){return createHash("md5").update(e).digest("hex")}function Er(e){return createHash("sha256").update(e).digest("hex")}function an(e){return createHash("sha256").update(Jo(e.toString("utf8"))).digest("hex")}async function Yo(e,t,n,s){if(s.has(n))return s.get(n)??null;try{let a=((await X(`S3 head object metadata ${n}`,3e5,({httpOptions:c})=>e.send(new HeadObjectCommand({Bucket:t,Key:n}),c))).Metadata?.[Mr]||"").trim().toLowerCase()||null;return s.set(n,a),a}catch{return s.set(n,null),null}}async function Xo(e,t,n,s,r){if(s.has(n))return s.get(n)??null;try{let a=((await X(`S3 head object normalized metadata ${n}`,3e5,({httpOptions:c})=>e.send(new HeadObjectCommand({Bucket:t,Key:n}),c))).Metadata?.[Fr]||"").trim().toLowerCase();if(a)return s.set(n,a),a}catch{return s.set(n,null),null}if(r.has(n)){let i=r.get(n)??null;return s.set(n,i),i}try{let a=await(await X(`S3 get object ${n}`,3e5,({httpOptions:o})=>e.send(new GetObjectCommand({Bucket:t,Key:n}),o))).Body?.transformToByteArray(),c=a?an(Buffer.from(a)):null;return r.set(n,c),s.set(n,c),c}catch{return r.set(n,null),s.set(n,null),null}}function ea(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"profile"}function ta(e,t){let n=e,s=Object.entries(t).sort((r,i)=>i[0].length-r[0].length);for(let[r,i]of s)r&&(n=n.split(r).join(i));return n}async function na(e,t,n,s){let r=S.join(e,"asset-map.json"),i;try{i=await A.readFile(r,"utf8");}catch(o){if(o.code==="ENOENT")return;throw o}let a=JSON.parse(i);if(!a||typeof a!="object")return;let c=Object.fromEntries(Object.entries(a).map(([o,u])=>{let l=String(u??"");return t.urlRewriteMode==="absolute"&&t.targetOrigin&&n.targetOrigin&&t.targetOrigin!==n.targetOrigin&&(l=l.split(t.targetOrigin).join(n.targetOrigin)),l=ta(l,s),[o,l]}));await A.writeFile(r,JSON.stringify(c,null,2),"utf8");}async function ra(e,t,n,s,r,i){let a=e.targetOrigin!==t.targetOrigin,c=Object.keys(s).length>0;if(!n||!a&&!c)return {outputDir:e.outputDir,cleanup:async()=>{}};if(a&&e.urlRewriteMode!=="absolute")throw new Error(`Deployment profile "${n}" changes targetOrigin, but the base crawl output must use urlRewriteMode "absolute" for multi-target redeploys.`);let o=S.join(S.dirname(e.outputDir),`.deploy-profile-${ea(n)}-${Date.now()}`),u=Uo(o);r.info(`Preparing deployment profile "${n}" from existing crawl output to ${o}...`);try{if(await A.rm(o,{recursive:!0,force:!0}),i){await A.mkdir(o,{recursive:!0});for(let g of i){let f=S.join(e.outputDir,g),w=S.join(o,g);await A.mkdir(S.dirname(w),{recursive:!0}),await A.copyFile(f,w);}}else await A.cp(e.outputDir,o,{recursive:!0});let l={...e,sourceOrigin:e.targetOrigin,targetOrigin:t.targetOrigin,extraReplacements:s,outputDir:o},d=1;r.info(`Rewriting text files for deployment profile "${n}"...`);let p=await ct(l,{},{files:i,onStart:({totalFiles:g,workerCount:f})=>{d=f,r.info(`Rewriting ${g} text file(s) for deployment profile "${n}" with ${f} worker(s).`);},onProgress:({index:g,totalFiles:f,changedTextFiles:w,file:m,changed:h})=>{let T=`Rewriting [${g}/${f}] ${m} (${h?"rewrote":"checked"}; ${w} changed so far)`;f<=200||g<=5||g%10===0||g===f?(r.progress(T,{file:m,index:g,totalFiles:f,changed:h,changedTextFiles:w,workerCount:d}),r.info(T)):r.debug(T);}});return await na(o,e,t,s),r.info(`Prepared deployment profile "${n}" in ${o} (${p} rewritten text file(s)).`),{outputDir:o,cleanup:async()=>{u(),await A.rm(o,{recursive:!0,force:!0});}}}catch(l){throw r.error(`Failed to prepare deployment profile "${n}" temporary output.`,{tempDir:o,outputDir:e.outputDir,error:l instanceof Error?l.message:String(l),...l instanceof Error&&l.stack?{stack:l.stack}:{}}),await A.rm(o,{recursive:true,force:true}).catch(()=>{}),u(),await r.flush().catch(()=>{}),l}}async function Or(e=process.argv.slice(2)){let t=await ne(),n=St(e),s=De(t,n),r=S.resolve(s.config.logDir||"logs"),i=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",a=i?S.join(S.resolve(i),"deploy-diff.json"):"",c=new $e(r,"deploy.log.jsonl",s.config.logLevel??"info"),o=s.profile?.extraReplacements??{},u=async()=>{};try{let l=await it(t);if(e.includes("--content-sync")&&l?.schemaVersion!==2)throw new Error("Content-sync deployment requires a valid schema-2 targeted deploy plan.");let p=await Nn(t);if(p)throw new Error(`Deployment blocked: the crawl started at ${p.startedAt} did not complete its final rewrite. Run a successful crawl or resume the rewrite before deploying.`);let g=await ra(t,s.config,s.name,o,c,l?.schemaVersion===2?l.changedFiles:void 0);u=g.cleanup;let f={...s.config,outputDir:g.outputDir},w=f.s3SyncMode??"sdk-upload-delete";if(l?.schemaVersion===2&&l.deletedFiles.length>0&&w!=="sdk-upload-delete")throw new Error("Content-sync tombstones require the sdk-upload-delete S3 sync mode.");let m=l?.schemaVersion!==2&&g.outputDir!==t.outputDir&&(t.targetOrigin!==s.config.targetOrigin||Object.keys(o).length>0),h=!!l&&!l.fullSyncRequired&&!m;if(l?.schemaVersion===2&&!h)throw new Error("Content-sync deployment cannot widen into a full-output deployment.");s.name&&c.info(`Using deployment profile: ${s.name}`),c.info(`Starting deploy \u2014 s3://${f.s3.bucket}/${f.s3.prefix||""} (region: ${f.s3.region})`),c.info(`S3 sync mode: ${w}`),l&&l.fullSyncRequired?c.info("Deploy plan requests a full sync; scanning the whole output tree."):l&&m?c.info("Ignoring incremental deploy plan because deployment-profile rewrites require a full sync."):h&&c.info(`Using incremental deploy plan: ${l.changedFiles.length} changed file(s), ${l.deletedFiles.length} deleted file(s).`),c.mark("deploy");let v=new S3Client({region:f.s3.region}),T=g.outputDir===t.outputDir?await No(t,i,c):null,E=l?.schemaVersion===2?[...l.uploadGroups.assets,...l.uploadGroups.content,...l.uploadGroups.listings,...l.uploadGroups.sitemapLeaves,...l.uploadGroups.sitemapIndexes]:l?.changedFiles??[];if(l?.schemaVersion===2){let k=[...new Set(E)],W=[...new Set(l.changedFiles)];if(k.length!==W.length||W.some(R=>!k.includes(R)))throw new Error("Content-sync deploy-plan upload groups do not cover the exact changed-file set.")}let F=h?(await Promise.all(E.map(async k=>{try{return (await A.stat(S.join(f.outputDir,k))).isFile()?k:null}catch{if(l?.schemaVersion===2)throw new Error(`Content-sync planned upload is missing: ${k}`);return null}}))).filter(k=>k!==null):await Rs(["**/*"],{cwd:f.outputDir,onlyFiles:!0,dot:!0}),I=[],O=[],b=F.filter(k=>{let W=T?.byRelativePath.get(Dr(k));if(!W)return !0;let R=bt(f.s3.prefix,k);return I.push(k),O.push(R),c.reject(W.kind,W.sourceUrl||k,"rewrite not completed; deploy upload blocked","deploy-guard",{file:k,key:R,outputPath:W.outputPath,manifestPath:T?.manifestPath}),!1}),P=new Set((h?b:F).map(k=>bt(f.s3.prefix,k)));T&&(T.pendingPages>0||T.pendingTextAssets>0)&&c.info(`Deploy rewrite guard loaded ${T.pendingPages} pending page(s) and ${T.pendingTextAssets} pending text asset(s) from crawl manifest.`,{manifestPath:T.manifestPath,pendingPages:T.pendingPages,pendingTextAssets:T.pendingTextAssets,source:"deploy-guard"}),I.length>0&&c.warn(`Deploy rewrite guard blocked ${I.length} file(s) from upload because final crawl rewrite is incomplete.`,{rejected:I.length,manifestPath:T?.manifestPath,source:"deploy-guard"}),h?c.info(`Using ${b.length} eligible planned changed file(s) from deploy plan for upload${I.length>0?` (${I.length} blocked by deploy rewrite guard)`:""}.`):c.info(`Found ${F.length} file(s) in output directory "${f.outputDir}"${I.length>0?`; ${b.length} remain eligible for upload after deploy rewrite guard filtering`:""}.`),c.progress("Deploy preflight: comparing local output with remote S3 state.",{phase:"deploy",mode:w,totalFiles:b.length,scannedFiles:F.length,rejected:I.length,deploymentProfile:s.name||"",s3Bucket:f.s3.bucket,s3Prefix:f.s3.prefix||"",targetedPlan:h,deployGuardEnabled:g.outputDir===t.outputDir});let C=0,y=0,x=0,j=[],L=[],V=[],B=[],K=[],$=new Map,Ye=new Map,Hr=new Map,Wr=new Map,zr=new Map;h||(c.info("Listing existing S3 objects to detect unchanged files..."),$=await Vo(v,f.s3.bucket,f.s3.prefix,c),c.info(`Found ${$.size} existing key(s) in S3.`));let Qr=async k=>$.has(k)?$.get(k)??null:h?Ko(v,f.s3.bucket,k,Ye):null;for(let k of b){let W=S.join(f.outputDir,k),R=bt(f.s3.prefix,k),ee=T?.contentTypeByRelativePath.get(k),je=ee&&ee!=="application/octet-stream"?ee:Do.lookup(k)||ee||"application/octet-stream",Jr=sn(k)?f.s3.htmlCacheControl:f.s3.assetCacheControl,U=C+y+x+1;b.length<=200||U<=5||U%10===0||U===b.length?(c.progress(`Uploading [${U}/${b.length}] ${R} (${je})`,{file:k,key:R,index:U,totalFiles:b.length,contentType:je,mode:w}),c.info(`Uploading [${U}/${b.length}] ${R} (${je})`)):c.debug(`Uploading [${U}/${b.length}] ${R} (${je})`);try{let te=await A.readFile(W),Ue=await Qr(R),Le=null,Ie=null;if(Ue){let xt=te.byteLength;if(Ue.size===xt){let Xe=Ue.etag.includes("-");if(Ue.etag!==""&&!Xe){let Vr=Zo(te);if(Ue.etag===Vr){y++,b.length<=200||y<=5||y%25===0?(c.progress(`Skipped unchanged [${U}/${b.length}] ${R}`,{file:k,key:R,index:U,totalFiles:b.length,uploaded:C,skipped:y,failed:x,mode:w,reason:"etag-md5-match"}),c.info(`Skipped unchanged [${U}/${b.length}] ${R}`)):c.debug(`Skipped unchanged [${U}/${b.length}] ${R}`),L.push(R);continue}}Le=Er(te);let hn=await Yo(v,f.s3.bucket,R,Hr);if(hn&&hn===Le){y++,b.length<=200||y<=5||y%25===0?(c.progress(`Skipped unchanged [${U}/${b.length}] ${R}`,{file:k,key:R,index:U,totalFiles:b.length,uploaded:C,skipped:y,failed:x,mode:w,reason:"metadata-sha256-match"}),c.info(`Skipped unchanged [${U}/${b.length}] ${R}`)):c.debug(`Skipped unchanged [${U}/${b.length}] ${R}`),L.push(R);continue}}if(sn(k)){Ie=an(te);let Xe=await Xo(v,f.s3.bucket,R,Wr,zr);if(Xe&&Xe===Ie){y++,b.length<=200||y<=5||y%25===0?(c.progress(`Skipped semantically unchanged [${U}/${b.length}] ${R}`,{file:k,key:R,index:U,totalFiles:b.length,uploaded:C,skipped:y,failed:x,mode:w,reason:"normalized-html-match"}),c.info(`Skipped semantically unchanged [${U}/${b.length}] ${R}`)):c.debug(`Skipped semantically unchanged [${U}/${b.length}] ${R}`),L.push(R);continue}}}Le=Le??Er(te),Ie=Ie??(sn(k)?an(te):null),await X(`S3 upload ${R}`,9e5,({abortController:xt})=>new Upload({client:v,abortController:xt,params:{Bucket:f.s3.bucket,Key:R,Body:te,ContentType:je,CacheControl:Jr,Metadata:{[Mr]:Le,...Ie?{[Fr]:Ie}:{}}}}).done()),C++,j.push(R),(C%25===0||C===b.length)&&(c.progress(`Uploaded ${C}/${b.length} file(s)\u2026`,{uploaded:C,skipped:y,failed:x,totalFiles:b.length,mode:w}),c.info(`Uploaded ${C}/${b.length} file(s)\u2026`));}catch(te){x++,V.push(R),c.error(`Failed to upload ${R}: ${te.message}`,{key:R,error:String(te)});}}if(c.info(`Upload complete: ${C} uploaded, ${y} skipped unchanged, ${O.length} rejected by guard, ${x} failed.`),V.length>0||O.length>0)throw new Error(`Deployment stopped before deletion because ${V.length} upload(s) failed and ${O.length} upload(s) were rejected.`);if(w==="sdk-upload-delete"){let k=new Set((l?.deletedFiles??[]).map(R=>bt(f.s3.prefix,R))),W=[...k].filter(R=>!P.has(R));if(!h&&(K=[...$.keys()].filter(ee=>!P.has(ee)).filter(ee=>!k.has(ee)),K.length>0)){c.warn(`Protected ${K.length} remote-only S3 object(s) from deletion because the crawl did not provide explicit tombstones.`,{protected:K.length,source:"deploy-delete-guard"});for(let ee of K)c.debug(` protected remote-only object: ${ee}`);}B=await Go(v,f.s3.bucket,h?W:W.filter(R=>$.has(R)),c);}else c.info("Sync mode is sdk-upload-only \u2014 skipping stale object deletion.");a&&(await A.mkdir(S.dirname(a),{recursive:!0}),await A.writeFile(a,JSON.stringify({generatedAt:new Date().toISOString(),mode:w,summary:{totalFiles:F.length,eligibleFiles:b.length,uploaded:j.length,skipped:L.length,rejected:O.length,failed:V.length,deleted:B.length,protected:K.length,...s.name?{profile:s.name}:{}},uploadedKeys:j,skippedKeys:L,rejectedKeys:O,failedKeys:V,deletedKeys:B,protectedRemoteOnlyKeys:K},null,2),"utf8")),l?.schemaVersion!==2&&await Te(t),c.endMark("deploy"),await c.flush();}finally{await u().catch(()=>{});}}function ia(e){let t=e;return t.endsWith("/")?t+="index.html":S.posix.basename(t).includes(".")||(t+="/index.html"),t}function jr(e,t){let n=new Set;for(let s of e){let r=new URL(s,"https://content-sync.invalid");if(r.origin!=="https://content-sync.invalid")continue;let i=`${r.pathname}${r.search}`;n.add(i),n.add(`${ia(r.pathname)}${r.search}`);}return [...n].sort()}function ua(){let e=String(process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"").trim();return e?S.join(S.resolve(e),"content-sync-invalidation.json"):""}async function dn(e,t){if(!e)return;await A.mkdir(S.dirname(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await A.writeFile(n,JSON.stringify({...t,updatedAt:new Date().toISOString()},null,2),"utf8"),await A.rename(n,e);}async function la(e,t,n,s){if(!e)return null;try{let r=JSON.parse(await A.readFile(e,"utf8"));if(r.schemaVersion!==1||r.distributionId!==t||r.impactHash!==n||!Array.isArray(r.batches))throw new Error("Content-sync invalidation state does not match the deploy plan.");let i=r.batches.flatMap(a=>a.paths);return i.length!==s.length||i.some((a,c)=>a!==s[c])?null:r}catch(r){if(r.code==="ENOENT")return null;throw r}}function da(e,t=3e3){let n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}async function Lr(e=process.argv.slice(2)){let t=await ne(),n=St(e),s=De(t,n),r=s.config,i=new $e(r.logDir||"logs","invalidate.log.jsonl",r.logLevel??"info"),a=e.includes("--content-sync"),c=await it(t);if(a&&c?.schemaVersion!==2)throw new Error("Content-sync invalidation requires a valid schema-2 targeted deploy plan.");if(s.name&&i.info(`Using deployment profile: ${s.name}`),!r.cloudFront.distributionId){i.info("No CloudFront distributionId configured; skipping invalidation."),await i.flush();return}let o=c?.schemaVersion===2?c.invalidationPaths:r.cloudFront.invalidationPaths.length>0?r.cloudFront.invalidationPaths:["/*"],u=c?.schemaVersion===2?jr(o,r.s3.prefix||""):o;if(c?.schemaVersion===2&&u.some(f=>f==="/*"))throw new Error("Content-sync cannot use a whole-distribution invalidation.");if(u.length===0){i.info("The targeted deploy plan has no CloudFront paths to invalidate."),await i.flush();return}let l=r.cloudFront.distributionId,d=new CloudFrontClient({region:"us-east-1",maxAttempts:5});if(i.mark("invalidate"),c?.schemaVersion!==2){let f=`smartcloud-static-publisher-${Date.now()}`;await X(`CloudFront invalidation for distribution ${l}`,3e5,({httpOptions:w})=>d.send(new CreateInvalidationCommand({DistributionId:l,InvalidationBatch:{CallerReference:f,Paths:{Quantity:u.length,Items:u}}}),w)),i.endMark("invalidate"),await i.flush();return}let p=ua(),g=await la(p,l,c.impactHash,u);if(!g){let f=createHash("sha256").update(JSON.stringify(u)).digest("hex");g={schemaVersion:1,distributionId:l,impactHash:c.impactHash,updatedAt:new Date().toISOString(),batches:da(u).map((w,m)=>({index:m,callerReference:`wpsuite-content-sync-${c.impactHash.slice(0,24)}-${f.slice(0,24)}-${m}`,paths:w,invalidationId:null,status:"pending"}))},await dn(p,g);}for(let f of g.batches){if(!f.invalidationId){let w=await X(`CloudFront targeted invalidation batch ${f.index+1}`,3e5,({httpOptions:h})=>d.send(new CreateInvalidationCommand({DistributionId:l,InvalidationBatch:{CallerReference:f.callerReference,Paths:{Quantity:f.paths.length,Items:f.paths}}}),h)),m=String(w.Invalidation?.Id||"").trim();if(!m)throw new Error("CloudFront did not return an invalidation ID.");f.invalidationId=m,f.status="created",await dn(p,g);}await waitUntilInvalidationCompleted({client:d,maxWaitTime:900,minDelay:2,maxDelay:15},{DistributionId:l,Id:f.invalidationId}),f.status="completed",await dn(p,g),i.info(`CloudFront invalidation batch ${f.index+1}/${g.batches.length} completed.`,{invalidationId:f.invalidationId,pathCount:f.paths.length});}i.endMark("invalidate"),await i.flush();}function It(e){let t=new URL(e);return t.hash="",t.href}function qr(e,t){let n=new Set([...t].map(c=>It(c))),s=new Map,r=new Map,i=c=>{s.set(It(c),c);},a=c=>{if(!c)return;let o=It(c);s.has(o)||r.set(o,c);};for(let c of e.deleteUrls)i(c);for(let c of e.archiveFamilies)if(c.foundPosts===0)for(let o of c.pageUrls)n.has(It(o))||i(o);a(e.directRenderUrls[0]);for(let c of e.archiveFamilies)a(c.pageUrls[0]),a(c.pageUrls.at(-1));for(let c of e.sitemapUrls)a(c);return {expectedAvailable:[...r.values()],expectedMissing:[...s.values()]}}var Nr=["claimed","impact-planned","rendered","deployed","invalidated","verified","acknowledged"];function fn(){let e=String(process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"").trim();if(!e)throw new Error("Content-sync requires a runtime directory.");return S.resolve(e)}function Oe(e,t){return Nr.indexOf(e)>=Nr.indexOf(t)}async function pe(e,t,n,s,r={}){let i={timestamp:new Date().toISOString(),eventType:t,status:t.endsWith("failed")?"failed":"success",actorSource:"content-sync",jobId:n.id||"",command:"content-sync",message:s,details:r};await A.mkdir(e,{recursive:true}),await A.appendFile(S.join(e,"audit-events.jsonl"),`${JSON.stringify(i)}
|
|
11
|
-
`,"utf8");}function ga(e){return qe({postTypes:e.postTypes??[],listingPaths:e.listingPaths??[],includeSubsites:e.includeSubsites,includePostTypeArchives:e.includePostTypeArchives,includeTaxonomyArchives:e.includeTaxonomyArchives,includeAuthorArchives:e.includeAuthorArchives,includeDateArchives:e.includeDateArchives,includePostsPage:e.includePostsPage,includeSitemapChain:e.includeSitemapChain})}function fa(e,t){let n=(e.scheduler?.rules??[]).find(s=>s.command==="content-sync"&&s.id===t);if(!n)throw new Error(`Content-sync scheduler rule not found: ${t}`);if(n.enabled===false)throw new Error(`Content-sync scheduler rule is disabled: ${t}`);return n}async function mn(e,t){if(e.subscriptionType!=="PROFESSIONAL"&&e.subscriptionType!=="AGENCY")throw new Error("Content-sync requires an active Professional or Agency subscription.");let n=ga(t),s=De(e,t.deploymentProfile),r=s.name||"",i=Sn(e.sourceOrigin,String(t.id||""),n),a=Pn({sourceOrigin:e.sourceOrigin,targetOrigin:s.config.targetOrigin,deploymentProfile:r,s3Bucket:s.config.s3.bucket,s3Prefix:s.config.s3.prefix,cloudFrontDistributionId:s.config.cloudFront.distributionId,urlRewriteMode:s.config.urlRewriteMode,extraReplacements:s.profile?.extraReplacements??{}}),c=bn({siteId:e.wpsuite?.siteSettings?.siteId,accountId:e.wpsuite?.siteSettings?.accountId,sourceOrigin:e.sourceOrigin,ruleId:String(t.id||""),targetFingerprint:a}),o=`content-sync:${String(t.id||"")}:${oe({scopeFingerprint:i,targetFingerprint:a}).slice(0,32)}`,u=new tt({sourceOrigin:e.sourceOrigin,runtimeToken:String(e.wpsuite?.runtimeToken||""),ignoreHttpsErrors:e.ignoreHttpsErrors}),l=await u.releaseFingerprint(n.includeSubsites),d=yn({wordpressFingerprint:l,targetFingerprint:a,sourceOrigin:e.sourceOrigin,sitemapPaths:e.sitemapPaths,blockedPathPrefixes:e.blockedPathPrefixes,assetPathPrefixes:e.assetPathPrefixes,noJavaScriptRenderPathPrefixes:e.noJavaScriptRenderPathPrefixes,urlRewriteMode:e.urlRewriteMode});return {rule:t,scope:n,deployment:s,deploymentProfile:r,scopeFingerprint:i,targetFingerprint:a,consumerId:c,coalesceKey:o,client:u,releaseFingerprint:d}}async function ma(e){let t=fn(),n=nt(t),s=await ne(),r=(s.scheduler?.rules??[]).filter(u=>u.command==="content-sync"&&u.enabled!==false);if(r.length===0)return 0;let i=await Et(n),a=await rt(n),c=await $t(n),o=0;for(let u of r){let l=await mn(s,u),d=c.entries[l.coalesceKey];if(!d||d.releaseJobId!==e||d.scopeFingerprint!==l.scopeFingerprint||d.targetFingerprint!==l.targetFingerprint||d.releaseFingerprint!==l.releaseFingerprint)throw new Error(`The normal release has no matching pre-crawl content-sync cutoff for rule ${String(u.id||"")}.`);let p=oe({releaseJobId:e,releaseFingerprint:l.releaseFingerprint,scopeFingerprint:l.scopeFingerprint,targetFingerprint:l.targetFingerprint,sequence:d.sequence}),g=await l.client.establishBaseline({consumerId:l.consumerId,scopeFingerprint:l.scopeFingerprint,baselineId:p,postTypes:l.scope.postTypes,includeSubsites:l.scope.includeSubsites,sequence:d.sequence}),f={schemaVersion:1,ruleId:String(u.id||""),consumerId:l.consumerId,coalesceKey:l.coalesceKey,scopeFingerprint:l.scopeFingerprint,targetFingerprint:l.targetFingerprint,releaseFingerprint:l.releaseFingerprint,baselineId:p,deploymentProfile:l.deploymentProfile,committedSequence:g.committedSequence,releaseJobId:e,verifiedAt:new Date().toISOString()};i.entries[l.coalesceKey]=f;let w=a.rules[l.coalesceKey];a.rules[l.coalesceKey]={ruleId:String(u.id||""),consumerId:l.consumerId,coalesceKey:l.coalesceKey,committedSequence:g.committedSequence,observedHeadSequence:g.headSequence,lag:Math.max(0,g.headSequence-g.committedSequence),lastSuccessfulJobId:w?.lastSuccessfulJobId||e,lastSuccessfulAt:new Date().toISOString(),trailingWorkDetected:g.headSequence>g.committedSequence,retryAttempt:0,nextRetryAt:null,lastError:null,baselineStatus:"ready",baselineReason:null};let m=await En(n,l.coalesceKey);await pe(t,"content-sync-baseline-established",{id:e},"A normal release established a verified content-sync baseline.",{ruleId:u.id,consumerId:l.consumerId,committedSequence:g.committedSequence,supersededCurrent:m}),o++;}return await xn(n,i),await st(n,a),await A.rm(n.releaseCutoff,{force:true}),o}async function ha(e){let t=fn(),n=nt(t),s=await ne(),r=(s.scheduler?.rules??[]).filter(c=>c.command==="content-sync"&&c.enabled!==false);if(r.length===0)return 0;let i=await $t(n),a=0;for(let c of r){let o=await mn(s,c),u=Object.values(i.entries).find(p=>p.releaseJobId===e&&p.ruleId===String(c.id||""));if(u){if(u.coalesceKey===o.coalesceKey&&u.scopeFingerprint===o.scopeFingerprint&&u.targetFingerprint===o.targetFingerprint&&u.releaseFingerprint===o.releaseFingerprint){a++;continue}throw new Error(`The normal release scope changed after its journal cutoff was captured for rule ${String(c.id||"")}. Start a new normal publish instead of resuming this release.`)}let l=await o.client.unboundHead(o.scope.postTypes,o.scope.includeSubsites),d={schemaVersion:1,releaseJobId:e,ruleId:String(c.id||""),coalesceKey:o.coalesceKey,scopeFingerprint:o.scopeFingerprint,targetFingerprint:o.targetFingerprint,releaseFingerprint:o.releaseFingerprint,sequence:l.headSequence,capturedAt:new Date().toISOString()};i.entries[o.coalesceKey]=d,await pe(t,"content-sync-release-cutoff-captured",{id:e},"A normal release captured its pre-crawl content-sync journal cutoff.",{ruleId:c.id,consumerId:o.consumerId,sequence:l.headSequence}),a++;}return await In(n,i),a}async function wa(e,t){let n=JSON.parse(await A.readFile(S.join(e,"current-run.json"),"utf8"));if(n.id!==t||n.command!=="content-sync"||!String(n.ruleId||"").trim())throw new Error("The active queue job is not the requested content-sync job.");return n}async function gn(e,t,n=0){let s=e.protocol==="https:"?Rn:es,r=e.protocol==="https:"?new Rn.Agent({rejectUnauthorized:!t}):void 0;return new Promise((i,a)=>{let c=s.get(e,{agent:r,timeout:3e4,headers:{"user-agent":"WP-Suite-Content-Sync/1"}},o=>{let u=o.statusCode??500,l=o.headers.location;if(u>=300&&u<400&&l&&n<5){o.resume(),gn(new URL(l,e),t,n+1).then(i,a);return}let d=[],p=0;o.on("data",g=>{p+=g.byteLength,p<=1048576&&d.push(g);}),o.on("error",a),o.on("end",()=>i({status:u,body:Buffer.concat(d).toString("utf8")}));});c.on("timeout",()=>c.destroy(new Error(`Verification timed out: ${e}`))),c.on("error",a);})}async function ya(e,t,n,s){let r=t.deployment.config.targetOrigin;if(!/^https?:\/\//i.test(r))throw new Error("Content-sync verification requires an absolute HTTP(S) target origin.");let i=JSON.parse(await A.readFile(s,"utf8")),a=new Set;for(let[o,u]of Object.entries(i.pages??{}))a.add(o),typeof u.url=="string"&&a.add(u.url);let c=qr(n,a);for(let o of c.expectedAvailable){let u=new URL(o),l=new URL(`${u.pathname}${u.search}`,r),d=await gn(l,e.ignoreHttpsErrors);if(d.status<200||d.status>=400)throw new Error(`Content-sync verification failed (${d.status}): ${l}`)}for(let o of c.expectedMissing.slice(0,10)){let u=new URL(o),l=new URL(`${u.pathname}${u.search}`,r),d=await gn(l,e.ignoreHttpsErrors);if(d.status>=200&&d.status<300)throw new Error(`Deleted content is still publicly available: ${l}`)}}async function Sa(e){let t=await A.readFile(e.candidateManifest,"utf8");JSON.parse(t);let n=`${e.trustedManifest}.${process.pid}.tmp`;await A.writeFile(n,t,"utf8"),await A.rename(n,e.trustedManifest);}async function Pa(e,t){try{let n=JSON.parse(await A.readFile(e.candidateManifest,"utf8"));if([...Object.values(n.pages??{}),...Object.values(n.assets??{})].some(r=>r?.lastSeenRunId===t))return "resumed"}catch(n){if(n.code!=="ENOENT")throw new Error(`The content-sync candidate manifest is invalid: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return await A.copyFile(e.trustedManifest,e.candidateManifest).catch(n=>{throw new Error(`A trusted crawl manifest is required before content-sync: ${n instanceof Error?n.message:String(n)}`,{cause:n})}),"initialized"}async function Re(e,t,n,s,r={},i=0,a=async()=>{}){t.phase=n,await An(e,t),await $n(e,{schemaVersion:1,jobId:t.jobId,phase:n,completedItems:s,totalItems:s,attempt:i,updatedAt:new Date().toISOString(),details:r}),await pe(S.dirname(e.state),"content-sync-checkpoint",{id:t.jobId},`Content-sync checkpoint completed: ${n}.`,{phase:n,completedItems:s,totalItems:s,attempt:i,...r}),await a(n,t);}async function ba(e,t={}){let n={loadConfig:ne,resolveRuleContext:mn,runCrawl:Tr,runDeploy:Or,runInvalidate:Lr,verifyDeployment:ya,promoteCandidateManifest:Sa,clearDeployPlan:Te,afterCheckpoint:async()=>{},...t},s=fn(),r=nt(s),i=await wa(s,e),a=await n.loadConfig(),c=fa(a,String(i.ruleId)),o=await n.resolveRuleContext(a,c);if(i.coalesceKey&&i.coalesceKey!==o.coalesceKey)throw new Error("Queued content-sync demand no longer matches the active rule scope.");let l=(await Et(r)).entries[o.coalesceKey];if(!l||l.scopeFingerprint!==o.scopeFingerprint||l.targetFingerprint!==o.targetFingerprint||l.releaseFingerprint!==o.releaseFingerprint)throw await pe(s,"content-sync-baseline-rejected",i,"Content-sync requires a new verified full or incremental release baseline.",{ruleId:c.id,reason:l?"mismatch":"missing"}),new Error("Content-sync baseline is missing or stale. Run a successful normal publish first.");let d=await Mt(r),p=await o.client.head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites});if(d&&d.jobId!==i.id)throw new Error("Another immutable content-sync range is still active.");if(d||(d={schemaVersion:1,jobId:i.id,ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,scopeFingerprint:o.scopeFingerprint,targetFingerprint:o.targetFingerprint,baselineId:l.baselineId,fromSequence:p.committedSequence,toSequence:p.headSequence,phase:"claimed",impactHash:null,startedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},await Re(r,d,"claimed",0,{fromSequence:d.fromSequence,toSequence:d.toSequence},0,n.afterCheckpoint),await pe(s,"content-sync-range-claimed",i,"Content-sync claimed a closed journal range.",{fromSequence:d.fromSequence,toSequence:d.toSequence})),d.fromSequence===d.toSequence){let h=await rt(r);h.rules[o.coalesceKey]={ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,committedSequence:d.toSequence,observedHeadSequence:p.headSequence,lag:Math.max(0,p.headSequence-d.toSequence),lastSuccessfulJobId:i.id,lastSuccessfulAt:new Date().toISOString(),trailingWorkDetected:false,retryAttempt:0,nextRetryAt:null,lastError:null},await st(r,h),await Ft(r);return}let g=await Tn(r);if(!Oe(d.phase,"impact-planned")){let h=await o.client.events({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites,afterSequence:d.fromSequence,throughSequence:d.toSequence}),v=kt({events:h,scope:o.scope,sourceOrigin:a.sourceOrigin}),T=await o.client.resolveImpactFamilies(v,o.scope.includeSubsites);g=Cn({jobId:i.id,ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,scopeFingerprint:o.scopeFingerprint,targetFingerprint:o.targetFingerprint,baselineId:l.baselineId,sourceOrigin:a.sourceOrigin,scope:o.scope,fromSequence:d.fromSequence,toSequence:d.toSequence,events:h,resolvedArchiveFamilies:T,sitemapUrls:a.sitemapPaths}),await kn(r,g),d.impactHash=g.impactHash,await Re(r,d,"impact-planned",h.length,{eventCount:h.length,foldedCount:g.foldedCount,impactHash:g.impactHash},0,n.afterCheckpoint),await pe(s,"content-sync-impact-planned",i,"Content-sync persisted an immutable impact plan.",{impactHash:g.impactHash,eventCount:h.length});}if(!g||g.jobId!==i.id||d.impactHash!==g.impactHash)throw new Error("The immutable content-sync impact plan is missing or mismatched.");if(process.env.STATIC_PUBLISHER_CRAWL_MANIFEST_PATH=r.candidateManifest,!Oe(d.phase,"rendered")){let h=await Pa(r,i.id);await pe(s,h==="resumed"?"content-sync-render-resumed":"content-sync-render-initialized",i,h==="resumed"?"Content-sync resumed its candidate crawl manifest.":"Content-sync initialized a candidate crawl manifest.",{impactHash:g.impactHash}),await n.runCrawl(["--content-sync-plan",r.impact]),await Re(r,d,"rendered",g.directRenderUrls.length+g.archiveFamilyUrls.length,{impactHash:g.impactHash},i.attempt??0,n.afterCheckpoint);}let f=o.deploymentProfile?["--profile",o.deploymentProfile]:[];if(Oe(d.phase,"deployed")||(await n.runDeploy([...f,"--content-sync"]),await Re(r,d,"deployed",1,{impactHash:g.impactHash},0,n.afterCheckpoint),await pe(s,"content-sync-deployed",i,"Content-sync targeted deployment completed.",{impactHash:g.impactHash})),Oe(d.phase,"invalidated")?Oe(d.phase,"verified")||await n.runInvalidate([...f,"--content-sync"]):(await n.runInvalidate([...f,"--content-sync"]),await Re(r,d,"invalidated",1,{impactHash:g.impactHash},0,n.afterCheckpoint)),Oe(d.phase,"verified")||(await n.verifyDeployment(a,o,g,r.candidateManifest),await n.promoteCandidateManifest(r),await Re(r,d,"verified",1,{impactHash:g.impactHash},0,n.afterCheckpoint)),p=await o.client.head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites}),p.committedSequence===d.fromSequence)await o.client.acknowledge({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,expectedSequence:d.fromSequence,sequence:d.toSequence,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites});else if(p.committedSequence!==d.toSequence)throw new Error("Content-sync acknowledgement cursor is in an unexpected state.");await Re(r,d,"acknowledged",1,{sequence:d.toSequence},0,n.afterCheckpoint),await pe(s,"content-sync-cursor-acknowledged",i,"Content-sync committed its journal cursor after verification.",{sequence:d.toSequence});let w=await o.client.head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites}),m=await rt(r);m.rules[o.coalesceKey]={ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,committedSequence:d.toSequence,observedHeadSequence:w.headSequence,lag:Math.max(0,w.headSequence-d.toSequence),lastSuccessfulJobId:i.id,lastSuccessfulAt:new Date().toISOString(),trailingWorkDetected:w.headSequence>d.toSequence,retryAttempt:0,nextRetryAt:null,lastError:null},await st(r,m),await n.clearDeployPlan(a),await A.rm(S.join(s,"content-sync-invalidation.json"),{force:true}),await A.rm(r.candidateManifest,{force:true}),await Ft(r);}async function Br(e=process.argv.slice(2)){let n=e.indexOf("--capture-baseline-cutoffs");if(n>=0){let a=String(e[n+1]||"").trim();if(!a)throw new Error("--capture-baseline-cutoffs requires a release job ID.");await ha(a);return}let s=e.indexOf("--establish-baselines");if(s>=0){let a=String(e[s+1]||"").trim();if(!a)throw new Error("--establish-baselines requires a release job ID.");await ma(a);return}let r=e.indexOf("--job-id"),i=r>=0?String(e[r+1]||"").trim():"";if(!i)throw new Error("Content-sync requires --job-id.");await ba(i);}Br().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1);});
|
|
10
|
+
${i}`,40);return s.info(`Using generated 404 fallback change token for ${n}`,{url:n,requestPath:e.generated404RequestPath,source:"generated-404-change-token-fallback"}),{url:n,supported:!0,token:a,tokenSource:"generated-404-response-hash",postId:null,dependencyPostIds:[],reason:null}}catch(r){return s.warn(`Generated 404 fallback token lookup failed for ${n}`,{url:n,error:String(r),requestPath:e.generated404RequestPath,source:"generated-404-change-token-fallback"}),null}}async function mi(e,t,n,s,r,i){let a=on(e,r);if(!s.enabled)return {action:"render",changeToken:s.trackManifest?await wt(e,t,s,r,i):null};let c=s.manifest.pages[r];if(!c)return {action:"render",changeToken:await wt(e,t,s,r,i)};let o=await wt(e,t,s,r,i);if(o?.supported&&o.token)return c.changeToken===o.token?a&&!await hi(e,t,r,i)?{action:"render",changeToken:o}:{action:"reuse",changeToken:o}:{action:"render",changeToken:o};let u=Ke(n.sitemapLastmodByPage[r]);return u&&c.sitemapLastmod&&c.sitemapLastmod===u?{action:"reuse",changeToken:o}:{action:"render",changeToken:o}}async function hi(e,t,n,s){try{let i=(await t.get(n,{timeout:Math.min(e.navigationTimeoutMs,15e3),failOnStatusCode:!1})).status();return i===404?!0:(s.warn(`Generated 404 request path no longer returns 404 for ${n}`,{url:n,status:i,requestPath:e.generated404RequestPath,source:"generated-404-status-probe"}),!1)}catch(r){return s.warn(`Generated 404 status probe failed for ${n}`,{url:n,error:String(r),requestPath:e.generated404RequestPath,source:"generated-404-status-probe"}),false}}async function wi(e,t,n,s,r){let i=ur(n.previousManifest,void 0,s,"previous-manifest"),a=0;for(let[p,g]of Object.entries(n.manifest.pages))if(!n.seenPages.has(p)){cr(r,e,g.outputPath);try{await A.unlink(g.outputPath);}catch(f){(f.code||"")!=="ENOENT"&&s.warn(`Failed to remove stale incremental page output for ${p}`,{url:p,outputPath:g.outputPath,error:String(f)});}delete n.manifest.pages[p],a++;}let c=ur(n.manifest,n.runId,s,"active-manifest"),o=new Set,u=new Set;for(let p of c){for(let w of Ge(e,p))o.add(w);let g=n.manifest.assets[p]?.outputPath;g&&u.add(g);let f=Oe(e,t.assetMap,p);f&&u.add(f);}for(let p of Object.keys(n.manifest.assets))c.has(p)||delete n.manifest.assets[p];let l=0,d=0;for(let p of i){let g=new Set,f=n.previousManifest.assets[p]?.outputPath;f&&g.add(f);let w=Oe(e,t.assetMap,p);if(!c.has(p)&&w)g.add(w);else if(!c.has(p)){let m=Di(e,p,s,"incremental-cleanup");m&&(g.add(m.originalFilePath),m.hashedFilePath&&g.add(m.hashedFilePath));}for(let m of g)if(!u.has(m)){cr(r,e,m);try{await A.unlink(m),l++;}catch(h){(h.code||"")!=="ENOENT"&&s.warn(`Failed to remove stale incremental asset output for ${p}`,{url:p,outputPath:m,error:String(h)});}}for(let m of Ge(e,p))o.has(m)||Object.prototype.hasOwnProperty.call(t.assetMap,m)&&(delete t.assetMap[m],d++);}(a>0||l>0||d>0)&&s.info(`Incremental cleanup removed ${a} stale pages, ${l} stale assets, ${d} stale asset mappings`,{removedPages:a,removedAssets:l,removedAssetMappings:d,phase:"incremental-cleanup"});}function ur(e,t,n,s){let r=new Set,i=a=>{let c=a.trim();if(c){if(n){let o=Pe(c,n,"asset",s??"manifest");if(!o)return;r.add(o.toString());return}r.add(c);}};for(let a of Object.values(e.pages))for(let c of a.discoveredAssets||[])i(c);for(let[a,c]of Object.entries(e.assets||{}))t&&c.lastSeenRunId!==t||i(a);return r}function lr(e,t,n){for(let s of t)for(let r of Ge(e,s))if(n.has(r))return true;return false}function yi(e,t,n,s,r){let i=new Set(n.rewriteTargets);for(let c of Object.values(t.manifest.pages))c.rewriteComplete||i.add(S.resolve(c.outputPath));for(let c of Object.values(t.manifest.assets))c.isText&&!c.rewriteComplete&&i.add(S.resolve(c.outputPath));let a=di(s,r);if(a.size===0)return [...i];for(let c of Object.values(t.manifest.pages))lr(e,c.discoveredAssets,a)&&i.add(S.resolve(c.outputPath));for(let[c,o]of Object.entries(t.manifest.assets)){o.isText&&lr(e,o.discoveredAssets,a)&&i.add(S.resolve(o.outputPath));for(let u of Ge(e,c))if(a.has(u)){Y(n,e,o.outputPath),o.isText&&i.add(S.resolve(o.outputPath));break}}return [...i]}function Si(e,t){let n=t?new Set(Array.from(t,r=>S.resolve(r))):null,s=r=>n===null||n.has(S.resolve(r));for(let r of Object.values(e.manifest.pages))s(r.outputPath)&&(r.rewriteComplete=true);for(let r of Object.values(e.manifest.assets)){if(!r.isText){r.rewriteComplete=true;continue}s(r.outputPath)&&(r.rewriteComplete=true);}}function Pi(e,t,n){let s=new Set,r=i=>{if(!i)return;let a=we(e.outputDir,i);a&&s.add(a);};for(let i of t.donePages)r(le(e,i));for(let i of Object.values(n.manifest.pages))i.lastSeenRunId===n.runId&&r(i.outputPath);for(let i of t.doneAssets)r(Oe(e,t.assetMap,i));for(let i of Object.values(n.manifest.assets))i.lastSeenRunId===n.runId&&r(i.outputPath);return s}async function bi(e,t,n,s,r){let i=[...s.deletedFiles].sort(),a=Pi(e,t,n),c=0;for(let l of [...a].sort()){try{if((await A.stat(S.join(e.outputDir,l))).isFile())continue}catch{}c++,r.warn(`Active output is missing after crawl: ${l}`,{phase:"deploy-plan",file:l,outputPath:S.join(e.outputDir,l)});}if(c>0&&r.warn(`Detected ${c} active output file(s) missing before deploy plan save.`,{phase:"deploy-plan",missingActiveOutputs:c}),i.length===0)return [];let o=[],u=0;for(let l of i){if(!a.has(l)){o.push(l);continue}u++;let d=S.join(e.outputDir,l),p;try{p=(await A.stat(d)).isFile();}catch{p=false;}r.warn(`Deploy plan protected active output from deletion: ${l}`,{phase:"deploy-plan",file:l,outputPath:d,exists:p});}return u>0&&r.info(`Deploy plan skipped ${u} active output deletion(s).`,{phase:"deploy-plan",protectedDeletes:u,deletedFiles:o.length}),o}function Ge(e,t){let n=new Set([t]);try{let s=new URL(t),i=[new URL(e.sourceOrigin).origin,...Object.keys(e.extraReplacements||{})];if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{i.push(new URL(e.targetOrigin).origin);}catch{}for(let a of i)try{n.add(new URL(a).origin+s.pathname+s.search);}catch{}n.add(s.pathname+s.search),n.add(s.pathname);}catch{}return [...n]}function vi(e,t){let n=new Set([t]);try{let s=new URL(t),i=[new URL(e.sourceOrigin).origin,...Object.keys(e.extraReplacements||{})];if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{i.push(new URL(e.targetOrigin).origin);}catch{}for(let a of i)try{n.add(new URL(a).origin+s.pathname+s.search);}catch{}n.add(s.pathname+s.search);}catch{}return [...n]}function Ir(e,t){let n=e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/"?e.targetOrigin:"https://relative.invalid/";try{let s=new URL(t,n);return S.join(e.outputDir,sn(s.pathname))}catch{return null}}function Ci(e,t,n){for(let s of vi(e,n)){let r=t[s];if(!r)continue;let i=Ir(e,r);if(i)return {outputPath:i,publicUrl:r}}return null}function Ri(e,t,n){for(let s of Ge(e,n)){let r=t[s];if(!r)continue;let i=Ir(e,r);if(i)return i}return null}function Oe(e,t,n){let s=Ri(e,t,n);if(s)return s;try{return bt(e,n).originalFilePath}catch{return null}}function Ii(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?S.join(S.resolve(e),"queue-runner-heartbeat.json"):""}async function dr(e){let t=Ii();if(t)try{let n=await A.readFile(t,"utf8"),s=JSON.parse(n);if(!s||typeof s!="object")return;await A.writeFile(t,JSON.stringify({...s,checkedAt:new Date().toISOString(),status:"running",currentStep:"rewrite",message:e},null,2),"utf8");}catch{}}function xi(e,t){let n=new Set;for(let s of t.donePages)n.add(S.resolve(le(e,s)));for(let s of t.doneAssets){let r=Oe(e,t.assetMap,s);!r||!ye(r)||n.add(S.resolve(r));}for(let s of t.doneSitemaps){let r=Oe(e,t.assetMap,s);!r||!ye(r)||n.add(S.resolve(r));}return [...n]}var St="re:",mt=new Map;function Ai(e){if(!e.startsWith(St))return null;let t=mt.get(e);if(t!==void 0)return t||null;let n=e.slice(St.length).trim();if(!n)return mt.set(e,false),null;try{let s=new RegExp(n);return mt.set(e,s),s}catch{return console.warn(`[crawl] Ignoring invalid path matcher regex: ${e}`),mt.set(e,false),null}}function rn(e,t){let n=Ai(t);return n?n.test(e):t.startsWith(St)?false:e.startsWith(t)}function Ti(e,t){return t.find(n=>rn(e,n))}function xr(e,t){let n=Ti(t.pathname,e.blockedPathPrefixes);if(n)return n.startsWith(St)?`blocked path regex: ${n}`:`blocked path prefix: ${n}`;let s=e.blockedSearchFragments.find(r=>t.search.includes(r));return s?`blocked search fragment: ${s}`:null}function ki(e){let t=new URL(e.sourceOrigin),n=new Set([t.hostname,...e.allowedAssetHosts]);if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{n.add(new URL(e.targetOrigin).hostname);}catch{}for(let s of Object.keys(e.extraReplacements||{}))try{n.add(new URL(s).hostname);}catch{}return n}function $i(e,t){return ki(e).has(t.hostname)}function Ei(e){let t=ce(e.trim()).replace(/\\\//g,"/").replace(/^['"]|['"]$/g,"").trim();return t=t.replace(/[)]+$/g,"").trim(),t=t.replace(/;.*$/g,"").trim(),t}function Xt(e){let t=ce(e).replace(/\\\//g,"/");return /[{}]|\bwindow\.|\blocation\.|\bincludes\(|\?\?null|\+|%7B|%7D|%22|<|>|\s/.test(t)||/[()[\]'"]/.test(t)}function Mi(e){let t=ce(e).replace(/\\\//g,"/").trim(),n=S.extname(t).toLowerCase();return Sr.has(n)||Pr.has(n)?false:/^(?:this|[A-Za-z_$][\w$]*)\.[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(t)}function je(e){return ni.some(t=>e.pathname.startsWith(t))}function W(e,t,n=e.sourceOrigin,s,r="url"){let i=Ei(t);if(!i||i.startsWith("data:")||i.startsWith("blob:")||i.startsWith("mailto:")||i.startsWith("tel:")||i.startsWith("#"))return s?.ignore(r,t,"empty or unsupported scheme",n),null;if(Xt(i))return s?.ignore(r,t,"looks like JavaScript/code fragment",n),null;if(Mi(i))return s?.ignore(r,t,"looks like JavaScript property access",n),null;try{let a=new URL(i,n);if(Ar(a))return s?.reject(r,t,"malformed URL encoding",n),null;if(!["http:","https:"].includes(a.protocol))return s?.ignore(r,t,"unsupported protocol: ",n),null;if(!$i(e,a))return s?.ignore(r,a.toString(),"host not allowed",n),null;let c=xr(e,a);if(c)return s?.reject(r,a.toString(),c,n),null;let o=new URL(e.sourceOrigin);return a.protocol=o.protocol,a.host=o.host,a.hash="",a}catch{return s?.reject(r,t,"invalid URL",n),null}}function Ar(e){try{return decodeURIComponent(e.pathname),decodeURIComponent(e.search),decodeURIComponent(e.hash),!1}catch{return true}}function Pe(e,t,n,s){try{let r=new URL(e);return Ar(r)?(t.reject(n,e,"malformed URL encoding",s),null):r.protocol!=="http:"&&r.protocol!=="https:"?(t.reject(n,e,`unsupported protocol: ${r.protocol}`,s),null):r}catch{return t.reject(n,e,"invalid URL",s),null}}function Tr(e){return Sr.has(S.extname(e.pathname).toLowerCase())}function be(e){return je(e)?false:Pr.has(S.extname(e.pathname).toLowerCase())}function Ue(e){let t=e.pathname.toLowerCase();return t.endsWith(".xml")&&(t.includes("sitemap")||t.endsWith("/sitemap.xml"))}function L(e,t){return !!(Ue(t)||t.pathname==="/robots.txt"||t.pathname==="/llms.txt"||t.pathname.toLowerCase().endsWith(".xsl")||e.assetPathPrefixes.length>0&&e.assetPathPrefixes.some(n=>rn(t.pathname,n))||Tr(t)||!be(t)&&!je(t))}function le(e,t){let n=new URL(t),s=sn(n.pathname);return s.endsWith("/")?s+="index.html":S.extname(s)||(s+="/index.html"),S.join(e.outputDir,s)}function sn(e){try{return decodeURIComponent(e)}catch{return e}}function Fi(e){if(!e.generated404RequestPath)return null;try{let t=new URL(e.generated404RequestPath,e.sourceOrigin);return !t.pathname.endsWith("/")&&S.extname(t.pathname)===""&&(t.pathname+="/"),t.hash="",t.toString()}catch{return null}}function on(e,t){let n=Fi(e);if(!n)return false;try{return new URL(t,e.sourceOrigin).toString()===n}catch{return false}}function bt(e,t){let n=new URL(t),s=sn(n.pathname);s.endsWith("/")&&(s+="index.html");let r=!!n.search,i=s,a=S.join(e.outputDir,i),c=zt(e.targetOrigin,i),o=`${c}${n.search}`;if(!r)return {originalPathname:i,originalFilePath:a,originalPublicUrl:c,originalPublicUrlWithSearch:o,preferQueryHashed:r};let u=S.extname(s),d=`${u?s.slice(0,-u.length):s}.${Je(n.search)}${u||".bin"}`;return {originalPathname:i,originalFilePath:a,originalPublicUrl:c,originalPublicUrlWithSearch:o,preferQueryHashed:r,hashedPathname:d,hashedFilePath:S.join(e.outputDir,d),hashedPublicUrl:zt(e.targetOrigin,d)}}function Di(e,t,n,s){let r=Pe(t,n,"asset",s);return r?bt(e,r.toString()):null}function Oi(e,t,n,s,r){t[n]=s;try{let i=new URL(n),c=[new URL(e.sourceOrigin).origin,...Object.keys(e.extraReplacements||{})];if(e.targetOrigin&&e.targetOrigin!=="."&&e.targetOrigin!=="/")try{c.push(new URL(e.targetOrigin).origin);}catch{}for(let o of c)try{let u=new URL(o);t[u.origin+i.pathname+i.search]=s;}catch{}try{let o=(()=>{let u=new URL(s,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin);return `${u.pathname}${u.search}`})();t[i.pathname+i.search]=o;}catch{}try{let o=new URL(s,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin).pathname;t[i.pathname]=o;}catch{}try{let o=new URL(r,e.targetOrigin==="."?"https://relative.invalid":e.targetOrigin).pathname;t[i.pathname]=o;}catch{}}catch{}}async function kr(e){try{return await A.readFile(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function De(e){try{return await A.stat(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function ji(e){let t=String(e["content-length"]||"").trim();if(!t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)&&n>=0?n:null}function $r(e){let t=String(e["last-modified"]||"").trim();if(!t)return null;let n=Date.parse(t);return Number.isFinite(n)?n:null}function Ui(e,t){let n=$r(t),s=ji(t),r=e?.mtime.getTime();return n!==null&&Math.abs((r??0)-n)>=1e3||s!==null&&e?.size!==s?false:n!==null||s!==null}async function Li(e,t){if(!t)return;let n=$r(t);if(n===null)return;let s=await De(e);if(!s)return;let r=new Date(n);await A.utimes(e,s.atime,r).catch(()=>{});}function pr(e,t){let n=S.extname(e.pathname).toLowerCase(),s=t["content-type"]||"";return ti.has(n)||ei.some(r=>s.includes(r))&&!s.startsWith("image/")&&!s.includes("font")}function qi(e){try{let t=S.extname(new URL(e).pathname).toLowerCase();return t===".js"||t===".mjs"}catch{return false}}function Fe(e,t){(e.doneAssets.size%25===0||e.doneAssets.size===1||e.doneAssets.size===e.stats.assetsQueued)&&t.progress(`Asset processing progress: processed ${e.doneAssets.size}, discovered ${e.stats.assetsQueued}.`,{doneAssets:e.doneAssets.size,assetsQueued:e.stats.assetsQueued,phase:"download-assets"});}function _i(e){return Je(e.toString("base64"),40)}function Ni(e,t,n){let s=e.assetVariantDigestsByOriginalPath.get(t);if(!s||s.size===0)return false;for(let r of s)if(r!==n)return true;return false}function Bi(e,t,n){let s=e.assetVariantDigestsByOriginalPath.get(t);s||(s=new Set,e.assetVariantDigestsByOriginalPath.set(t,s)),s.add(n);}async function en(e,t,n,s,r,i,a){let c=bt(e,n),o=_i(s),u=c.originalFilePath,l=c.originalPublicUrlWithSearch;if(c.preferQueryHashed&&c.hashedFilePath&&c.hashedPublicUrl&&Ni(r,c.originalFilePath,o)){let f=Ci(e,t,n);f?(u=f.outputPath,l=f.publicUrl):(u=c.hashedFilePath,l=c.hashedPublicUrl);}Oi(e,t,n,l,c.originalPublicUrl);let d=ye(u)?Buffer.from(Vt(s.toString("utf8"),e,t,u),"utf8"):s,p=await kr(u),g=false;return (p===null||!p.equals(d))&&(await Ve(u,d),g=true),i?.debug(`${g?"Saved":"Skipped unchanged"} asset output ${n}`,{phase:"download-assets",url:n,outputPath:u,bytes:d.length,wroteFile:g}),Bi(r,c.originalFilePath,o),await Li(u,a),r.stats.assetsSaved++,i&&(r.stats.assetsSaved%50===0||r.stats.assetsSaved===1)&&i.progress(`Asset progress: saved ${r.stats.assetsSaved}, discovered ${r.stats.assetsQueued}, pending ${r.assetQueue.length}.`,{assetsSaved:r.stats.assetsSaved,assetsQueued:r.stats.assetsQueued,assetQueue:r.assetQueue.length,phase:"download-assets"}),{outputPath:u,publicUrl:l,wroteFile:g}}function Ze(e,t,n,s,r){let i=()=>{let d=String(r??"").trim();if(!d)return {discoveredFrom:"",discoveredFromType:"unknown"};if(d==="seed-path"||d==="cli"||d==="generated-404-request-path")return {discoveredFrom:d,discoveredFromType:d};if(/^https?:\/\//i.test(d))try{let p=new URL(d);return Ue(p)?{discoveredFrom:d,discoveredFromType:"sitemap"}:L(e,p)?{discoveredFrom:d,discoveredFromType:"asset"}:be(p)&&!je(p)?{discoveredFrom:d,discoveredFromType:"page"}:{discoveredFrom:d,discoveredFromType:"url"}}catch{return {discoveredFrom:d,discoveredFromType:"url"}}return {discoveredFrom:d,discoveredFromType:"url"}},a=r&&/^https?:\/\//i.test(r)?r:e.sourceOrigin,c=W(e,n,a,s,"page");if(!c)return;if(!be(c)||Tr(c)){if(L(e,c)){s.info(`Seeded/non-page URL queued as asset: ${c.toString()}`,{url:c.toString(),source:r}),H(e,t,c.toString(),s,r);return}s.reject("page",c.toString(),je(c)?"asset/internal path cannot be page":"not page-like",r);return}let o=c.toString(),{discoveredFrom:u,discoveredFromType:l}=i();u&&!t.pageDiscoverySources.has(o)&&t.pageDiscoverySources.set(o,u),!t.donePages.has(o)&&!t.queuedPages.has(o)&&(t.queuedPages.add(o),t.pageQueue.push(o),t.stats.pagesQueued++,s.debug(`Queued discovered page ${o}`,{phase:"discovery",url:o,discoveredFrom:u,discoveredFromType:l,outputPath:le(e,o)}),(t.stats.pagesQueued%25===0||t.stats.pagesQueued===1)&&s.progress(`Discovery progress: pages ${t.stats.pagesQueued}, assets ${t.stats.assetsQueued}, sitemaps ${t.stats.sitemapsQueued}.`,{pagesQueued:t.stats.pagesQueued,assetsQueued:t.stats.assetsQueued,sitemapsQueued:t.stats.sitemapsQueued,pageQueue:t.pageQueue.length,phase:"discovery"}));}function H(e,t,n,s,r){let i=r&&/^https?:\/\//i.test(r)?r:e.sourceOrigin,a=W(e,n,i,s,"asset");if(!a)return;if(!L(e,a)){s.reject("asset",a.toString(),"not a safe asset path/prefix",r);return}let c=a.toString();!t.doneAssets.has(c)&&!t.queuedAssets.has(c)&&(t.queuedAssets.add(c),t.assetQueue.push(c),t.stats.assetsQueued++,(t.stats.assetsQueued%100===0||t.stats.assetsQueued===1)&&s.progress(`Discovery progress: pages ${t.stats.pagesQueued}, assets ${t.stats.assetsQueued}, sitemaps ${t.stats.sitemapsQueued}.`,{pagesQueued:t.stats.pagesQueued,assetsQueued:t.stats.assetsQueued,sitemapsQueued:t.stats.sitemapsQueued,assetQueue:t.assetQueue.length,phase:"discovery"}));}function Pt(e,t,n,s,r){let i=r&&/^https?:\/\//i.test(r)?r:e.sourceOrigin,a=W(e,n,i,s,"sitemap");if(!a)return;if(!Ue(a)){s.reject("sitemap",a.toString(),"not sitemap-like",r);return}let c=a.toString();!t.doneSitemaps.has(c)&&!t.queuedSitemaps.has(c)&&(t.queuedSitemaps.add(c),t.sitemapQueue.push(c),t.stats.sitemapsQueued++,(t.stats.sitemapsQueued%10===0||t.stats.sitemapsQueued===1)&&s.progress(`Discovery progress: pages ${t.stats.pagesQueued}, assets ${t.stats.assetsQueued}, sitemaps ${t.stats.sitemapsQueued}.`,{pagesQueued:t.stats.pagesQueued,assetsQueued:t.stats.assetsQueued,sitemapsQueued:t.stats.sitemapsQueued,sitemapQueue:t.sitemapQueue.length,phase:"discovery"}));}function Wi(e){let t=ce(e),n=[...t.matchAll(/<url>\s*([\s\S]*?)\s*<\/url>/gi)].map(s=>s[1]);return n.length>0?n.map(s=>{let r=s.match(/<loc>\s*([^<]+?)\s*<\/loc>/i);if(!r?.[1])return null;let i=s.match(/<lastmod>\s*([^<]+?)\s*<\/lastmod>/i);return {loc:r[1].trim(),lastmod:Ke(i?.[1]??null)}}).filter(s=>!!s):[...t.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/gi)].map(s=>({loc:s[1].trim(),lastmod:null})).filter(s=>s.loc)}function Hi(e){return e.split(",").map(t=>t.trim().split(/\s+/)[0]).filter(Boolean)}function zi(e){let t=[],n=/url\(\s*(?:"([^"]+)"|'([^']+)'|([^)]*?))\s*\)/gi;for(let s of e.matchAll(n)){let r=e.slice(Math.max(0,s.index-8),s.index);if(/\bnew\s+$/i.test(r))continue;let i=(s[1]||s[2]||s[3]||"").trim();i&&t.push(i);}return t}function Qi(e){return e.replace(/<script\b[^>]*>[\s\S]*?<\/script\s*>/gi,"")}function Ji(e,t){if(t==="dom-style")return true;let n=(()=>{try{return S.extname(new URL(e).pathname).toLowerCase()}catch{return ""}})();return !(n===".js"||n===".mjs"||n===".map"||t.includes("javascript"))}function Gt(e){return e.trim().replace(/\\/g,"/").replace(/^https?:\/\/[^/]+/i,"").replace(/^\/+/,"")}async function Er(e,t,n,s){let r=[];await A.mkdir(t,{recursive:true});let i=await A.readdir(e,{withFileTypes:true});for(let a of i){let c=S.join(e,a.name),o=S.join(t,a.name);if(a.isDirectory()){r.push(...await Er(c,o,n,s));continue}await Mr(c,o,n,s)&&r.push(o);}return r}async function Vi(e,t){try{let[n,s]=await Promise.all([A.stat(e),A.stat(t)]);if(n.size!==s.size)return !1;let[r,i]=await Promise.all([A.readFile(e),A.readFile(t)]);return r.equals(i)}catch{return false}}async function Mr(e,t,n,s){let r=S.resolve(t);return n.has(r)?(s.debug("Skipped post-crawl copy over crawled page output",{phase:"copy-extra-paths",sourcePath:e,targetPath:t}),false):await Vi(e,t)?(s.debug("Skipped unchanged post-crawl copy target",{phase:"copy-extra-paths",sourcePath:e,targetPath:t}),false):(await A.mkdir(S.dirname(t),{recursive:true}),await A.copyFile(e,t),true)}async function Ki(e,t,n){let s=Object.entries(e.postCrawlCopyMap||{}).map(([c,o])=>({sourcePath:c.trim(),prefix:String(o||"").trim()}));if(s.length===0)return [];let r=0,i=[],a=new Set([...t.donePages].map(c=>S.resolve(le(e,c))));n.mark("copy-extra-paths");for(let c of s){let o=c.sourcePath,u=c.prefix;if(!o||!u){n.warn("Skipped post-crawl copy mapping with empty key/value",{sourcePath:o,prefixPath:u});continue}let l=oi(o);if(!l.resolvedPath){n.warn("Skipped post-crawl copy source because alias root is not configured",{sourcePath:o,alias:l.alias||"",requiredEnv:l.requiredEnv||"",prefixPath:u});continue}let d=l.resolvedPath,p=Gt(u);if(!p){n.warn("Skipped post-crawl copy mapping with invalid export prefix",{sourcePath:o,prefixPath:u});continue}let g;try{g=await A.stat(d);}catch{n.warn("Skipped post-crawl copy source because it does not exist",{sourcePath:o,sourceAbs:d,prefixPath:u});continue}let f=S.resolve(e.outputDir,p);if(g.isDirectory()){let b=await Er(d,f,a,n);i.push(...b),r+=b.length,b.length>0&&n.progress(`Copied static directory to export: ${d} -> /${p}`,{phase:"copy-extra-paths",sourcePath:d,targetPath:`/${p}`,copiedItems:r,changedFiles:b.length});continue}let w=S.basename(d),m=u.endsWith("/")?S.join(f,w):f;await Mr(d,m,a,n)&&(i.push(m),r++,n.progress(`Copied static file to export: ${d} -> /${Gt(u.endsWith("/")?`${u}${w}`:u)}`,{phase:"copy-extra-paths",sourcePath:d,targetPath:`/${Gt(u.endsWith("/")?`${u}${w}`:u)}`,copiedItems:r}));}return n.endMark("copy-extra-paths",{mappedSources:s.length,copiedItems:r}),i}function Ye(e,t,n,s,r){let i=new Set,a=ce(n).replace(/\\\//g,"/"),c=r==="page-html"?Qi(a):a,o=Ji(t,r);if(o){for(let l of zi(c)){let d=W(e,l,t,s,`${r}:css-url`);d&&L(e,d)&&i.add(d.toString());}for(let l of c.matchAll(/@import\s+(?:url\()?\s*['"]?([^'"\s;]+)['"]?\s*\)?/gi)){let d=W(e,l[1],t,s,`${r}:css-import`);d&&L(e,d)&&i.add(d.toString());}}if(o||r==="page-html")for(let l of c.matchAll(/<\?xml-stylesheet[^>]+href=["']([^"']+)["'][^>]*\?>/gi)){let d=W(e,l[1],t,s,`${r}:xml-stylesheet`);d&&L(e,d)&&i.add(d.toString());}let u=new RegExp(`(?:https?:)?//[^\\s'"<>\\);]+\\.${Kt}(?:\\?[^\\s'"<>\\);]*)?|(?<!\\.)/[^\\s'"<>\\);]+\\.${Kt}(?:\\?[^\\s'"<>\\);]*)?`,"gi");if(r==="page-html")for(let l of a.matchAll(u)){let d=l[0].startsWith("//")?`${new URL(e.sourceOrigin).protocol}${l[0]}`:l[0];if(Xt(d)){s.ignore(`${r}:serialized-url`,d,"looks like JavaScript/code fragment",t);continue}let p=W(e,d,t,s,`${r}:serialized-url`);p&&L(e,p)?i.add(p.toString()):p&&s.ignore("asset",p.toString(),"serialized URL did not pass safe asset path filter",t);}if(r!=="page-html"&&qi(t))for(let l of sr(a)){if(Xt(l)||!/\.(?:js|mjs)(?:[?#]|$)/i.test(l))continue;let d=W(e,l,t,s,`${r}:relative-asset`);d&&L(e,d)&&i.add(d.toString());}return [...i]}function Gi(e,t,n,s){let r=new Set,i=ce(n);for(let a of i.matchAll(/href=["']([^"'#\s][^"']*?)["']/gi)){let c=a[1],o=W(e,c,t,s,"page-link");o&&(xr(e,o)||be(o)&&!je(o)&&!L(e,o)&&r.add(o.toString()));}return [...r]}async function gr(e,t,n,s,r,i,a=false){let c=new Map,o=(u,l)=>{let d=[l],p=new Set;for(;d.length>0;){let g=d.pop();if(g===u)return true;p.has(g)||(p.add(g),d.push(...c.get(g)??[]));}return false};for(;n.sitemapQueue.length>0;){let u=n.sitemapQueue.shift();n.queuedSitemaps.delete(u);let l=Pe(u,s,"sitemap","sitemap-queue");if(!l)continue;let d=l.toString();if(!n.doneSitemaps.has(d)){n.doneSitemaps.add(d),s.sitemap(`Fetching sitemap ${d}`,{url:d});try{let p=await t.get(d,{timeout:6e4});if(!p.ok()){if(s.skip("sitemap",d,p.status()),a)throw new Error(`Required content-sync sitemap returned HTTP ${p.status()}: ${d}`);continue}let g=await p.body(),f=p.url()||d,w=Pe(f,s,"sitemap-response",d);if(!w)continue;let m=w.toString(),h=await en(e,n.assetMap,m,g,n,s);Y(r,e,h.outputPath),Ie(r,h.outputPath);let b=g.toString("utf8");/<sitemapindex(?:\s|>)/i.test(b)?n.sitemapIndexUrls.add(m):n.sitemapLeafUrls.add(m);let k=Ye(e,m,b,s,"sitemap");for(let F of k)H(e,n,F,s,m);let M=[];for(let F of Wi(b)){let x=W(e,F.loc,m,s,"sitemap-loc");if(!x){if(a)throw new Error(`Content-sync sitemap contains an inadmissible location: ${F.loc}`);continue}if(Ue(x)){if(o(m,x.toString()))throw new Error(`Sitemap index cycle detected: ${m} -> ${x.toString()}`);c.has(m)||c.set(m,new Set),c.get(m).add(x.toString()),M.push(x.toString()),Pt(e,n,x.toString(),s,m);}else if(a){if(be(x)&&!L(e,x)){let j=i.requiredUrls.has(x.toString()),v=i.manifest.pages[x.toString()],P=!!v&&!!await De(v.outputPath);if(!j&&!P)throw new Error(`Content-sync sitemap coverage is incomplete for ${x.toString()}.`)}s.ignore("sitemap-loc",x.toString(),"content-sync sitemap-only traversal does not enqueue urlset locations",m);}else L(e,x)?H(e,n,x.toString(),s,m):be(x)?(F.lastmod&&(n.sitemapLastmodByPage[x.toString()]=F.lastmod),Ze(e,n,x.toString(),s,m)):s.reject("sitemap-loc",x.toString(),"not page/sitemap/asset-like",m);}i.trackManifest&&(i.manifest.assets[m]={url:m,outputPath:h.outputPath,isText:!0,contentType:p.headers()["content-type"]??"application/xml",changeToken:null,tokenSource:null,discoveredAssets:[...new Set([...k,...M])],lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!1},await Se(e,i));}catch(p){if(s.error(`Failed sitemap ${d}`,{url:d,error:String(p)}),a)throw p}}}}async function Zi(e,t,n,s,r,i,a){let c=W(e,s,e.sourceOrigin,r,"asset-fetch");if(!c||!L(e,c))return;let o=c.toString();if(n.doneAssets.has(o))return;let u=i.enabled||i.strictTargeted?i.previousManifest.assets[o]:void 0,l=i.trackManifest?await wt(e,t,i,o,r):null,d=l?.token??null,p=ir(u?.changeToken,l),g=i.strictTargeted&&(!l?.supported||!l.token)&&or(e.sourceOrigin,o),f=i.strictTargeted?i.manifest.assets[o]:void 0;if(f?.lastSeenRunId===i.runId&&await De(f.outputPath)){n.doneAssets.add(o);for(let m of f.discoveredAssets||[])H(e,n,m,r,o);Y(a,e,f.outputPath),f.isText&&Ie(a,f.outputPath),r.info(`Resumed completed content-sync asset ${o}`,{url:o,source:"content-sync-checkpoint"}),Fe(n,r);return}if(u&&(p||g)&&await De(u.outputPath)){i.manifest.assets[o]={...u,changeToken:d,tokenSource:l?.tokenSource??u.tokenSource,discoveredAssets:[...u.discoveredAssets||[]],lastSeenRunId:i.runId},delete i.manifest.pages[o],n.doneAssets.add(o);for(let m of u.discoveredAssets||[])H(e,n,m,r,o);r.info(`Reused unchanged trusted asset ${o}.`,{url:o,tokenSource:l?.tokenSource??"unknown",phase:"download-assets",source:p?"asset-change-token-match":"content-sync-release-fingerprint"}),Fe(n,r);return}let w=(m,h={})=>{if(!u||i.strictTargeted)return false;i.manifest.assets[o]={...u,discoveredAssets:[...u.discoveredAssets||[]],lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId},delete i.manifest.pages[o],n.doneAssets.add(o);for(let b of u.discoveredAssets||[])H(e,n,b,r,o);return r.warn(`Keeping previous incremental asset ${o} after fetch issue.`,{url:o,reason:m,preservedFromPreviousManifest:true,...h,phase:"download-assets"}),Fe(n,r),true};r.asset(`Fetching asset ${o}`,{url:o});try{let m=Oe(e,n.assetMap,o),h=m?await De(m):null;if(m&&h)try{let y=await N(`fetch asset headers ${o}`,6e4,()=>t.head(o,{timeout:6e4})),R=y.headers();if(y.ok()&&Ui(h,R)){let U=await kr(m);if(U!==null){let q=y.url()||o,Z=Pe(q,r,"asset-response",o);if(!Z)return;let V=Z.toString(),_=await en(e,n.assetMap,V,U,n,r,R);_.wroteFile&&(Y(a,e,_.outputPath),ye(_.outputPath)&&Ie(a,_.outputPath)),n.doneAssets.add(o),r.info(`Reused existing asset ${o} based on response headers.`,{url:o,filePath:m,lastModified:R["last-modified"]||"",contentLength:R["content-length"]||"",phase:"download-assets"}),Fe(n,r);let $=pr(c,R),ge=u?.discoveredAssets?[...u.discoveredAssets]:[];if($||u?.isText){let ve=U.toString("utf8"),et=Ye(e,V,ve,r,"asset:cached");(et.length>0||!u)&&(ge=et);for(let kt of ge)H(e,n,kt,r,V);}if(i.trackManifest){let ve=$||!!u?.isText;i.manifest.assets[o]={url:o,outputPath:_.outputPath,isText:ve,contentType:Zt(R)||u?.contentType||null,changeToken:l?.supported?l.token:null,tokenSource:l?.supported?l.tokenSource??null:null,discoveredAssets:ge,lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!ve},delete i.manifest.pages[o],(i.enabled||i.strictTargeted)&&ve&&await Se(e,i);}return}}}catch{}let b=await N(`fetch asset ${o}`,6e4,()=>t.get(o,{timeout:6e4}));if(!b.ok()){if(w(`http-${b.status()}`,{status:b.status()}))return;if(i.strictTargeted)throw new Error(`Required content-sync asset returned HTTP ${b.status()}: ${o}`);r.skip("asset",o,b.status());return}let k=await N(`read asset response ${o}`,6e4,()=>b.body()),M=b.url()||o,F=Pe(M,r,"asset-response",o);if(!F)return;let x=F.toString(),j=b.headers(),v=await en(e,n.assetMap,x,k,n,r,j);v.wroteFile&&(Y(a,e,v.outputPath),ye(v.outputPath)&&Ie(a,v.outputPath)),n.doneAssets.add(o),Fe(n,r);let P=pr(c,j),C=[];if(P){let y=k.toString("utf8");C=Ye(e,x,y,r,`asset:${S.extname(c.pathname).toLowerCase()||j["content-type"]||"unknown"}`);for(let R of C)H(e,n,R,r,x);}i.trackManifest&&(i.manifest.assets[o]={url:o,outputPath:v.outputPath,isText:P,contentType:Zt(j),changeToken:l?.supported?l.token:null,tokenSource:l?.supported?l.tokenSource??null:null,discoveredAssets:C,lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!P},delete i.manifest.pages[o],(i.enabled||i.strictTargeted)&&P&&await Se(e,i));}catch(m){if(w("fetch-error",{error:String(m)}))return;if(r.error(`Failed asset ${o}`,{url:o,error:String(m)}),i.strictTargeted)throw m}finally{n.doneAssets.has(o)||(n.doneAssets.add(o),Fe(n,r));}}async function Yi(e,t,n,s,r,i){let a=Math.max(1,Number(e.assetDownloadConcurrency||e.concurrency||1)),c=Array.from({length:a},async()=>{for(;n.assetQueue.length>0;){let o=n.assetQueue.shift();o&&(n.queuedAssets.delete(o),await Zi(e,t,n,o,s,r,i));}});await Promise.all(c);}function Xi(e){let t=Math.ceil(e/1e3);return `${t} second${t===1?"":"s"}`}function ue(e){return Math.max(6e4,e.navigationTimeoutMs*2,e.readiness.timeoutMs+e.readiness.fallbackWaitMs+15e3)}function yt(e){return Math.max(15e3,Math.min(6e4,ue(e)))}function eo(e){return Math.max(15e3,e.readiness.timeoutMs+e.readiness.fallbackWaitMs+1e4)}function an(e){return e.stats.pagesCompleted}function Fr(e){let n=e.options?.browserProcess;return {pid:typeof n?.process?.pid=="number"?n.process.pid:null,kill:typeof n?.kill=="function"?n.kill.bind(n):null}}async function to(e,t,n){let s=Fr(e);try{if(s.kill){await s.kill(),t.warn(`Force-killed crawl worker browser after ${n}`,{browserPid:s.pid,reason:n});return}if(s.pid!==null){process.kill(s.pid,"SIGKILL"),t.warn(`Sent SIGKILL to crawl worker browser after ${n}`,{browserPid:s.pid,reason:n});return}t.warn(`Could not resolve crawl worker browser PID after ${n}`,{reason:n});}catch(r){t.error(`Failed to force-kill crawl worker browser after ${n}`,{browserPid:s.pid,reason:n,error:String(r)});}}async function N(e,t,n){let s;try{return await Promise.race([n(),new Promise((r,i)=>{s=globalThis.setTimeout(()=>{i(new Error(`${e} timed out after ${Xi(t)}.`));},t);})])}finally{s!==void 0&&globalThis.clearTimeout(s);}}async function no(e,t){let n=eo(e);await t.evaluate(async s=>{await new Promise(r=>{let i=0,a=700,c=Date.now(),o=()=>{window.clearInterval(u),window.scrollTo(0,0),r();},u=window.setInterval(()=>{if(Date.now()-c>=s.maxDurationMs){o();return}window.scrollBy(0,a),i+=a;let l=document.body?.scrollHeight||0,d=document.documentElement?.scrollHeight||0,p=Math.max(l,d);i>=p+window.innerHeight&&o();},120);});},{maxDurationMs:n});}async function ro(e,t){await t.waitForLoadState("domcontentloaded",{timeout:e.readiness.timeoutMs}).catch(()=>{}),e.readiness.waitForSelector&&await t.waitForSelector(e.readiness.waitForSelector,{timeout:e.readiness.timeoutMs}).catch(()=>{}),e.readiness.waitForFunction&&await t.waitForFunction(e.readiness.waitForFunction,void 0,{timeout:e.readiness.timeoutMs}).catch(()=>{}),await no(e,t),await t.waitForTimeout(e.readiness.fallbackWaitMs);}async function so(e,t){await t.waitForLoadState("domcontentloaded",{timeout:e.readiness.timeoutMs}).catch(()=>{}),await t.waitForLoadState("load",{timeout:e.readiness.timeoutMs}).catch(()=>{}),e.readiness.waitForSelector&&await t.waitForSelector(e.readiness.waitForSelector,{timeout:e.readiness.timeoutMs}).catch(()=>{}),await t.waitForTimeout(e.readiness.fallbackWaitMs);}function io(e,t){return e.noJavaScriptRenderPathPrefixes.some(n=>rn(t,n))}async function oo(e,t,n,s,r=true){let i=new Set;if(r){let c=await t.evaluate(()=>{let o=new Set,u=["href","src","poster","data-src","data-lazy-src","data-original","data-bg","data-background","data-href"],l=new Set,d=["srcset","data-srcset","data-lazy-srcset"];return document.querySelectorAll("*").forEach(p=>{for(let f of u){let w=p.getAttribute(f);w&&o.add(w);}for(let f of d){let w=p.getAttribute(f);w&&w.split(",").forEach(m=>{let h=m.trim().split(/\s+/)[0];h&&o.add(h);});}let g=p.getAttribute("style");g&&l.add(g);}),{attrs:[...o],styles:[...l]}});for(let o of c.attrs)for(let u of Hi(o)){let l=W(e,u,n,s,"dom-attr");l&&L(e,l)&&i.add(l.toString());}for(let o of c.styles)for(let u of Ye(e,n,o,s,"dom-style"))i.add(u);}let a=await t.content();for(let c of Ye(e,n,a,s,"page-html"))i.add(c);return [...i]}async function fr(e,t,n,s,r){let i=le(e,t);await Ve(i,n,"utf8");let a=await A.stat(i);r?.debug(`Saved page output ${t}`,{phase:"save-pages",url:t,outputPath:i,bytes:a.size}),s.stats.pagesSaved++;let c=Math.min(s.stats.pagesQueued,an(s)+1);r&&(s.stats.pagesSaved%10===0||s.stats.pagesSaved===1)&&r.progress(`Page progress: processed ${c}, rendered ${s.stats.pagesRendered}, saved ${s.stats.pagesSaved}, discovered ${s.stats.pagesQueued}.`,{donePages:c,claimedPages:s.donePages.size,pagesRendered:s.stats.pagesRendered,pagesSaved:s.stats.pagesSaved,pagesQueued:s.stats.pagesQueued,pageQueue:s.pageQueue.length,phase:"save-pages"});}function ao(e){let t=an(e);return t%5===0||t===1||t===e.stats.pagesQueued}function co(e,t){let n=an(e);t.progress(`Render progress: processed ${n}, rendered ${e.stats.pagesRendered}, saved ${e.stats.pagesSaved}, discovered ${e.stats.pagesQueued}.`,{donePages:n,claimedPages:e.donePages.size,pagesRendered:e.stats.pagesRendered,pagesSaved:e.stats.pagesSaved,pagesQueued:e.stats.pagesQueued,phase:"render-pages"});}async function uo(e){await e.addInitScript(()=>{Object.defineProperty(window,"__WPSUITE_STATIC_EXPORT__",{value:true,writable:false,configurable:true});let t=n=>{if(n==null||String(n)==="")return true;try{let s=new URL(String(n),window.location.href),r=new URL(window.location.href);return s.hash="",r.hash="",s.href===r.href}catch{return false}};try{let n=window.location.assign.bind(window.location),s=window.location.replace.bind(window.location),r=window.location.reload.bind(window.location);Object.defineProperty(window.location,"assign",{configurable:!0,value:i=>{if(t(i)){console.warn("[smartcloud-static-publisher] blocked same-page location.assign",i??"");return}return n(i)}}),Object.defineProperty(window.location,"replace",{configurable:!0,value:i=>{if(t(i)){console.warn("[smartcloud-static-publisher] blocked same-page location.replace",i??"");return}return s(i)}}),Object.defineProperty(window.location,"reload",{configurable:!0,value:()=>{console.warn("[smartcloud-static-publisher] blocked location.reload");}});}catch{}});}async function lo(e,t,n){let s=await e.newContext({viewport:t.viewport,userAgent:"WPSuiteStaticPublisher/0.8 Playwright SitemapOnly",ignoreHTTPSErrors:t.ignoreHttpsErrors,...n?{javaScriptEnabled:false}:{}});return n||await uo(s),s}async function po(e,t,n,s,r,i,a){let c=await chromium.launch({headless:true}),o=Fr(c);o.pid!==null&&n.debug(`Launched crawl worker browser PID ${o.pid}`,{browserPid:o.pid});try{for(;t.pageQueue.length>0&&!(e.maxPages>0&&t.donePages.size>=e.maxPages);){let u=t.pageQueue.shift();if(!u)break;t.queuedPages.delete(u);let l=null,d=null;try{let p=Pe(u,n,"page","page-queue");if(!p)continue;let g=p.toString();if(u=g,t.queuedPages.delete(u),t.donePages.has(u))continue;t.donePages.add(u),i.enabled&&i.seenPages.add(u);let f=on(e,u),w=io(e,p.pathname);if(!be(p)||L(e,p)||je(p)){if(L(e,p)){n.info(`Worker redirected non-page URL to asset queue: ${u}`,{url:u,source:"worker-guard"}),H(e,t,u,n,"worker-guard");continue}n.reject("page",u,"guard rejected non-page URL before rendering","worker");continue}let m=i.strictTargeted?i.manifest.pages[u]:void 0;if(m?.lastSeenRunId===i.runId&&await De(m.outputPath)){i.seenPages.add(u);for(let y of m.discoveredAssets||[])H(e,t,y,n,u);Y(a,e,m.outputPath),Ie(a,m.outputPath),n.info(`Resumed completed content-sync page ${u}`,{url:u,source:"content-sync-checkpoint"});continue}let h=await mi(e,r,t,i,u,n);if(i.enabled&&s!=="single-url"&&s!=="content-sync"){let y=i.manifest.pages[u];if(h.action==="reuse"&&y){for(let R of y.discoveredAssets)H(e,t,R,n,u);for(let R of y.discoveredPages)Ze(e,t,R,n,u);y.lastSeenRunId=i.runId,y.sitemapLastmod=Ke(t.sitemapLastmodByPage[u])??y.sitemapLastmod,h.changeToken?.supported&&(y.changeToken=h.changeToken.token,y.tokenSource=h.changeToken.tokenSource??y.tokenSource),n.info(`Incremental reuse skipped unchanged page ${u}`,{url:u,mode:"incremental",reason:h.changeToken?.supported===!0?"change-token-match":"sitemap-lastmod-match"});continue}}l=await N(`create page context ${u}`,ue(e),()=>lo(c,e,w)),d=await N(`create page ${u}`,ue(e),()=>l.newPage());let b=!1,k=new Set;await d.route("**/*",async y=>{let R=y.request();if(R.isNavigationRequest()&&R.frame()===d.mainFrame())try{let U=new URL(R.url()),q=new URL(g);if(U.hash="",q.hash="",U.href===q.href){if(b){n.warn(`Blocked same-page navigation/reload for ${u}`,{url:u,requestUrl:R.url()}),await y.abort("aborted");return}b=!0;}}catch{}await y.continue();}),d.on("response",y=>{try{let R=W(e,y.url(),e.sourceOrigin,n,"network-response");R&&L(e,R)&&(k.add(R.toString()),H(e,t,R.toString(),n,u));}catch{}}),n.page(`Rendering ${u}`,{url:u});let M=null,F=null;try{if(M=await d.goto(u,{waitUntil:"domcontentloaded",timeout:e.navigationTimeoutMs}),M&&M.ok())try{F=await N(`read response body ${u}`,ue(e),()=>M.text());}catch{F=null;}}catch(y){n.warn(`Navigation issue for ${u}; saving current DOM if available`,{url:u,error:String(y)});}if(s==="content-sync"&&M){let y=Pe(M.url(),n,"content-sync-final-response",u)?.toString();if(y&&y!==g){if(i.deleteOnMissingUrls.has(u)){await tn(e,i,a,u,i.deleteOnMissingUrls),n.info(`Removed stale content-sync archive route redirected to ${y}`,{url:u,finalResponseUrl:y,source:"content-sync-tombstone"});continue}throw new Error(`Required content-sync route redirected outside its planned URL: ${u} -> ${y}`)}}if(f){let y=M?.status()??null;if(y!==404){n.error(`Generated 404 request path returned unexpected status for ${u}`,{url:u,expectedStatus:404,status:y,requestPath:e.generated404RequestPath});continue}n.info(`Capturing rendered 404 page for ${u}`,{url:u,status:y,outputPath:le(e,u)});}else if(M&&!M.ok()){if(s==="content-sync"&&(M.status()===404||M.status()===410)&&i.deleteOnMissingUrls.has(u)){await tn(e,i,a,u,i.deleteOnMissingUrls),n.info(`Removed stale content-sync archive page ${u}`,{url:u,status:M.status(),source:"content-sync-tombstone"}),await d.close();continue}if(s==="content-sync")throw new Error(`Required content-sync route returned HTTP ${M.status()}: ${u}`);n.skip("page",u,M.status(),t.pageDiscoverySources.get(u)),await d.close();continue}w?(n.info(`Rendering without JS execution for ${u}`,{url:u,mode:"no-js"}),await N(`wait for rendered page ${u}`,ue(e),()=>so(e,d))):await N(`wait for rendered page ${u}`,ue(e),()=>ro(e,d)),t.stats.pagesRendered++;let x=await N(`extract rendered assets ${u}`,ue(e),()=>oo(e,d,g,n,!w));for(let y of x)H(e,t,y,n,u);let j=[...new Set([...x,...k])],v=F??await N(`capture rendered html ${u}`,ue(e),()=>d.content()),P=s!=="single-url"&&s!=="content-sync"&&!f?Gi(e,u,v,n):[];if(s!=="single-url"&&s!=="content-sync"&&!f)for(let y of P)Ze(e,t,y,n,u);await fr(e,u,v,t,n);let C=le(e,u);if(Y(a,e,C),Ie(a,C),i.trackManifest){let y=M?.headers();i.manifest.pages[u]={url:u,outputPath:C,contentType:Zt(y),changeToken:h.changeToken?.supported?h.changeToken.token:null,tokenSource:h.changeToken?.supported?h.changeToken.tokenSource??null:null,sitemapLastmod:Ke(t.sitemapLastmodByPage[u])??null,discoveredPages:P,discoveredAssets:j,lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!1},(i.enabled||i.strictTargeted)&&await Se(e,i);}}catch(p){if(i.strictTargeted)throw n.error(`Failed required content-sync page ${u}`,{url:u,error:String(p)}),p;try{let g=d?await N(`capture partial html ${u}`,ue(e),()=>d.content()):"";if(g&&g.trim()){await fr(e,u,g,t,n);let f=le(e,u);if(Y(a,e,f),Ie(a,f),i.trackManifest){let w=i.manifest.pages[u]??i.previousManifest.pages[u];i.manifest.pages[u]={url:u,outputPath:f,contentType:w?.contentType??null,changeToken:null,tokenSource:null,sitemapLastmod:Ke(t.sitemapLastmodByPage[u])??w?.sitemapLastmod??null,discoveredPages:w?.discoveredPages?[...w.discoveredPages]:[],discoveredAssets:w?.discoveredAssets?[...w.discoveredAssets]:[],lastCrawledAt:new Date().toISOString(),lastSeenRunId:i.runId,rewriteComplete:!1},(i.enabled||i.strictTargeted)&&await Se(e,i);}n.warn(`Saved partial DOM for ${u}`,{url:u,error:String(p)});}}catch(g){n.error(`Could not save partial DOM for ${u}`,{url:u,error:String(g)});}n.error(`Failed page ${u}`,{url:u,error:String(p)});}finally{t.stats.pagesCompleted++,ao(t)&&co(t,n),d&&await N(`close page ${u}`,yt(e),()=>d.close()).catch(p=>{n.warn(`Timed out while closing page ${u}`,{url:u,browserPid:o.pid,error:String(p)});}),l&&await N(`close page context ${u}`,yt(e),()=>l.close()).catch(p=>{n.warn(`Timed out while closing page context for ${u}`,{url:u,browserPid:o.pid,error:String(p)});});}}}finally{await N("close worker browser",yt(e),()=>c.close()).catch(u=>(n.warn("Timed out while closing crawl worker browser",{browserPid:o.pid,error:String(u)}),to(c,n,"browser.close timeout")));}}async function go(e){try{let t=await A.readFile(e),s=(e.endsWith(".gz")?gunzipSync(t):t).toString("utf8").trim();if(!s)return [];try{let r=JSON.parse(s);if(Array.isArray(r))return r;if(r&&typeof r=="object")return [r]}catch{return s.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).map(r=>{try{let i=JSON.parse(r);return i&&typeof i=="object"?i:null}catch{return null}}).filter(r=>r!==null)}return []}catch{return []}}function mr(e){let t=String(e||"").toLowerCase();return t.includes("timeout")||t.includes("timed out")||t.includes("navigation timeout")}function fo(e){let t=String(e?.job?.command||"").trim(),n=String(e?.job?.crawlMode||"full").trim();return t!=="publish"&&t!=="crawl"?false:n!=="incremental"}function mo(e){let t=[e?.archivedAt,e?.job?.endedAt,e?.job?.startedAt];for(let n of t){let s=Date.parse(String(n||""));if(Number.isFinite(s))return s}return 0}async function Dr(e){try{let t=await A.readFile(e,"utf8"),n=JSON.parse(t);return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function hr(e){let t=String(e.originalFileName||"").toLowerCase();return t.endsWith("errors.jsonl")?0:t.endsWith("errors.json")?1:2}function ho(e,t){let n=Array.isArray(t?.artifacts)?t.artifacts.filter(s=>String(s?.role||"").trim()==="errors"&&String(s?.storedFileName||"").trim()!=="").sort((s,r)=>hr(s)-hr(r)).map(s=>S.join(e,String(s.storedFileName))):[];return [...new Set([...n,S.join(e,"errors.jsonl"),S.join(e,"errors.json"),S.join(e,"errors.jsonl.gz"),S.join(e,"errors.json.gz")])]}async function wr(e){let t=await Dr(S.join(e,"job.json"));for(let n of ho(e,t)){let s=await go(n);if(s.length>0)return s}return []}async function wo(e){let t=S.join(e.logDir,"archive"),n;try{n=await A.readdir(t);}catch{return ""}let s="",r=0;for(let i of n){let a=S.join(t,i);if(!(await A.stat(a).catch(()=>null))?.isDirectory())continue;let o=await Dr(S.join(a,"job.json"));if(!fo(o))continue;let u=mo(o);u>=r&&(r=u,s=a);}return s}async function yo(e){let t=await wo(e),n=t!==""?await wr(t):await wr(e.logDir),s=new Set;for(let r of n)if(mr(r.error)||mr(r.message)){let i=r.url;typeof i=="string"&&i&&s.add(i);}return [...s]}async function So(e){let t=[];for(let n of e)if(n.startsWith("@")){let s=n.slice(1),r=await A.readFile(s,"utf8");t.push(...r.split(/\r?\n/).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")));}else t.push(n);return t}async function Po(e){if(!e)throw new Error("Content-sync crawl requires an immutable impact plan.");let t=JSON.parse(await A.readFile(e,"utf8"));return He(t),t}function bo(e,t){let n;try{n=new URL(e);}catch{return false}return t.archiveFamilies.some(s=>{let r=new URL(s.url);if(n.origin!==r.origin)return false;if(n.toString()===r.toString())return true;if(n.searchParams.has("paged")&&n.pathname===r.pathname)return /^\d+$/.test(n.searchParams.get("paged")||"");let i=r.pathname.replace(/\/+$/,""),a=n.pathname.slice(i.length).replace(/^\/+/,""),c=String(s.paginationBase||"page").replace(/^\/+|\/+$/g,"").replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return n.pathname.startsWith(`${i}/`)&&new RegExp(`^${c}/\\d+/?$`).test(a)})}function ht(e,t,n){let s=n==="page"?le(e,t):bt(e,t).originalFilePath;return we(e.outputDir,s)}async function tn(e,t,n,s,r){let i=t.manifest.pages[s];if(!i)return;let a=we(e.outputDir,i.outputPath);if(!a)throw new Error(`Manifest-owned page path escaped output root: ${s}`);let c=S.resolve(i.outputPath);Object.entries(t.manifest.pages).some(([u,l])=>u!==s&&!r.has(u)&&S.resolve(l.outputPath)===c)||(await A.rm(i.outputPath,{force:true}),n.deletedFiles.add(a)),delete t.manifest.pages[s];}function vo(e,t){let n=new Set,s=[...t];for(;s.length>0;){let r=s.shift();if(n.has(r))continue;n.add(r);let i=e.assets[r];for(let a of i?.discoveredAssets??[])try{Ue(new URL(a))&&s.push(a);}catch{}}return n}async function Co(e,t,n,s,r){let i=vo(n.previousManifest,r);for(let a of i){if(t.doneSitemaps.has(a))continue;let c=n.previousManifest.assets[a];if(!c)continue;let o=we(e.outputDir,c.outputPath);if(!o)throw new Error(`Manifest-owned sitemap path escaped output root: ${a}`);await A.rm(c.outputPath,{force:true}),s.deletedFiles.add(o),delete n.manifest.assets[a];}await Se(e,n);}async function Ro(e){try{let t=await A.readFile(S.join(e.outputDir,"asset-map.json"),"utf8");return JSON.parse(t)}catch{return {}}}async function Io(e){let t=["crawl.log.jsonl","current-crawl-event.json","rejected.jsonl","ignored.jsonl","skipped-http.jsonl","errors.jsonl","timings.jsonl","rejected.json","ignored.json","skipped-http.json","errors.json","timings.json"];await A.mkdir(e,{recursive:true}),await Promise.all(t.map(async n=>{try{await A.unlink(S.join(e,n));}catch(s){if(s.code!=="ENOENT")throw s}}));}function yr(e,t,n,s,r){let i=W(e,n,e.sourceOrigin,s,"manual-url");i&&(Ue(i)?Pt(e,t,i.toString(),s,r):L(e,i)?H(e,t,i.toString(),s,r):be(i)?Ze(e,t,i.toString(),s,r):s.reject("manual-url",i.toString(),"not page/sitemap/asset-like",r));}async function Or(e=process.argv.slice(2)){let t=[],n=await ne(void 0,{onRemotePublisherConfigDiagnostic:P=>{t.push(P);}}),s=t.at(-1)??null,r=ri(e),i=r.mode==="content-sync"?await Po(r.contentSyncPlanPath):null;if(r.resumeRewrite&&r.mode!=="full")throw new Error("--resume-rewrite is only supported for full crawl/publish jobs.");let a=[];r.mode==="retry-timeouts"&&(a=await yo(n)),r.mode==="single-url"&&(a=await So(r.urls)),i&&(a=[...i.directRenderUrls,...i.archiveFamilyUrls]);let c=r.crawlMode==="incremental"&&r.mode==="full",o=c&&typeof n.subscriptionType=="string"&&n.subscriptionType.trim()!=="";if(i&&n.subscriptionType!=="PROFESSIONAL"&&n.subscriptionType!=="AGENCY")throw new Error("Content-sync requires an active Professional or Agency subscription.");let u=(r.mode==="full"||r.mode==="single-url"||r.mode==="content-sync")&&!r.resumeRewrite,l=r.mode!=="full"||r.resumeRewrite||o,d=l?await Ro(n):{},p=o||r.mode==="single-url"||r.mode==="content-sync"?await ui(n):vr(),g=new Set(a),f=new Set;if(i){for(let P of i.archiveFamilies)if(P.foundPosts===0)for(let C of P.pageUrls)f.add(C);for(let P of Object.keys(p.pages))bo(P,i)&&!g.has(P)&&(a.push(P),f.add(P));}let w={enabled:o,trackManifest:u,manifest:Yt(p),previousManifest:Yt(p),runId:i?.jobId??`${Date.now()}`,seenPages:new Set,changeTokenCache:new Map,manifestSaveChain:Promise.resolve(),strictTargeted:!!i,requiredUrls:g,deleteOnMissingUrls:f};await Io(n.logDir);let m=new gt(n.logDir,n.logLevel);if(s){let P={status:s.status,virtualAssetBaseUrl:s.virtualAssetBaseUrl,subscriptionType:s.subscriptionType??null,error:s.error,requests:s.requests,source:"remote-publisher-config"};s.status==="loaded"&&s.subscriptionType?m.info("Loaded remote WP Suite publisher configuration.",P):m.warn("Remote WP Suite publisher configuration is unavailable or has no active subscription type.",P);}if(c&&!o){let P="Incremental crawl requires an active remote publisher subscription; refusing to fall back to a destructive full crawl.";throw m.error(P,{requestedMode:r.crawlMode,subscriptionType:n.subscriptionType??null,source:"incremental-subscription-guard"}),await m.flush(),new Error(P)}let h={pageQueue:[],queuedPages:new Set,donePages:new Set,pageDiscoverySources:new Map,assetQueue:[],queuedAssets:new Set,doneAssets:new Set,sitemapQueue:[],queuedSitemaps:new Set,doneSitemaps:new Set,sitemapIndexUrls:new Set,sitemapLeafUrls:new Set,sitemapLastmodByPage:{},assetMap:{...d},assetVariantDigestsByOriginalPath:new Map,stats:{pagesQueued:0,pagesRendered:0,pagesCompleted:0,assetsQueued:0,sitemapsQueued:0,assetsSaved:0,pagesSaved:0}},b=ci();if(await $e(n),await Wn(n,{startedAt:new Date().toISOString(),outputDir:S.resolve(n.outputDir)}),l||await A.rm(n.outputDir,{recursive:true,force:true}),await A.mkdir(n.outputDir,{recursive:true}),i){let P=new Set([...i.deleteUrls,...w.deleteOnMissingUrls]);for(let C of i.deleteUrls)await tn(n,w,b,C,P);}if(r.resumeRewrite)m.info("Resuming final rewrite from existing output.",{phase:"rewrite-text",mode:r.mode,crawlMode:r.crawlMode});else {let P=await request.newContext({ignoreHTTPSErrors:n.ignoreHttpsErrors});try{if(m.mark("discovery"),r.mode==="full"?(n.sitemapPaths.forEach(y=>Pt(n,h,y,m)),await gr(n,P,h,m,b,w),n.seedPaths.forEach(y=>yr(n,h,y,m,"seed-path")),n.generated404RequestPath&&Ze(n,h,n.generated404RequestPath,m,"generated-404-request-path")):(a.forEach(y=>yr(n,h,y,m,"cli")),i?.sitemapUrls.forEach(y=>Pt(n,h,y,m,"content-sync-impact")),await gr(n,P,h,m,b,w,r.mode==="content-sync"),i&&await Co(n,h,w,b,i.sitemapUrls)),m.endMark("discovery",{pages:h.pageQueue.length,assets:h.assetQueue.length,sitemaps:h.sitemapQueue.length}),m.summary(`Queued ${h.pageQueue.length} pages, ${h.assetQueue.length} assets, ${h.sitemapQueue.length} sitemaps.`,{mode:r.mode,crawlMode:r.crawlMode,queuedPages:h.pageQueue.length,queuedAssets:h.assetQueue.length,queuedSitemaps:h.sitemapQueue.length}),r.mode==="retry-timeouts"&&h.pageQueue.length===0&&h.assetQueue.length===0&&h.sitemapQueue.length===0){m.summary("No timed-out URLs were queued. Skipping retry crawl.",{mode:r.mode,crawlMode:r.crawlMode,queuedPages:0,queuedAssets:0,queuedSitemaps:0}),await m.flush();return}m.mark("render-pages");let C=Array.from({length:Math.max(1,n.concurrency)},()=>po(n,h,m,r.mode,P,w,b));if(await Promise.all(C),m.endMark("render-pages",{pages:h.stats.pagesCompleted}),m.mark("download-assets"),m.progress("Asset download phase started.",{phase:"download-assets",doneAssets:h.doneAssets.size,assetsQueued:h.stats.assetsQueued,assetQueue:h.assetQueue.length}),await pi(n,P,w,[...h.assetQueue],m),await Yi(n,P,h,m,w,b),m.endMark("download-assets",{assets:h.doneAssets.size}),w.enabled&&n.maxPages===0&&await wi(n,h,w,m,b),r.mode==="full"){let y=await Ki(n,h,m);for(let R of y)Y(b,n,R);}}finally{await N("dispose crawl request context",yt(n),()=>P.dispose()).catch(C=>{m.warn("Timed out while disposing crawl request context",{error:String(C)});});}}w.trackManifest&&await Se(n,w),await A.writeFile(S.join(n.outputDir,"asset-map.json"),JSON.stringify(h.assetMap,null,2),"utf8"),JSON.stringify(d,null,2)!==JSON.stringify(h.assetMap,null,2)&&Y(b,n,S.join(n.outputDir,"asset-map.json"));let k=r.mode==="single-url"||r.mode==="content-sync"?xi(n,h):w.enabled&&!r.resumeRewrite?yi(n,w,b,d,h.assetMap):void 0;m.mark("rewrite-text");let M=r.mode==="single-url"||r.mode==="content-sync"?`Rewriting text files touched by URL crawl: 0/${k?.length??0}`:"Rewriting text files...";m.progress(M,{phase:"rewrite-text",index:0,totalFiles:k?.length,changedTextFiles:0}),await dr(M);let F=Date.now(),x=await lt(n,h.assetMap,{files:k,previousAssetMap:d,onStart:({totalFiles:P,workerCount:C})=>{m.info(`Rewrite phase scanning ${P} text files.`,{phase:"rewrite-text",totalFiles:P,workerCount:C});},onProgress:async({index:P,totalFiles:C,changedTextFiles:y,file:R,changed:U})=>{U&&Y(b,n,S.join(n.outputDir,R)),m.checkpoint(`Rewriting text file ${P}/${C}`,{phase:"rewrite-text",index:P,totalFiles:C,changedTextFiles:y,file:R}),m.debug(`${U?"Rewrote":"Checked unchanged"} text file ${P}/${C}: ${R}`,{phase:"rewrite-text",index:P,totalFiles:C,changedTextFiles:y,file:R,changed:U});let q=Date.now();if(!(P===1||P===C||P%50===0||q-F>=5e3))return;F=q;let V=`Rewriting text files: ${P}/${C}`;m.progress(V,{phase:"rewrite-text",index:P,totalFiles:C,changedTextFiles:y,file:R}),await dr(V);}});w.trackManifest&&(Si(w,k),await Se(n,w)),m.endMark("rewrite-text",{changedTextFiles:x});let j=i?[...b.deletedFiles].sort():w.enabled&&!r.resumeRewrite?await bi(n,h,w,b,m):[],v=[...new Set((k||[]).map(P=>we(n.outputDir,S.isAbsolute(P)?P:S.join(n.outputDir,P))).filter(P=>P!==null))].sort();if(i){let P=[...b.changedFiles].sort(),C=new Set(P),y=new Set(i.directRenderUrls.map($=>ht(n,$,"page")).filter($=>!!$&&C.has($))),R=new Set(i.archiveFamilyUrls.map($=>ht(n,$,"page")).filter($=>!!$&&C.has($))),U=new Set([...h.sitemapLeafUrls].map($=>ht(n,$,"asset")).filter($=>!!$&&C.has($))),q=new Set([...h.sitemapIndexUrls].map($=>ht(n,$,"asset")).filter($=>!!$&&C.has($))),Z=new Set([...y,...R,...U,...q]),V=P.filter($=>!Z.has($)),_=[...new Set([...i.directRenderUrls,...i.archiveFamilyUrls,...i.sitemapUrls,...h.sitemapLeafUrls,...h.sitemapIndexUrls,...i.deleteUrls].map($=>{let ge=new URL($);return `${ge.pathname}${ge.search}`}))].sort();await Ht(n,{schemaVersion:2,generatedAt:new Date().toISOString(),outputDir:S.resolve(n.outputDir),runMode:"content-sync",crawlMode:"incremental",fullSyncRequired:false,changedFiles:P,deletedFiles:j,rewriteTargets:v,consumerId:i.consumerId,fromSequence:i.fromSequence,toSequence:i.toSequence,impactHash:i.impactHash,uploadGroups:{assets:V,content:[...y].sort(),listings:[...R].sort(),sitemapLeaves:[...U].sort(),sitemapIndexes:[...q].reverse()},invalidationPaths:_});}else await Ht(n,{schemaVersion:1,generatedAt:new Date().toISOString(),outputDir:S.resolve(n.outputDir),runMode:r.mode,crawlMode:r.crawlMode,fullSyncRequired:!(w.enabled&&!r.resumeRewrite),changedFiles:w.enabled&&!r.resumeRewrite?[...b.changedFiles].sort():[],deletedFiles:w.enabled&&!r.resumeRewrite?j:[],rewriteTargets:w.enabled&&!r.resumeRewrite?v:[]});await zn(n),m.summary(r.resumeRewrite?`Done. Resumed final rewrite over existing output and changed ${x} text files.`:`Done. Rendered ${h.stats.pagesRendered} pages, processed ${h.doneSitemaps.size} sitemaps and ${h.doneAssets.size} assets.`,{mode:r.mode,crawlMode:r.crawlMode,resumeRewrite:r.resumeRewrite,...h.stats,pagesRendered:h.stats.pagesRendered,donePages:h.stats.pagesCompleted,claimedPages:h.donePages.size,doneSitemaps:h.doneSitemaps.size,doneAssets:h.doneAssets.size,changedTextFiles:x}),await m.flush();}function xo(e){let t=e/6e4;if(Number.isInteger(t)&&t>=1)return `${t} minute${t===1?"":"s"}`;let n=Math.ceil(e/1e3);return `${n} second${n===1?"":"s"}`}async function X(e,t,n){let s=new AbortController,r=globalThis.setTimeout(()=>{s.abort(new Error(`${e} timed out after ${xo(t)}.`));},t);try{return await n({abortController:s,httpOptions:{abortSignal:s.signal,requestTimeout:t}})}finally{globalThis.clearTimeout(r);}}function Ao(e){return typeof e.subscriptionType=="string"&&e.subscriptionType.trim()!==""}function vt(e){let t="";for(let s=0;s<e.length;s++){let r=e[s];if(r==="--profile"){let i=(e[s+1]||"").trim();if(!i)throw new Error("Missing value for --profile.");t=i,s+=1;}else if(r.startsWith("--profile=")){let i=r.slice(10).trim();if(!i)throw new Error("Missing value for --profile.");t=i;}}let n=String(process.env.PUBLISHER_DEPLOY_PROFILE||process.env.PUBLISHER_DEPLOYMENT_PROFILE||"").trim();return t||n||null}function To(e,t){return {...e,...t??{}}}function ko(e,t){return {...e,...t??{},invalidationPaths:[...(t?.invalidationPaths??e.invalidationPaths)||[]]}}function Le(e,t){let n=String(t??e.deploymentTargetOverride??"").trim();if(!Ao(e)){if(n)throw new Error(`Deployment target "${n}" requires an active WPSuite subscription and remote publisher config.`);return {name:null,profile:null,config:e}}let s=String(n||e.defaultDeploymentProfile||"").trim();if(!s)return {name:null,profile:null,config:e};let r=e.deploymentProfiles?.[s];if(!r)throw new Error(`Unknown deployment profile "${s}". Check the linked WPSuite publisher configuration.`);return {name:s,profile:r,config:{...e,targetOrigin:r.targetOrigin??e.targetOrigin,s3:To(e.s3,r.s3),cloudFront:ko(e.cloudFront,r.cloudFront)}}}var qr="wpsuite-sha256",_r="wpsuite-normalized-sha256",Lo=/(?:^|[-_:.])(id|uid|nonce|token|hash|instance)(?:$|[-_:.])/i,gn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,qo=["SIGINT","SIGTERM"],It=new Set,Ct=new Map,jr=null;function _o(e){It.add(e);let t=false;return ()=>{t||(t=true,It.delete(e));}}async function No(){let e=[...It];e.length!==0&&await Promise.allSettled(e.map(async t=>{It.delete(t),await A.rm(t,{recursive:true,force:true});}));}function Bo(){if(!(Ct.size>0))for(let e of qo){let t=()=>{jr||(jr=No().finally(()=>{for(let[n,s]of Ct)process.off(n,s);Ct.clear(),process.exit(1);}));};Ct.set(e,t),process.on(e,t);}}Bo();function Wo(e,t){let n=String(process.env.STATIC_PUBLISHER_CRAWL_MANIFEST_PATH||"").trim();if(n)return S.resolve(n);let s=t.trim();return s?S.join(S.resolve(s),"crawl-manifest.json"):S.join(S.resolve(e),".crawl-manifest.json")}function Nr(e){return S.normalize(e).split(S.sep).join("/")}function Ur(e,t){let n=S.relative(S.resolve(e),S.resolve(t));return !n||n.startsWith("..")||S.isAbsolute(n)?null:Nr(n)}async function Ho(e,t,n){let s=Wo(e.outputDir,t),r;try{r=await A.readFile(s,"utf8");}catch(l){return l.code==="ENOENT"?(n.warn("Deploy rewrite guard disabled because the crawl manifest is missing.",{manifestPath:s,source:"deploy-guard"}),null):(n.warn("Deploy rewrite guard disabled because the crawl manifest could not be read.",{manifestPath:s,error:l instanceof Error?l.message:String(l),source:"deploy-guard"}),null)}let i;try{i=JSON.parse(r);}catch(l){return n.warn("Deploy rewrite guard disabled because the crawl manifest is invalid JSON.",{manifestPath:s,error:l instanceof Error?l.message:String(l),source:"deploy-guard"}),null}let a=new Map,c=new Map,o=0,u=0;for(let[l,d]of Object.entries(i.pages||{})){let p=String(d?.outputPath||"").trim(),g=p?Ur(e.outputDir,p):null;if(g){let f=typeof d?.contentType=="string"&&d.contentType?d.contentType:null;f&&c.set(g,f);}!p||d?.rewriteComplete===true||g&&(o++,a.has(g)||a.set(g,{kind:"page",sourceUrl:l,outputPath:S.resolve(p),relativePath:g}));}for(let[l,d]of Object.entries(i.assets||{})){let p=String(d?.outputPath||"").trim(),g=d?.isText===true,f=p?Ur(e.outputDir,p):null;if(f){let w=typeof d?.contentType=="string"&&d.contentType?d.contentType:null;w&&c.set(f,w);}!p||!g||d?.rewriteComplete===true||f&&(u++,a.has(f)||a.set(f,{kind:"asset",sourceUrl:l,outputPath:S.resolve(p),relativePath:f}));}return {manifestPath:s,byRelativePath:a,contentTypeByRelativePath:c,pendingPages:o,pendingTextAssets:u}}function zo(e){return e&&(gn.test(e)?"__uuid__":/^[0-9a-f]{6,}$/i.test(e)?"__hex__":/^[0-9]{8,}$/.test(e)?"__num__":/^(?=.*[a-z])(?=.*\d)[a-z0-9]{8,}$/i.test(e)?"__alnum__":e)}function un(e){return e.split(/([_:.\-/=?&#]+)/g).map((t,n)=>n%2===1?t:zo(t)).join("")}function Qo(e){return e.split(/([_:.\-/=?&#]+)/g).map((t,n)=>n%2===1?t:gn.test(t)?"__uuid__":/^[0-9a-f]{6,}$/i.test(t)?"__hex__":/^[0-9]{6,}$/.test(t)?"__num__":/^[a-z0-9_-]{6,}$/i.test(t)?"__id__":t).join("")}function xt(e,t){return Array.isArray(e)?e.map(n=>xt(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,s])=>[n,xt(s,n)])):typeof e!="string"?e:t&&Lo.test(t)?Qo(e):gn.test(e)?"__uuid__":/^[0-9a-f]{6,}$/i.test(e)||/^[0-9]{8,}$/.test(e)?un(e):e}function Jo(e){return e.replace(/((?:https?:\/\/[^"'\s>]+|\/)(?:wp-content|wp-includes)\/[^"'\s>?]+)\?ver=[A-Za-z0-9._-]+(?=$|[#"'])/gi,"$1")}function Vo(e,t){let n=t.trim();if((n.startsWith("{")||n.startsWith("[")||n.startsWith('"'))&&e.startsWith("data-"))try{let r=JSON.parse(n);return JSON.stringify(xt(r))}catch{}if(e.startsWith("data-")&&/^[A-Za-z0-9+/=]+$/.test(n))try{let r=Buffer.from(n,"base64").toString("utf8"),i=JSON.parse(r),a=JSON.stringify(xt(i));return Buffer.from(a,"utf8").toString("base64")}catch{}return t}function Ko(e,t){let n=e.toLowerCase();return n==="class"?t.split(/(\s+)/).map((s,r)=>r%2===1?s:un(s)).join(""):n==="id"||n==="for"||n==="aria-controls"||n==="aria-labelledby"||n==="aria-describedby"||n==="aria-owns"||n==="aria-activedescendant"||n==="name"?un(t):n==="href"||n==="src"?Jo(t):Vo(n,t)}function Go(e){return e.replace(/<([a-z][^\s/>]*)([^<>]*?)>/gi,(t,n,s)=>{if(n.startsWith("/"))return t;let r=s.replace(/\s([:@a-zA-Z_][-:.a-zA-Z0-9_]*?)=(['"])([\s\S]*?)\2/g,(i,a,c,o)=>{let u=Ko(a,o);return ` ${a}=${c}${u}${c}`});return `<${n}${r}>`})}function cn(e){let t=S.extname(e).toLowerCase();return [".html",".htm",".xml",".xsl",".txt"].includes(t)||["robots.txt","sitemap.xml"].includes(S.basename(e))}function Rt(e,t){return [e.replace(/^\/+|\/+$/g,""),t.replace(/^\/+/,"")].filter(Boolean).join("/")}async function Zo(e,t,n,s){let r=new Map,i,a=0;do{a++;let c=await X(`S3 list objects page ${a} for s3://${t}/${n||""}`,3e5,({httpOptions:o})=>e.send(new ListObjectsV2Command({Bucket:t,Prefix:n||void 0,ContinuationToken:i}),o));for(let o of c.Contents||[]){if(!o.Key)continue;let u=(o.ETag||"").replace(/^"|"$/g,"").toLowerCase(),l=Number(o.Size??0);r.set(o.Key,{etag:u,size:l});}i=c.NextContinuationToken,s.debug(`Listed S3 keys page ${a}: ${r.size} keys so far`);}while(i);return r}async function Yo(e,t,n,s){if(s.has(n))return s.get(n)??null;try{let r=await X(`S3 head object ${n}`,3e5,({httpOptions:a})=>e.send(new HeadObjectCommand({Bucket:t,Key:n}),a)),i={etag:(r.ETag||"").replace(/^"|"$/g,"").toLowerCase(),size:Number(r.ContentLength??0)};return s.set(n,i),i}catch{return s.set(n,null),null}}async function Xo(e,t,n,s){let r=[...new Set(Array.from(n).filter(Boolean))];if(r.length===0)return s.info("No explicitly tombstoned S3 objects to delete."),[];s.info(`Deleting ${r.length} explicitly tombstoned S3 object(s)\u2026`);for(let i=0;i<r.length;i+=1e3){let a=r.slice(i,i+1e3);if(a.length===0)continue;let c=await X(`S3 delete objects batch ${Math.floor(i/1e3)+1}`,3e5,({httpOptions:o})=>e.send(new DeleteObjectsCommand({Bucket:t,Delete:{Objects:a.map(u=>({Key:u}))}}),o));if(c.Errors&&c.Errors.length>0){let o=c.Errors.map(u=>`${u.Key||"(unknown)"}: ${u.Code||"DeleteFailed"}`);throw new Error(`S3 reported ${o.length} object deletion error(s): ${o.join(", ")}`)}s.info(`Deleted batch of ${a.length} object(s).`);for(let o of a)s.debug(` deleted: ${o}`);}return r}function ea(e){return createHash("md5").update(e).digest("hex")}function Lr(e){return createHash("sha256").update(e).digest("hex")}function ln(e){return createHash("sha256").update(Go(e.toString("utf8"))).digest("hex")}async function ta(e,t,n,s){if(s.has(n))return s.get(n)??null;try{let a=((await X(`S3 head object metadata ${n}`,3e5,({httpOptions:c})=>e.send(new HeadObjectCommand({Bucket:t,Key:n}),c))).Metadata?.[qr]||"").trim().toLowerCase()||null;return s.set(n,a),a}catch{return s.set(n,null),null}}async function na(e,t,n,s,r){if(s.has(n))return s.get(n)??null;try{let a=((await X(`S3 head object normalized metadata ${n}`,3e5,({httpOptions:c})=>e.send(new HeadObjectCommand({Bucket:t,Key:n}),c))).Metadata?.[_r]||"").trim().toLowerCase();if(a)return s.set(n,a),a}catch{return s.set(n,null),null}if(r.has(n)){let i=r.get(n)??null;return s.set(n,i),i}try{let a=await(await X(`S3 get object ${n}`,3e5,({httpOptions:o})=>e.send(new GetObjectCommand({Bucket:t,Key:n}),o))).Body?.transformToByteArray(),c=a?ln(Buffer.from(a)):null;return r.set(n,c),s.set(n,c),c}catch{return r.set(n,null),s.set(n,null),null}}function ra(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"profile"}function sa(e,t){let n=e,s=Object.entries(t).sort((r,i)=>i[0].length-r[0].length);for(let[r,i]of s)r&&(n=n.split(r).join(i));return n}async function ia(e,t,n,s){let r=S.join(e,"asset-map.json"),i;try{i=await A.readFile(r,"utf8");}catch(o){if(o.code==="ENOENT")return;throw o}let a=JSON.parse(i);if(!a||typeof a!="object")return;let c=Object.fromEntries(Object.entries(a).map(([o,u])=>{let l=String(u??"");return t.urlRewriteMode==="absolute"&&t.targetOrigin&&n.targetOrigin&&t.targetOrigin!==n.targetOrigin&&(l=l.split(t.targetOrigin).join(n.targetOrigin)),l=sa(l,s),[o,l]}));await A.writeFile(r,JSON.stringify(c,null,2),"utf8");}async function oa(e,t,n,s,r,i){let a=e.targetOrigin!==t.targetOrigin,c=Object.keys(s).length>0;if(!n||!a&&!c)return {outputDir:e.outputDir,cleanup:async()=>{}};if(a&&e.urlRewriteMode!=="absolute")throw new Error(`Deployment profile "${n}" changes targetOrigin, but the base crawl output must use urlRewriteMode "absolute" for multi-target redeploys.`);let o=S.join(S.dirname(e.outputDir),`.deploy-profile-${ra(n)}-${Date.now()}`),u=_o(o);r.info(`Preparing deployment profile "${n}" from existing crawl output to ${o}...`);try{if(await A.rm(o,{recursive:!0,force:!0}),i){await A.mkdir(o,{recursive:!0});for(let g of i){let f=S.join(e.outputDir,g),w=S.join(o,g);await A.mkdir(S.dirname(w),{recursive:!0}),await A.copyFile(f,w);}}else await A.cp(e.outputDir,o,{recursive:!0});let l={...e,sourceOrigin:e.targetOrigin,targetOrigin:t.targetOrigin,extraReplacements:s,outputDir:o},d=1;r.info(`Rewriting text files for deployment profile "${n}"...`);let p=await lt(l,{},{files:i,onStart:({totalFiles:g,workerCount:f})=>{d=f,r.info(`Rewriting ${g} text file(s) for deployment profile "${n}" with ${f} worker(s).`);},onProgress:({index:g,totalFiles:f,changedTextFiles:w,file:m,changed:h})=>{let k=`Rewriting [${g}/${f}] ${m} (${h?"rewrote":"checked"}; ${w} changed so far)`;f<=200||g<=5||g%10===0||g===f?(r.progress(k,{file:m,index:g,totalFiles:f,changed:h,changedTextFiles:w,workerCount:d}),r.info(k)):r.debug(k);}});return await ia(o,e,t,s),r.info(`Prepared deployment profile "${n}" in ${o} (${p} rewritten text file(s)).`),{outputDir:o,cleanup:async()=>{u(),await A.rm(o,{recursive:!0,force:!0});}}}catch(l){throw r.error(`Failed to prepare deployment profile "${n}" temporary output.`,{tempDir:o,outputDir:e.outputDir,error:l instanceof Error?l.message:String(l),...l instanceof Error&&l.stack?{stack:l.stack}:{}}),await A.rm(o,{recursive:true,force:true}).catch(()=>{}),u(),await r.flush().catch(()=>{}),l}}async function Br(e=process.argv.slice(2)){let t=await ne(),n=vt(e),s=Le(t,n),r=S.resolve(s.config.logDir||"logs"),i=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",a=i?S.join(S.resolve(i),"deploy-diff.json"):"",c=new Me(r,"deploy.log.jsonl",s.config.logLevel??"info"),o=s.profile?.extraReplacements??{},u=async()=>{};try{let l=await at(t);if(e.includes("--content-sync")&&l?.schemaVersion!==2)throw new Error("Content-sync deployment requires a valid schema-2 targeted deploy plan.");let p=await Hn(t);if(p)throw new Error(`Deployment blocked: the crawl started at ${p.startedAt} did not complete its final rewrite. Run a successful crawl or resume the rewrite before deploying.`);let g=await oa(t,s.config,s.name,o,c,l?.schemaVersion===2?l.changedFiles:void 0);u=g.cleanup;let f={...s.config,outputDir:g.outputDir},w=f.s3SyncMode??"sdk-upload-delete";if(l?.schemaVersion===2&&l.deletedFiles.length>0&&w!=="sdk-upload-delete")throw new Error("Content-sync tombstones require the sdk-upload-delete S3 sync mode.");let m=l?.schemaVersion!==2&&g.outputDir!==t.outputDir&&(t.targetOrigin!==s.config.targetOrigin||Object.keys(o).length>0),h=!!l&&!l.fullSyncRequired&&!m;if(l?.schemaVersion===2&&!h)throw new Error("Content-sync deployment cannot widen into a full-output deployment.");s.name&&c.info(`Using deployment profile: ${s.name}`),c.info(`Starting deploy \u2014 s3://${f.s3.bucket}/${f.s3.prefix||""} (region: ${f.s3.region})`),c.info(`S3 sync mode: ${w}`),l&&l.fullSyncRequired?c.info("Deploy plan requests a full sync; scanning the whole output tree."):l&&m?c.info("Ignoring incremental deploy plan because deployment-profile rewrites require a full sync."):h&&c.info(`Using incremental deploy plan: ${l.changedFiles.length} changed file(s), ${l.deletedFiles.length} deleted file(s).`),c.mark("deploy");let b=new S3Client({region:f.s3.region}),k=g.outputDir===t.outputDir?await Ho(t,i,c):null,M=l?.schemaVersion===2?[...l.uploadGroups.assets,...l.uploadGroups.content,...l.uploadGroups.listings,...l.uploadGroups.sitemapLeaves,...l.uploadGroups.sitemapIndexes]:l?.changedFiles??[];if(l?.schemaVersion===2){let T=[...new Set(M)],z=[...new Set(l.changedFiles)];if(T.length!==z.length||z.some(I=>!T.includes(I)))throw new Error("Content-sync deploy-plan upload groups do not cover the exact changed-file set.")}let F=h?(await Promise.all(M.map(async T=>{try{return (await A.stat(S.join(f.outputDir,T))).isFile()?T:null}catch{if(l?.schemaVersion===2)throw new Error(`Content-sync planned upload is missing: ${T}`);return null}}))).filter(T=>T!==null):await Ts(["**/*"],{cwd:f.outputDir,onlyFiles:!0,dot:!0}),x=[],j=[],v=F.filter(T=>{let z=k?.byRelativePath.get(Nr(T));if(!z)return !0;let I=Rt(f.s3.prefix,T);return x.push(T),j.push(I),c.reject(z.kind,z.sourceUrl||T,"rewrite not completed; deploy upload blocked","deploy-guard",{file:T,key:I,outputPath:z.outputPath,manifestPath:k?.manifestPath}),!1}),P=new Set((h?v:F).map(T=>Rt(f.s3.prefix,T)));k&&(k.pendingPages>0||k.pendingTextAssets>0)&&c.info(`Deploy rewrite guard loaded ${k.pendingPages} pending page(s) and ${k.pendingTextAssets} pending text asset(s) from crawl manifest.`,{manifestPath:k.manifestPath,pendingPages:k.pendingPages,pendingTextAssets:k.pendingTextAssets,source:"deploy-guard"}),x.length>0&&c.warn(`Deploy rewrite guard blocked ${x.length} file(s) from upload because final crawl rewrite is incomplete.`,{rejected:x.length,manifestPath:k?.manifestPath,source:"deploy-guard"}),h?c.info(`Using ${v.length} eligible planned changed file(s) from deploy plan for upload${x.length>0?` (${x.length} blocked by deploy rewrite guard)`:""}.`):c.info(`Found ${F.length} file(s) in output directory "${f.outputDir}"${x.length>0?`; ${v.length} remain eligible for upload after deploy rewrite guard filtering`:""}.`),c.progress("Deploy preflight: comparing local output with remote S3 state.",{phase:"deploy",mode:w,totalFiles:v.length,scannedFiles:F.length,rejected:x.length,deploymentProfile:s.name||"",s3Bucket:f.s3.bucket,s3Prefix:f.s3.prefix||"",targetedPlan:h,deployGuardEnabled:g.outputDir===t.outputDir});let C=0,y=0,R=0,U=[],q=[],Z=[],V=[],_=[],$=new Map,ge=new Map,ve=new Map,et=new Map,kt=new Map;h||(c.info("Listing existing S3 objects to detect unchanged files..."),$=await Zo(b,f.s3.bucket,f.s3.prefix,c),c.info(`Found ${$.size} existing key(s) in S3.`));let Gr=async T=>$.has(T)?$.get(T)??null:h?Yo(b,f.s3.bucket,T,ge):null;for(let T of v){let z=S.join(f.outputDir,T),I=Rt(f.s3.prefix,T),ee=k?.contentTypeByRelativePath.get(T),_e=ee&&ee!=="application/octet-stream"?ee:Uo.lookup(T)||ee||"application/octet-stream",Zr=cn(T)?f.s3.htmlCacheControl:f.s3.assetCacheControl,O=C+y+R+1;v.length<=200||O<=5||O%10===0||O===v.length?(c.progress(`Uploading [${O}/${v.length}] ${I} (${_e})`,{file:T,key:I,index:O,totalFiles:v.length,contentType:_e,mode:w}),c.info(`Uploading [${O}/${v.length}] ${I} (${_e})`)):c.debug(`Uploading [${O}/${v.length}] ${I} (${_e})`);try{let te=await A.readFile(z),Ne=await Gr(I),Be=null,Ae=null;if(Ne){let $t=te.byteLength;if(Ne.size===$t){let tt=Ne.etag.includes("-");if(Ne.etag!==""&&!tt){let Yr=ea(te);if(Ne.etag===Yr){y++,v.length<=200||y<=5||y%25===0?(c.progress(`Skipped unchanged [${O}/${v.length}] ${I}`,{file:T,key:I,index:O,totalFiles:v.length,uploaded:C,skipped:y,failed:R,mode:w,reason:"etag-md5-match"}),c.info(`Skipped unchanged [${O}/${v.length}] ${I}`)):c.debug(`Skipped unchanged [${O}/${v.length}] ${I}`),q.push(I);continue}}Be=Lr(te);let Sn=await ta(b,f.s3.bucket,I,ve);if(Sn&&Sn===Be){y++,v.length<=200||y<=5||y%25===0?(c.progress(`Skipped unchanged [${O}/${v.length}] ${I}`,{file:T,key:I,index:O,totalFiles:v.length,uploaded:C,skipped:y,failed:R,mode:w,reason:"metadata-sha256-match"}),c.info(`Skipped unchanged [${O}/${v.length}] ${I}`)):c.debug(`Skipped unchanged [${O}/${v.length}] ${I}`),q.push(I);continue}}if(cn(T)){Ae=ln(te);let tt=await na(b,f.s3.bucket,I,et,kt);if(tt&&tt===Ae){y++,v.length<=200||y<=5||y%25===0?(c.progress(`Skipped semantically unchanged [${O}/${v.length}] ${I}`,{file:T,key:I,index:O,totalFiles:v.length,uploaded:C,skipped:y,failed:R,mode:w,reason:"normalized-html-match"}),c.info(`Skipped semantically unchanged [${O}/${v.length}] ${I}`)):c.debug(`Skipped semantically unchanged [${O}/${v.length}] ${I}`),q.push(I);continue}}}Be=Be??Lr(te),Ae=Ae??(cn(T)?ln(te):null),await X(`S3 upload ${I}`,9e5,({abortController:$t})=>new Upload({client:b,abortController:$t,params:{Bucket:f.s3.bucket,Key:I,Body:te,ContentType:_e,CacheControl:Zr,Metadata:{[qr]:Be,...Ae?{[_r]:Ae}:{}}}}).done()),C++,U.push(I),(C%25===0||C===v.length)&&(c.progress(`Uploaded ${C}/${v.length} file(s)\u2026`,{uploaded:C,skipped:y,failed:R,totalFiles:v.length,mode:w}),c.info(`Uploaded ${C}/${v.length} file(s)\u2026`));}catch(te){R++,Z.push(I),c.error(`Failed to upload ${I}: ${te.message}`,{key:I,error:String(te)});}}if(c.info(`Upload complete: ${C} uploaded, ${y} skipped unchanged, ${j.length} rejected by guard, ${R} failed.`),Z.length>0||j.length>0)throw new Error(`Deployment stopped before deletion because ${Z.length} upload(s) failed and ${j.length} upload(s) were rejected.`);if(w==="sdk-upload-delete"){let T=new Set((l?.deletedFiles??[]).map(I=>Rt(f.s3.prefix,I))),z=[...T].filter(I=>!P.has(I));if(!h&&(_=[...$.keys()].filter(ee=>!P.has(ee)).filter(ee=>!T.has(ee)),_.length>0)){c.warn(`Protected ${_.length} remote-only S3 object(s) from deletion because the crawl did not provide explicit tombstones.`,{protected:_.length,source:"deploy-delete-guard"});for(let ee of _)c.debug(` protected remote-only object: ${ee}`);}V=await Xo(b,f.s3.bucket,h?z:z.filter(I=>$.has(I)),c);}else c.info("Sync mode is sdk-upload-only \u2014 skipping stale object deletion.");a&&(await A.mkdir(S.dirname(a),{recursive:!0}),await A.writeFile(a,JSON.stringify({generatedAt:new Date().toISOString(),mode:w,summary:{totalFiles:F.length,eligibleFiles:v.length,uploaded:U.length,skipped:q.length,rejected:j.length,failed:Z.length,deleted:V.length,protected:_.length,...s.name?{profile:s.name}:{}},uploadedKeys:U,skippedKeys:q,rejectedKeys:j,failedKeys:Z,deletedKeys:V,protectedRemoteOnlyKeys:_},null,2),"utf8")),l?.schemaVersion!==2&&await $e(t),c.endMark("deploy"),await c.flush();}finally{await u().catch(()=>{});}}function ca(e){let t=e;return t.endsWith("/")?t+="index.html":S.posix.basename(t).includes(".")||(t+="/index.html"),t}function ua(e,t){let n=t.trim().replace(/^\/+|\/+$/g,"");if(!n)return null;let s=`/${n}`;return e===s||e.startsWith(`${s}/`)?e:`${s}${e.startsWith("/")?e:`/${e}`}`}function Wr(e,t){let n=new Set;for(let s of e){let r=new URL(s,"https://content-sync.invalid");if(r.origin!=="https://content-sync.invalid")continue;let i=`${r.pathname}${r.search}`,a=ca(r.pathname);n.add(i),n.add(`${a}${r.search}`);let c=ua(a,t);c&&n.add(`${c}${r.search}`);}return [...n].sort()}function ga(){let e=String(process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"").trim();return e?S.join(S.resolve(e),"content-sync-invalidation.json"):""}async function fn(e,t){if(!e)return;await A.mkdir(S.dirname(e),{recursive:true});let n=`${e}.${process.pid}.${Date.now()}.tmp`;await A.writeFile(n,JSON.stringify({...t,updatedAt:new Date().toISOString()},null,2),"utf8"),await A.rename(n,e);}async function fa(e,t,n,s){if(!e)return null;try{let r=JSON.parse(await A.readFile(e,"utf8"));if(r.schemaVersion!==1||r.distributionId!==t||r.impactHash!==n||!Array.isArray(r.batches))throw new Error("Content-sync invalidation state does not match the deploy plan.");let i=r.batches.flatMap(a=>a.paths);return i.length!==s.length||i.some((a,c)=>a!==s[c])?null:r}catch(r){if(r.code==="ENOENT")return null;throw r}}function ma(e,t=3e3){let n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}async function zr(e=process.argv.slice(2)){let t=await ne(),n=vt(e),s=Le(t,n),r=s.config,i=new Me(r.logDir||"logs","invalidate.log.jsonl",r.logLevel??"info"),a=e.includes("--content-sync"),c=await at(t);if(a&&c?.schemaVersion!==2)throw new Error("Content-sync invalidation requires a valid schema-2 targeted deploy plan.");if(s.name&&i.info(`Using deployment profile: ${s.name}`),!r.cloudFront.distributionId){i.info("No CloudFront distributionId configured; skipping invalidation."),await i.flush();return}let o=c?.schemaVersion===2?c.invalidationPaths:r.cloudFront.invalidationPaths.length>0?r.cloudFront.invalidationPaths:["/*"],u=c?.schemaVersion===2?Wr(o,r.s3.prefix||""):o;if(c?.schemaVersion===2&&u.some(f=>f==="/*"))throw new Error("Content-sync cannot use a whole-distribution invalidation.");if(u.length===0){i.info("The targeted deploy plan has no CloudFront paths to invalidate."),await i.flush();return}let l=r.cloudFront.distributionId,d=new CloudFrontClient({region:"us-east-1",maxAttempts:5});if(i.mark("invalidate"),c?.schemaVersion!==2){let f=`smartcloud-static-publisher-${Date.now()}`;await X(`CloudFront invalidation for distribution ${l}`,3e5,({httpOptions:w})=>d.send(new CreateInvalidationCommand({DistributionId:l,InvalidationBatch:{CallerReference:f,Paths:{Quantity:u.length,Items:u}}}),w)),i.endMark("invalidate"),await i.flush();return}let p=ga(),g=await fa(p,l,c.impactHash,u);if(!g){let f=createHash("sha256").update(JSON.stringify(u)).digest("hex");g={schemaVersion:1,distributionId:l,impactHash:c.impactHash,updatedAt:new Date().toISOString(),batches:ma(u).map((w,m)=>({index:m,callerReference:`wpsuite-content-sync-${c.impactHash.slice(0,24)}-${f.slice(0,24)}-${m}`,paths:w,invalidationId:null,status:"pending"}))},await fn(p,g);}for(let f of g.batches){if(!f.invalidationId){let w=await X(`CloudFront targeted invalidation batch ${f.index+1}`,3e5,({httpOptions:h})=>d.send(new CreateInvalidationCommand({DistributionId:l,InvalidationBatch:{CallerReference:f.callerReference,Paths:{Quantity:f.paths.length,Items:f.paths}}}),h)),m=String(w.Invalidation?.Id||"").trim();if(!m)throw new Error("CloudFront did not return an invalidation ID.");f.invalidationId=m,f.status="created",await fn(p,g);}await waitUntilInvalidationCompleted({client:d,maxWaitTime:900,minDelay:2,maxDelay:15},{DistributionId:l,Id:f.invalidationId}),f.status="completed",await fn(p,g),i.info(`CloudFront invalidation batch ${f.index+1}/${g.batches.length} completed.`,{invalidationId:f.invalidationId,pathCount:f.paths.length});}i.endMark("invalidate"),await i.flush();}function Tt(e){let t=new URL(e);return t.hash="",t.href}function Qr(e,t){let n=new Set([...t].map(c=>Tt(c))),s=new Map,r=new Map,i=c=>{s.set(Tt(c),c);},a=c=>{if(!c)return;let o=Tt(c);s.has(o)||r.set(o,c);};for(let c of e.deleteUrls)i(c);for(let c of e.archiveFamilies)if(c.foundPosts===0)for(let o of c.pageUrls)n.has(Tt(o))||i(o);a(e.directRenderUrls[0]);for(let c of e.archiveFamilies)a(c.pageUrls[0]),a(c.pageUrls.at(-1));for(let c of e.sitemapUrls)a(c);return {expectedAvailable:[...r.values()],expectedMissing:[...s.values()]}}var Vr=["claimed","impact-planned","rendered","deployed","invalidated","verified","acknowledged"];function wn(){let e=String(process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"").trim();if(!e)throw new Error("Content-sync requires a runtime directory.");return S.resolve(e)}function qe(e,t){return Vr.indexOf(e)>=Vr.indexOf(t)}async function pe(e,t,n,s,r={}){let i={timestamp:new Date().toISOString(),eventType:t,status:t.endsWith("failed")?"failed":"success",actorSource:"content-sync",jobId:n.id||"",command:"content-sync",message:s,details:r};await A.mkdir(e,{recursive:true}),await A.appendFile(S.join(e,"audit-events.jsonl"),`${JSON.stringify(i)}
|
|
11
|
+
`,"utf8");}function wa(e){return We({postTypes:e.postTypes??[],listingPaths:e.listingPaths??[],includeSubsites:e.includeSubsites,includePostTypeArchives:e.includePostTypeArchives,includeTaxonomyArchives:e.includeTaxonomyArchives,includeAuthorArchives:e.includeAuthorArchives,includeDateArchives:e.includeDateArchives,includePostsPage:e.includePostsPage,includeSitemapChain:e.includeSitemapChain})}function ya(e,t){let n=(e.scheduler?.rules??[]).find(s=>s.command==="content-sync"&&s.id===t);if(!n)throw new Error(`Content-sync scheduler rule not found: ${t}`);if(n.enabled===false)throw new Error(`Content-sync scheduler rule is disabled: ${t}`);return n}async function yn(e,t){if(e.subscriptionType!=="PROFESSIONAL"&&e.subscriptionType!=="AGENCY")throw new Error("Content-sync requires an active Professional or Agency subscription.");let n=wa(t),s=Le(e,t.deploymentProfile),r=s.name||"",i=vn(e.sourceOrigin,String(t.id||""),n),a=Cn({sourceOrigin:e.sourceOrigin,targetOrigin:s.config.targetOrigin,deploymentProfile:r,s3Bucket:s.config.s3.bucket,s3Prefix:s.config.s3.prefix,cloudFrontDistributionId:s.config.cloudFront.distributionId,urlRewriteMode:s.config.urlRewriteMode,extraReplacements:s.profile?.extraReplacements??{}}),c=Rn({siteId:e.wpsuite?.siteSettings?.siteId,accountId:e.wpsuite?.siteSettings?.accountId,sourceOrigin:e.sourceOrigin,ruleId:String(t.id||""),targetFingerprint:a}),o=`content-sync:${String(t.id||"")}:${oe({scopeFingerprint:i,targetFingerprint:a}).slice(0,32)}`,u=new rt({sourceOrigin:e.sourceOrigin,runtimeToken:String(e.wpsuite?.runtimeToken||""),ignoreHttpsErrors:e.ignoreHttpsErrors}),l=await u.releaseFingerprint(n.includeSubsites),d=bn({wordpressFingerprint:l,targetFingerprint:a,sourceOrigin:e.sourceOrigin,sitemapPaths:e.sitemapPaths,blockedPathPrefixes:e.blockedPathPrefixes,assetPathPrefixes:e.assetPathPrefixes,noJavaScriptRenderPathPrefixes:e.noJavaScriptRenderPathPrefixes,urlRewriteMode:e.urlRewriteMode});return {rule:t,scope:n,deployment:s,deploymentProfile:r,scopeFingerprint:i,targetFingerprint:a,consumerId:c,coalesceKey:o,client:u,releaseFingerprint:d}}async function Sa(e){let t=wn(),n=st(t),s=await ne(),r=(s.scheduler?.rules??[]).filter(u=>u.command==="content-sync"&&u.enabled!==false);if(r.length===0)return 0;let i=await Ot(n),a=await it(n),c=await Dt(n),o=0;for(let u of r){let l=await yn(s,u),d=c.entries[l.coalesceKey];if(!d||d.releaseJobId!==e||d.scopeFingerprint!==l.scopeFingerprint||d.targetFingerprint!==l.targetFingerprint||d.releaseFingerprint!==l.releaseFingerprint)throw new Error(`The normal release has no matching pre-crawl content-sync cutoff for rule ${String(u.id||"")}.`);let p=oe({releaseJobId:e,releaseFingerprint:l.releaseFingerprint,scopeFingerprint:l.scopeFingerprint,targetFingerprint:l.targetFingerprint,sequence:d.sequence}),g=await l.client.establishBaseline({consumerId:l.consumerId,scopeFingerprint:l.scopeFingerprint,baselineId:p,postTypes:l.scope.postTypes,includeSubsites:l.scope.includeSubsites,sequence:d.sequence}),f={schemaVersion:1,ruleId:String(u.id||""),consumerId:l.consumerId,coalesceKey:l.coalesceKey,scopeFingerprint:l.scopeFingerprint,targetFingerprint:l.targetFingerprint,releaseFingerprint:l.releaseFingerprint,baselineId:p,deploymentProfile:l.deploymentProfile,committedSequence:g.committedSequence,releaseJobId:e,verifiedAt:new Date().toISOString()};i.entries[l.coalesceKey]=f;let w=a.rules[l.coalesceKey];a.rules[l.coalesceKey]={ruleId:String(u.id||""),consumerId:l.consumerId,coalesceKey:l.coalesceKey,committedSequence:g.committedSequence,observedHeadSequence:g.headSequence,lag:Math.max(0,g.headSequence-g.committedSequence),lastSuccessfulJobId:w?.lastSuccessfulJobId||e,lastSuccessfulAt:new Date().toISOString(),trailingWorkDetected:g.headSequence>g.committedSequence,retryAttempt:0,nextRetryAt:null,lastError:null,baselineStatus:"ready",baselineReason:null};let m=await Dn(n,l.coalesceKey);await pe(t,"content-sync-baseline-established",{id:e},"A normal release established a verified content-sync baseline.",{ruleId:u.id,consumerId:l.consumerId,committedSequence:g.committedSequence,supersededCurrent:m}),o++;}return await kn(n,i),await ot(n,a),await A.rm(n.releaseCutoff,{force:true}),o}async function Pa(e){let t=wn(),n=st(t),s=await ne(),r=(s.scheduler?.rules??[]).filter(c=>c.command==="content-sync"&&c.enabled!==false);if(r.length===0)return 0;let i=await Dt(n),a=0;for(let c of r){let o=await yn(s,c),u=Object.values(i.entries).find(p=>p.releaseJobId===e&&p.ruleId===String(c.id||""));if(u){if(u.coalesceKey===o.coalesceKey&&u.scopeFingerprint===o.scopeFingerprint&&u.targetFingerprint===o.targetFingerprint&&u.releaseFingerprint===o.releaseFingerprint){a++;continue}throw new Error(`The normal release scope changed after its journal cutoff was captured for rule ${String(c.id||"")}. Start a new normal publish instead of resuming this release.`)}let l=await o.client.unboundHead(o.scope.postTypes,o.scope.includeSubsites),d={schemaVersion:1,releaseJobId:e,ruleId:String(c.id||""),coalesceKey:o.coalesceKey,scopeFingerprint:o.scopeFingerprint,targetFingerprint:o.targetFingerprint,releaseFingerprint:o.releaseFingerprint,sequence:l.headSequence,capturedAt:new Date().toISOString()};i.entries[o.coalesceKey]=d,await pe(t,"content-sync-release-cutoff-captured",{id:e},"A normal release captured its pre-crawl content-sync journal cutoff.",{ruleId:c.id,consumerId:o.consumerId,sequence:l.headSequence}),a++;}return await Tn(n,i),a}async function ba(e,t){let n=JSON.parse(await A.readFile(S.join(e,"current-run.json"),"utf8"));if(n.id!==t||n.command!=="content-sync"||!String(n.ruleId||"").trim())throw new Error("The active queue job is not the requested content-sync job.");return n}async function hn(e,t,n=0){let s=e.protocol==="https:"?An:ss,r=e.protocol==="https:"?new An.Agent({rejectUnauthorized:!t}):void 0;return new Promise((i,a)=>{let c=s.get(e,{agent:r,timeout:3e4,headers:{"user-agent":"WP-Suite-Content-Sync/1"}},o=>{let u=o.statusCode??500,l=o.headers.location;if(u>=300&&u<400&&l&&n<5){o.resume(),hn(new URL(l,e),t,n+1).then(i,a);return}let d=[],p=0;o.on("data",g=>{p+=g.byteLength,p<=1048576&&d.push(g);}),o.on("error",a),o.on("end",()=>i({status:u,body:Buffer.concat(d).toString("utf8")}));});c.on("timeout",()=>c.destroy(new Error(`Verification timed out: ${e}`))),c.on("error",a);})}async function va(e,t,n,s){let r=t.deployment.config.targetOrigin;if(!/^https?:\/\//i.test(r))throw new Error("Content-sync verification requires an absolute HTTP(S) target origin.");let i=JSON.parse(await A.readFile(s,"utf8")),a=new Set;for(let[o,u]of Object.entries(i.pages??{}))a.add(o),typeof u.url=="string"&&a.add(u.url);let c=Qr(n,a);for(let o of c.expectedAvailable){let u=new URL(o),l=new URL(`${u.pathname}${u.search}`,r),d=await hn(l,e.ignoreHttpsErrors);if(d.status<200||d.status>=400)throw new Error(`Content-sync verification failed (${d.status}): ${l}`)}for(let o of c.expectedMissing.slice(0,10)){let u=new URL(o),l=new URL(`${u.pathname}${u.search}`,r),d=await hn(l,e.ignoreHttpsErrors);if(d.status>=200&&d.status<300)throw new Error(`Deleted content is still publicly available: ${l}`)}}async function Ca(e){let t=await A.readFile(e.candidateManifest,"utf8");JSON.parse(t);let n=`${e.trustedManifest}.${process.pid}.tmp`;await A.writeFile(n,t,"utf8"),await A.rename(n,e.trustedManifest);}async function Ra(e,t){try{let n=JSON.parse(await A.readFile(e.candidateManifest,"utf8"));if([...Object.values(n.pages??{}),...Object.values(n.assets??{})].some(r=>r?.lastSeenRunId===t))return "resumed"}catch(n){if(n.code!=="ENOENT")throw new Error(`The content-sync candidate manifest is invalid: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return await A.copyFile(e.trustedManifest,e.candidateManifest).catch(n=>{throw new Error(`A trusted crawl manifest is required before content-sync: ${n instanceof Error?n.message:String(n)}`,{cause:n})}),"initialized"}async function xe(e,t,n,s,r={},i=0,a=async()=>{}){t.phase=n,await $n(e,t),await Fn(e,{schemaVersion:1,jobId:t.jobId,phase:n,completedItems:s,totalItems:s,attempt:i,updatedAt:new Date().toISOString(),details:r}),await pe(S.dirname(e.state),"content-sync-checkpoint",{id:t.jobId},`Content-sync checkpoint completed: ${n}.`,{phase:n,completedItems:s,totalItems:s,attempt:i,...r}),await a(n,t);}async function Ia(e,t={}){let n={loadConfig:ne,resolveRuleContext:yn,runCrawl:Or,runDeploy:Br,runInvalidate:zr,verifyDeployment:va,promoteCandidateManifest:Ca,clearDeployPlan:$e,afterCheckpoint:async()=>{},...t},s=wn(),r=st(s),i=await ba(s,e),a=await n.loadConfig(),c=ya(a,String(i.ruleId)),o=await n.resolveRuleContext(a,c);if(i.coalesceKey&&i.coalesceKey!==o.coalesceKey)throw new Error("Queued content-sync demand no longer matches the active rule scope.");let l=(await Ot(r)).entries[o.coalesceKey];if(!l||l.scopeFingerprint!==o.scopeFingerprint||l.targetFingerprint!==o.targetFingerprint||l.releaseFingerprint!==o.releaseFingerprint)throw await pe(s,"content-sync-baseline-rejected",i,"Content-sync requires a new verified full or incremental release baseline.",{ruleId:c.id,reason:l?"mismatch":"missing"}),new Error("Content-sync baseline is missing or stale. Run a successful normal publish first.");let d=await jt(r),p=await o.client.head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites});if(d&&d.jobId!==i.id)throw new Error("Another immutable content-sync range is still active.");if(d||(d={schemaVersion:1,jobId:i.id,ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,scopeFingerprint:o.scopeFingerprint,targetFingerprint:o.targetFingerprint,baselineId:l.baselineId,fromSequence:p.committedSequence,toSequence:p.headSequence,phase:"claimed",impactHash:null,startedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},await xe(r,d,"claimed",0,{fromSequence:d.fromSequence,toSequence:d.toSequence},0,n.afterCheckpoint),await pe(s,"content-sync-range-claimed",i,"Content-sync claimed a closed journal range.",{fromSequence:d.fromSequence,toSequence:d.toSequence})),d.fromSequence===d.toSequence){let h=await it(r);h.rules[o.coalesceKey]={ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,committedSequence:d.toSequence,observedHeadSequence:p.headSequence,lag:Math.max(0,p.headSequence-d.toSequence),lastSuccessfulJobId:i.id,lastSuccessfulAt:new Date().toISOString(),trailingWorkDetected:false,retryAttempt:0,nextRetryAt:null,lastError:null},await ot(r,h),await Ut(r);return}let g=await En(r);if(!qe(d.phase,"impact-planned")){let h=await o.client.events({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites,afterSequence:d.fromSequence,throughSequence:d.toSequence}),b=Ft({events:h,scope:o.scope,sourceOrigin:a.sourceOrigin}),k=await o.client.resolveImpactFamilies(b,o.scope.includeSubsites);g=xn({jobId:i.id,ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,scopeFingerprint:o.scopeFingerprint,targetFingerprint:o.targetFingerprint,baselineId:l.baselineId,sourceOrigin:a.sourceOrigin,scope:o.scope,fromSequence:d.fromSequence,toSequence:d.toSequence,events:h,resolvedArchiveFamilies:k,sitemapUrls:a.sitemapPaths}),await Mn(r,g),d.impactHash=g.impactHash,await xe(r,d,"impact-planned",h.length,{eventCount:h.length,foldedCount:g.foldedCount,impactHash:g.impactHash},0,n.afterCheckpoint),await pe(s,"content-sync-impact-planned",i,"Content-sync persisted an immutable impact plan.",{impactHash:g.impactHash,eventCount:h.length});}if(!g||g.jobId!==i.id||d.impactHash!==g.impactHash)throw new Error("The immutable content-sync impact plan is missing or mismatched.");if(process.env.STATIC_PUBLISHER_CRAWL_MANIFEST_PATH=r.candidateManifest,!qe(d.phase,"rendered")){let h=await Ra(r,i.id);await pe(s,h==="resumed"?"content-sync-render-resumed":"content-sync-render-initialized",i,h==="resumed"?"Content-sync resumed its candidate crawl manifest.":"Content-sync initialized a candidate crawl manifest.",{impactHash:g.impactHash}),await n.runCrawl(["--content-sync-plan",r.impact]),await xe(r,d,"rendered",g.directRenderUrls.length+g.archiveFamilyUrls.length,{impactHash:g.impactHash},i.attempt??0,n.afterCheckpoint);}let f=o.deploymentProfile?["--profile",o.deploymentProfile]:[];if(qe(d.phase,"deployed")||(await n.runDeploy([...f,"--content-sync"]),await xe(r,d,"deployed",1,{impactHash:g.impactHash},0,n.afterCheckpoint),await pe(s,"content-sync-deployed",i,"Content-sync targeted deployment completed.",{impactHash:g.impactHash})),qe(d.phase,"invalidated")?qe(d.phase,"verified")||await n.runInvalidate([...f,"--content-sync"]):(await n.runInvalidate([...f,"--content-sync"]),await xe(r,d,"invalidated",1,{impactHash:g.impactHash},0,n.afterCheckpoint)),qe(d.phase,"verified")||(await n.verifyDeployment(a,o,g,r.candidateManifest),await n.promoteCandidateManifest(r),await xe(r,d,"verified",1,{impactHash:g.impactHash},0,n.afterCheckpoint)),p=await o.client.head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites}),p.committedSequence===d.fromSequence)await o.client.acknowledge({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,expectedSequence:d.fromSequence,sequence:d.toSequence,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites});else if(p.committedSequence!==d.toSequence)throw new Error("Content-sync acknowledgement cursor is in an unexpected state.");await xe(r,d,"acknowledged",1,{sequence:d.toSequence},0,n.afterCheckpoint),await pe(s,"content-sync-cursor-acknowledged",i,"Content-sync committed its journal cursor after verification.",{sequence:d.toSequence});let w=await o.client.head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:l.baselineId,postTypes:o.scope.postTypes,includeSubsites:o.scope.includeSubsites}),m=await it(r);m.rules[o.coalesceKey]={ruleId:String(c.id||""),consumerId:o.consumerId,coalesceKey:o.coalesceKey,committedSequence:d.toSequence,observedHeadSequence:w.headSequence,lag:Math.max(0,w.headSequence-d.toSequence),lastSuccessfulJobId:i.id,lastSuccessfulAt:new Date().toISOString(),trailingWorkDetected:w.headSequence>d.toSequence,retryAttempt:0,nextRetryAt:null,lastError:null},await ot(r,m),await n.clearDeployPlan(a),await A.rm(S.join(s,"content-sync-invalidation.json"),{force:true}),await A.rm(r.candidateManifest,{force:true}),await Ut(r);}async function Kr(e=process.argv.slice(2)){let n=e.indexOf("--capture-baseline-cutoffs");if(n>=0){let a=String(e[n+1]||"").trim();if(!a)throw new Error("--capture-baseline-cutoffs requires a release job ID.");await Pa(a);return}let s=e.indexOf("--establish-baselines");if(s>=0){let a=String(e[s+1]||"").trim();if(!a)throw new Error("--establish-baselines requires a release job ID.");await Sa(a);return}let r=e.indexOf("--job-id"),i=r>=0?String(e[r+1]||"").trim():"";if(!i)throw new Error("Content-sync requires --job-id.");await Ia(i);}Kr().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1);});
|