@smart-cloud/publisher-exporter 1.1.38 → 1.1.40

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.
@@ -1,2 +1,2 @@
1
- import {pathToFileURL}from'url';import f from'fs/promises';import {existsSync,createReadStream,createWriteStream}from'fs';import g from'path';import {spawn}from'child_process';import {randomUUID}from'crypto';import {pipeline}from'stream/promises';import {createGzip}from'zlib';import se from'http';import ue from'https';function W(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function ae(e){let t=String(e??"").trim();if(!t)return "";let r=t;if(/^https?:\/\//i.test(r))try{r=new URL(r).pathname;}catch{return ""}if(r=r.split(/[?#]/,1)[0]?.replace(/\\/g,"/").trim()??"",!r)return "";let i=r.endsWith("/"),n=r.replace(/^\/+/,"").split("/").map(o=>o.replace(/[^A-Za-z0-9._-]/g,"")).filter(o=>o.length>0&&o!=="."&&o!=="..");if(n.length===0)return "";let s=`/${n.join("/")}`;return i&&g.extname(s)===""&&(s+="/"),s==="/"?"":s}function T(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t.trim(),String(r??"")]).filter(([t])=>t.length>0))}function ce(e){if(!e||typeof e!="object")return {};let t={};for(let[r,i]of Object.entries(e)){let n=r.trim();if(!n||!i||typeof i!="object")continue;let s=i,o={};if(typeof s.targetOrigin=="string"){let a=W(s.targetOrigin);a&&(o.targetOrigin=a);}let u=T(s.extraReplacements);if(Object.keys(u).length>0&&(o.extraReplacements=u),s.s3&&typeof s.s3=="object"){let a={},c=s.s3;typeof c.bucket=="string"&&(a.bucket=c.bucket.trim()),typeof c.prefix=="string"&&(a.prefix=c.prefix.trim()),typeof c.region=="string"&&(a.region=c.region.trim()),typeof c.htmlCacheControl=="string"&&(a.htmlCacheControl=c.htmlCacheControl.trim()),typeof c.assetCacheControl=="string"&&(a.assetCacheControl=c.assetCacheControl.trim()),Object.keys(a).length>0&&(o.s3=a);}if(s.cloudFront&&typeof s.cloudFront=="object"){let a={},c=s.cloudFront;typeof c.distributionId=="string"&&(a.distributionId=c.distributionId.trim()),Array.isArray(c.invalidationPaths)&&(a.invalidationPaths=c.invalidationPaths.map(d=>String(d??"").trim()).filter(d=>d.length>0)),Object.keys(a).length>0&&(o.cloudFront=a);}t[n]=o;}return t}function k(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function le(e,t){if(!e||typeof e!="object")return null;let r=e,i=r.command;if(i!=="publish"&&i!=="crawl"&&i!=="deploy"&&i!=="invalidate"&&i!=="retry-timeouts"&&i!=="url")return null;let n=Number.parseInt(String(r.intervalMinutes??"0"),10);if(!Number.isFinite(n)||n<1)return null;let s=String(r.id??`${i}-${t+1}`).trim();if(!s)return null;let o=String(r.deploymentProfile??"").trim(),u=String(r.url??"").trim(),a=Array.isArray(r.postTypes)?[...new Set(r.postTypes.map(d=>String(d??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],c=Array.isArray(r.listingPaths)?[...new Set(r.listingPaths.map(d=>String(d??"").trim()).filter(Boolean))]:[];return {id:s,enabled:r.enabled!==false,command:i,intervalMinutes:n,...i==="publish"||i==="crawl"?{crawlMode:r.crawlMode==="incremental"?"incremental":"full"}:{},...(i==="publish"||i==="deploy"||i==="invalidate")&&o?{deploymentProfile:o}:{},...u?{url:u}:{},...a.length>0?{postTypes:a}:{},...c.length>0?{listingPaths:c}:{},...typeof r.includePostTypeArchives=="boolean"?{includePostTypeArchives:r.includePostTypeArchives}:{},...typeof r.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:r.includeTaxonomyArchives}:{},...typeof r.includeAuthorArchives=="boolean"?{includeAuthorArchives:r.includeAuthorArchives}:{},...typeof r.includeDateArchives=="boolean"?{includeDateArchives:r.includeDateArchives}:{},...typeof r.includePostsPage=="boolean"?{includePostsPage:r.includePostsPage}:{},...typeof r.includeSitemapChain=="boolean"?{includeSitemapChain:r.includeSitemapChain}:{}}}function Q(e){let t=e&&typeof e=="object"?e:{},r=Array.isArray(t.rules)?t.rules.map((i,n)=>le(i,n)).filter(i=>!!i):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:r}}function de(e){if(!e||typeof e!="object")return;let t=e,r={};for(let n of ["accountId","siteId"]){let s=t[n];typeof s=="string"&&s.trim()!==""&&(r[n]=s.trim());}let i=Number(t.lastUpdate??0);return Number.isFinite(i)&&i>0&&(r.lastUpdate=Math.floor(i)),t.subscriber===true&&(r.subscriber=true),Object.keys(r).length>0?r:void 0}function J(e){let t=e&&typeof e=="object"?e:{},r=String(t.accountId??"").trim(),i=String(t.siteId??"").trim(),n=t.subscriber===true,s=de(t.siteSettings),o={...s??{},...r?{accountId:s?.accountId??r}:{},...i?{siteId:s?.siteId??i}:{},...s?.subscriber===true||n?{subscriber:true}:{}},u={},a=String(t.apiBase??"").trim();a&&(u.apiBase=a);let c=String(t.runtimeToken??t.nonce??"").trim();c&&(u.runtimeToken=c);let d=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();d&&(u.virtualAssetBaseUrl=d),Object.keys(o).length>0&&(u.siteSettings=o);let p=k(t.subscriptionType);return p&&(u.subscriptionType=p),u}function pe(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function z(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function ge(e,t){let r=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[i,n]of new Headers(t.headers).entries())r.set(i,n);return r}async function N(e,t,r=5){let i=new URL(z(e)),n=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),s=i.protocol==="http:"?se:ue,o=ge(e,t);return await new Promise((u,a)=>{let c=s.request(i,{method:n,headers:Object.fromEntries(o.entries()),...i.protocol==="https:"?{rejectUnauthorized:false}:{}},d=>{let p=[];d.on("data",l=>{p.push(Buffer.isBuffer(l)?l:Buffer.from(l));}),d.on("error",a),d.on("end",()=>{let l=d.statusCode??0,m=d.headers.location;if(r>0&&m&&[301,302,303,307,308].includes(l)){u(N(new URL(m,i),{method:l===303?"GET":n},r-1));return}let h=new Headers;for(let[P,S]of Object.entries(d.headers))Array.isArray(S)?h.set(P,S.join(", ")):typeof S=="string"&&h.set(P,S);u(new Response(Buffer.concat(p),{status:l,statusText:d.statusMessage??"",headers:h}));});});c.on("error",a),c.end();})}function me(e){let t=J(e.wpsuite),r={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},i=String(r.accountId??"").trim(),n=String(r.siteId??"").trim(),s=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...s?{virtualAssetBaseUrl:s}:{},...Object.keys(r).length>0?{siteSettings:r}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!i||!n||!s)return false;pe(e.sourceOrigin);let o=globalThis,a={...o.WpSuite??{},siteSettings:r,uploadUrl:s};return t.apiBase&&(a.apiBase=t.apiBase),o.WpSuite=a,true}async function fe(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!me(e)){let n=e.wpsuite?.siteSettings,s=[String(n?.accountId??"").trim()?"":"accountId",String(n?.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): ${s.join(", ")}.`,requests:[]}}}let r=globalThis.fetch,i=[];try{typeof r=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(a,c)=>{let d=z(a);if(d.startsWith(t)){let p=(()=>{try{return new URL(d).pathname}catch{return d}})();try{let l=e.ignoreHttpsErrors&&d.startsWith("https://")?await N(a,c):await r(a,c);return i.push({path:p,status:l.status,ok:l.ok,error:null}),l}catch(l){throw i.push({path:p,status:null,ok:!1,error:l instanceof Error?l.message:String(l)}),l}}return r(a,c)}));let{getConfig:n}=await import('@smart-cloud/wpsuite-core'),s=await n("publisher"),o=s&&typeof s=="object"?s:null,u=k(o?.subscriptionType);return {remote:o,diagnostic:{status:o?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:u??null,error:o?null:"WP Suite publisher config loader returned no configuration.",requests:i}}}catch(n){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:n instanceof Error?n.message:String(n),requests:i}}}finally{typeof r=="function"&&(globalThis.fetch=r);}}function he(e,t){let r=ce(t?.deploymentProfiles),i=String(t?.defaultDeploymentProfile??"").trim(),n=r[i]?i:"",s=k(t?.subscriptionType),o=J(e.wpsuite);return {...e,scheduler:Q(t?.scheduler),deploymentProfiles:r,defaultDeploymentProfile:n,...s?{subscriptionType:s}:{},wpsuite:{...o,...o.siteSettings||s?{siteSettings:{...o.siteSettings??{},...o.siteSettings?.subscriber===true||s==="PROFESSIONAL"||s==="AGENCY"?{subscriber:true}:{}}}:{},...s?{subscriptionType:s}:{}}}}function x(e,t){let i=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!i)return t;let n=i.split("/").map(s=>s.trim()).filter(s=>s.length>0&&s!=="."&&s!=="..");return n.length>0?n.join("/"):t}function be(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?g.resolve(e):""}function L(e,t,r){let i=String(t||"").trim();return i&&g.isAbsolute(i)?g.resolve(i):g.resolve(e,x(i,r))}async function E(e,t={}){let r=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",i=await f.readFile(r,"utf8"),n=JSON.parse(i);n.sourceOrigin=n.sourceOrigin.replace(/\/$/,""),n.targetOrigin=W(n.targetOrigin),n.ignoreHttpsErrors??=false,n.outputDir=String(n.outputDir||"export").trim()||"export",n.urlRewriteMode||=n.targetOrigin==="."?"relative":"absolute",n.noJavaScriptRenderPathPrefixes||=[],n.seedPaths||=[],n.generated404RequestPath=ae(n.generated404RequestPath),n.sitemapPaths||=["/sitemap_index.xml","/sitemap.xml"],n.allowedAssetHosts||=[],n.assetPathPrefixes||=["/wp-content/","/wp-includes/","/static/","/assets/","/build/","/_next/","/docs/","/sitemap","/robots.txt","/llms.txt"],n.blockedPathPrefixes||=[],n.blockedSearchFragments||=[],n.concurrency||=1,n.maxPages||=0,n.extraReplacements=T(n.extraReplacements),n.postCrawlCopyMap=T(n.postCrawlCopyMap),n.logDir=String(n.logDir||"logs").trim()||"logs",n.verbose??=false,n.logLevel||=n.verbose?"debug":"info",n.s3SyncMode||="sdk-upload-delete",n.readiness||={waitForSelector:null,waitForFunction:null,timeoutMs:1500,fallbackWaitMs:1500},n.readiness.timeoutMs??=1500,n.readiness.fallbackWaitMs??=1500,n.viewport||={width:1440,height:1200},n.navigationTimeoutMs||=3e4,n.assetDownloadConcurrency=Number(n.assetDownloadConcurrency)>0?Number(n.assetDownloadConcurrency):n.concurrency,n.rewriteConcurrency=Number(n.rewriteConcurrency)>0?Number(n.rewriteConcurrency):n.assetDownloadConcurrency,n.wpsuite=J(n.wpsuite),n.scheduler=Q(void 0),n.deploymentProfiles={},n.defaultDeploymentProfile="",n.deploymentTargetOverride=String(n.deploymentTargetOverride??"").trim();let s=await fe(n);t.onRemotePublisherConfigDiagnostic?.(s.diagnostic);let o=he(n,s.remote),u=be(),a=u?g.resolve(u,".."):"";return a?(o.outputDir=L(a,o.outputDir,"export"),o.logDir=L(a,o.logDir,"logs")):(g.isAbsolute(o.outputDir)||(o.outputDir=x(o.outputDir,"export")),g.isAbsolute(o.logDir)||(o.logDir=x(o.logDir,"logs"))),o}function Y(e){let t=String(e.command??"").trim();return (t==="publish"||t==="crawl")&&e.crawlMode==="incremental"||t==="content-sync"}var j=new Map;async function _(e){let t=g.resolve(e),r=j.get(t);if(r!==void 0)return r;try{let i=JSON.parse(await f.readFile(t,"utf8")),n=String(i.version??"").trim();return j.set(t,n),n}catch{return j.set(t,""),""}}var D=class extends Error{request;step;constructor(t,r){super(`Stop requested during ${r}.`),this.name="StopRequestedError",this.request=t,this.step=r;}},Ce="queue-mutation.lock",Re=5e3,qe=3e4;function De(e){let t=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",r=process.env.STATIC_PUBLISHER_EXPORTER_DIR||process.cwd(),i=process.env.PUBLISHER_CONFIG||"",n=1;for(let u=0;u<e.length;u++){let a=e[u];a==="--runtime-dir"?t=e[++u]||"":a.startsWith("--runtime-dir=")?t=a.slice(14):a==="--exporter-dir"?r=e[++u]||r:a.startsWith("--exporter-dir=")?r=a.slice(15):a==="--config"?i=e[++u]||"":a.startsWith("--config=")?i=a.slice(9):a==="--max-jobs"?n=Number.parseInt(e[++u]||"1",10):a.startsWith("--max-jobs=")&&(n=Number.parseInt(a.slice(11),10));}if(!t)throw new Error("Missing runtime dir. Use --runtime-dir or STATIC_PUBLISHER_RUNTIME_DIR.");let s=g.resolve(t),o=i?g.resolve(i):g.join(s,"config.json");return {runtimeDir:s,exporterDir:g.resolve(r),configPath:o,maxJobs:Number.isFinite(n)&&n>0?n:1}}async function w(e,t){try{let r=await f.readFile(e,"utf8");return JSON.parse(r)}catch(r){if((r&&typeof r=="object"&&"code"in r?String(r.code||""):"")!=="ENOENT"){let n=r instanceof Error?r.message:String(r);console.warn(`[queue-runner] failed to read JSON ${e}: ${n}`);}return t}}async function y(e,t){await f.mkdir(g.dirname(e),{recursive:true}),await f.writeFile(e,JSON.stringify(t,null,2),"utf8");}function Z(e){return g.join(e,Ce)}async function Ie(e){await new Promise(t=>setTimeout(t,e));}async function Te(e){let t=Z(e),r=Date.now()+Re;for(;;)try{await f.mkdir(g.dirname(t),{recursive:!0}),await f.writeFile(t,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()},null,2),{encoding:"utf8",flag:"wx"});return}catch(i){if((i&&typeof i=="object"&&"code"in i?String(i.code||""):"")!=="EEXIST")throw i;let s=await f.stat(t).catch(()=>null);if(s&&Date.now()-s.mtimeMs>qe){await f.unlink(t).catch(()=>{});continue}if(Date.now()>=r)throw new Error("Timed out acquiring queue mutation lock.",{cause:i});await Ie(50);}}async function xe(e){await f.unlink(Z(e)).catch(()=>{});}async function I(e,t){await Te(e);try{return await t()}finally{await xe(e);}}function ke(e){return g.join(e,"queue-runner-heartbeat.json")}function B(e){return g.join(e,"current-progress.json")}function $(e){return g.join(e,"scheduler-state.json")}function Je(e,t){let i=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!i)return t;let n=i.split("/").map(s=>s.trim()).filter(s=>s.length>0&&s!=="."&&s!=="..");return n.length>0?n.join("/"):t}async function X(e){let t=await w(e.configPath||"",null),r=g.resolve(e.runtimeDir,".."),n=(typeof t?.logDir=="string"?t.logDir:"").trim();return n&&g.isAbsolute(n)?g.resolve(n):g.resolve(r,Je(n,"logs"))}function O(e,t){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||t}function Ee(e){let t=e?new Date(e):new Date;return (Number.isNaN(t.getTime())?new Date:t).toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function je(e){return [Ee(e.endedAt||e.startedAt),O(e.command||"job","job"),O(e.id||"job","job"),O(e.status||"finished","finished")].join("-")}function Oe(e){return e.endsWith(".log.jsonl")||e.endsWith(".errors.jsonl")||e.endsWith(".rejected.jsonl")?true:["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"].includes(e)}function Fe(e){return e==="errors.json"||e==="errors.jsonl"||e.endsWith(".errors.jsonl")?"errors":e==="ignored.json"||e==="ignored.jsonl"?"ignored":e==="rejected.json"||e==="rejected.jsonl"||e.endsWith(".rejected.jsonl")?"rejected":e==="skipped-http.json"||e==="skipped-http.jsonl"?"skipped-http":e==="timings.json"||e==="timings.jsonl"?"timings":e==="current-progress.json"?"current-progress":e==="current-crawl-event.json"?"current-crawl-event":e.endsWith(".log.jsonl")?e.replace(/\.log\.jsonl$/i,"-log"):e.replace(/\.[^.]+$/u,"")||"artifact"}function Me(e){return e.endsWith(".gz")?"application/gzip":e.endsWith(".jsonl")?"application/x-ndjson":e.endsWith(".json")?"application/json":"text/plain"}async function H(e,t,r){let i=`${r}.gz`,n=g.join(t,i);await pipeline(createReadStream(e),createGzip({level:9}),createWriteStream(n));let[s,o]=await Promise.all([f.stat(e),f.stat(n)]);return {role:Fe(r),originalFileName:r,storedFileName:i,compressed:true,compression:"gzip",contentType:Me(i),originalSize:s.size,storedSize:o.size}}async function G(e,t){let r=await X(t),i=new Date().toISOString(),n=je(e),s=g.join(r,"archive",n),o=[],u=[];await f.mkdir(s,{recursive:true});try{let d=await f.readdir(r,{withFileTypes:!0});for(let p of d){if(!p.isFile()||!Oe(p.name))continue;let l=await H(g.join(r,p.name),s,p.name);u.push(l),o.push(l.storedFileName);}}catch(d){if((d&&typeof d=="object"&&"code"in d?String(d.code||""):"")!=="ENOENT")throw d}let a=B(t.runtimeDir);if(existsSync(a)){let d=await H(a,s,"current-progress.json");u.push(d),o.push(d.storedFileName);}let c=[...o,"job.json"];return await y(g.join(s,"job.json"),{manifestVersion:1,archivedAt:i,archiveKey:n,archiveDir:s,logDir:r,runtimeDir:t.runtimeDir,exporterDir:t.exporterDir,configPath:t.configPath||"",archivedFiles:c,artifacts:u,job:e}),{archiveKey:n,archiveDir:s,archiveCreatedAt:i,archivedFiles:c,artifacts:u}}function Be(e){return g.join(e,"audit-events.jsonl")}function F(e){return g.join(e,"stop-request.json")}async function ee(e){try{let t=await f.readFile(F(e),"utf8"),r=JSON.parse(t);return r&&typeof r=="object"?r:null}catch{return null}}async function K(e,t){let r=await ee(e);if(!r)return null;let i=String(r.targetJobId||"").trim();return i&&i!==t?null:r}async function M(e,t){if(!t){await f.unlink(F(e)).catch(()=>{});return}let r=await ee(e);if(!r)return;let i=String(r.targetJobId||"").trim();(!i||i===t)&&await f.unlink(F(e)).catch(()=>{});}async function R(e,t){try{let r={occurredAt:t.occurredAt||new Date().toISOString(),status:t.status||"info",actorSource:t.actorSource||"queue-runner",...t};await f.mkdir(e,{recursive:!0}),await f.appendFile(Be(e),`${JSON.stringify(r)}
2
- `,"utf8");}catch{}}async function b(e,t,r){let[i,n]=await Promise.all([_(g.join(e.exporterDir,"package.json")),_(g.join(e.exporterDir,"node_modules","@smart-cloud","wpsuite-core","package.json"))]),s={checkedAt:new Date().toISOString(),status:t,pid:process.pid,nodePath:process.execPath,nodeVersion:process.version,exporterVersion:i,wpsuiteCoreVersion:n,runtimeDir:e.runtimeDir,exporterDir:e.exporterDir,...r??{}};try{await y(ke(e.runtimeDir),s);}catch{}}async function q(e){try{await f.unlink(B(e));}catch{}}function Ue(e,t){let r=e.command;if(r!=="publish"&&r!=="crawl"&&r!=="deploy"&&r!=="invalidate"&&r!=="retry-timeouts"&&r!=="url")return null;let i=Number.parseInt(String(e.intervalMinutes??"0"),10);if(!Number.isFinite(i)||i<1)return null;let n=(e.id||`${r}-${t+1}`).trim();if(!n)return null;let s=e.enabled!==false,o=typeof e.url=="string"?e.url.trim():"",u=typeof e.deploymentProfile=="string"?e.deploymentProfile.trim():"",a=Array.isArray(e.postTypes)?[...new Set(e.postTypes.map(p=>String(p).trim()).filter(Boolean))]:[],c=Array.isArray(e.listingPaths)?[...new Set(e.listingPaths.map(p=>String(p).trim()).filter(Boolean))]:[],d=(r==="publish"||r==="crawl")&&e.crawlMode==="incremental"?"incremental":"full";return r==="url"&&!o?null:{id:n,enabled:s,command:r,intervalMinutes:i,...r==="publish"||r==="crawl"?{crawlMode:d}:{},...(r==="publish"||r==="deploy"||r==="invalidate")&&u?{deploymentProfile:u}:{},...o?{url:o}:{},...a.length>0?{postTypes:a}:{},...c.length>0?{listingPaths:c}:{},...typeof e.includePostTypeArchives=="boolean"?{includePostTypeArchives:e.includePostTypeArchives}:{},...typeof e.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:e.includeTaxonomyArchives}:{},...typeof e.includeAuthorArchives=="boolean"?{includeAuthorArchives:e.includeAuthorArchives}:{},...typeof e.includeDateArchives=="boolean"?{includeDateArchives:e.includeDateArchives}:{},...typeof e.includePostsPage=="boolean"?{includePostsPage:e.includePostsPage}:{},...typeof e.includeSitemapChain=="boolean"?{includeSitemapChain:e.includeSitemapChain}:{}}}async function Le(e){let t=await E(e.configPath).catch(()=>null),r=t?.scheduler,i=Array.isArray(r?.rules)?r.rules.map((n,s)=>Ue(n,s)).filter(n=>!!n):[];return {enabled:!!r?.enabled,timezone:typeof r?.timezone=="string"&&r.timezone.trim()?r.timezone.trim():"UTC",rules:i,wpsuite:t?.wpsuite}}function We(e,t){let r=(t.url||"").trim(),i=t.crawlMode||"full",n=(t.deploymentProfile||"").trim();return e.some(s=>s.command===t.command&&(s.url||"").trim()===r&&(s.crawlMode||"full")===i&&(s.deploymentProfile||"").trim()===n&&(s.status===void 0||s.status==="queued"||s.status==="running"))}async function Qe(e,t){if(!t.allowSchedulerAutoEnqueue)return 0;let r=await Le(e);if(!r.enabled||r.rules.length===0)return 0;if(t.assertActiveSubscriptionForIdentity)try{await t.assertActiveSubscriptionForIdentity(r.wpsuite??null);}catch(a){let c=a instanceof Error?a.message:String(a);return console.warn(`[queue-runner] scheduler auto-enqueue skipped: ${c}`),0}let i=g.join(e.runtimeDir,"queue.json"),n=g.join(e.runtimeDir,"current-run.json"),s=Date.now(),o=0,u=[];await I(e.runtimeDir,async()=>{let a=await w(i,[]),c=await w(n,null),d=await w($(e.runtimeDir),{lastEnqueuedBucketByRuleId:{}}),p=[...a];c&&c.status==="running"&&p.unshift(c);for(let l of r.rules){if(!l.enabled)continue;let m=l.intervalMinutes*60*1e3,h=Math.floor(s/m),P=d.lastEnqueuedBucketByRuleId[l.id]??-1;if(h<=P||We(p,{command:l.command,url:l.url,crawlMode:l.crawlMode,deploymentProfile:l.deploymentProfile}))continue;let S={id:randomUUID(),command:l.command,...(l.command==="publish"||l.command==="crawl")&&l.crawlMode?{crawlMode:l.crawlMode}:{},...(l.command==="publish"||l.command==="deploy"||l.command==="invalidate")&&l.deploymentProfile?{deploymentProfile:l.deploymentProfile}:{},...l.url?{url:l.url}:{},enqueueSource:"scheduler",...r.wpsuite?{wpsuite:r.wpsuite}:{},status:"queued",createdAt:new Date().toISOString(),createdBy:0};a.push(S),p.push(S),u.push({job:S,rule:l}),d.lastEnqueuedBucketByRuleId[l.id]=h,o+=1;}o>0&&(await y(i,a),await y($(e.runtimeDir),d));});for(let a of u)await R(e.runtimeDir,{eventType:"job-created",status:"queued",actorSource:"queue-runner-scheduler",jobId:a.job.id,command:a.job.command,message:"Scheduler auto-enqueued a job.",details:{ruleId:a.rule.id,intervalMinutes:a.rule.intervalMinutes,timezone:r.timezone,deploymentProfile:a.rule.deploymentProfile||"",url:a.rule.url||""}});return o}async function ze(e){let t={pid:process.pid,startedAt:new Date().toISOString()};await f.writeFile(e,JSON.stringify(t,null,2),{encoding:"utf8",flag:"wx"});}async function Ne(e){try{await f.unlink(e);}catch{}}function _e(e,t){let r=[g.join(e,"dist",`${t}.js`),g.join(e,`${t}.js`)];for(let i of r)if(existsSync(i))return i;throw new Error(`Cannot find ${t}.js in ${g.join(e,"dist")} or ${e}`)}async function A(e,t,r,i,n,s,o){if(o){let c=await K(t,o);if(c)throw new D(c,r)}let u=_e(e,r),a={...process.env,...s??{}};return a.STATIC_PUBLISHER_RUNTIME_DIR=t,n&&(a.PUBLISHER_CONFIG=n),await new Promise((c,d)=>{let p=null,l=null,m=null,h=false,P=spawn(process.execPath,[u,...i],{cwd:e,env:a,stdio:"inherit"}),S=()=>{l&&clearInterval(l),m&&clearTimeout(m);},ie=async()=>{if(!(!o||p||h)){h=true;try{let C=await K(t,o);if(!C)return;p=C,P.kill("SIGTERM"),m=setTimeout(()=>{P.kill("SIGKILL");},1e4);}finally{h=false;}}};o&&(l=setInterval(()=>{ie();},1e3)),P.on("error",C=>{S(),d(C);}),P.on("close",(C,U)=>{if(S(),p){d(new D(p,r));return}C===0?c():d(new Error(`${r} exited with code ${C??-1}${U?` (signal ${U})`:""}`));});}),0}function $e(e){let t=e.awsTempCreds;if(!t)return {};let r={};return typeof t.accessKeyId=="string"&&t.accessKeyId.trim()!==""&&(r.AWS_ACCESS_KEY_ID=t.accessKeyId.trim()),typeof t.secretAccessKey=="string"&&t.secretAccessKey.trim()!==""&&(r.AWS_SECRET_ACCESS_KEY=t.secretAccessKey.trim()),typeof t.sessionToken=="string"&&t.sessionToken.trim()!==""&&(r.AWS_SESSION_TOKEN=t.sessionToken.trim()),r}async function He(e,t){let r=o=>{if(!o||typeof o!="object")return null;let u=o,a={...u.siteSettings??{},...String(u.accountId??"").trim()&&!u.siteSettings?.accountId?{accountId:String(u.accountId).trim()}:{},...String(u.siteId??"").trim()&&!u.siteSettings?.siteId?{siteId:String(u.siteId).trim()}:{},...u.siteSettings?.subscriber===true||u.subscriber===true?{subscriber:true}:{}},c={...String(u.apiBase??"").trim()?{apiBase:String(u.apiBase).trim()}:{},...String(u.runtimeToken??u.nonce??"").trim()?{runtimeToken:String(u.runtimeToken??u.nonce).trim()}:{},...String(u.virtualAssetBaseUrl??u.uploadUrl??"").trim()?{virtualAssetBaseUrl:String(u.virtualAssetBaseUrl??u.uploadUrl).trim()}:{},...Object.keys(a).length>0?{siteSettings:a}:{},...u.subscriptionType?{subscriptionType:u.subscriptionType}:{}};return Object.keys(c).length>0?c:null},i=await E(t.configPath).catch(()=>null),n=r(i?.wpsuite);if(n)return n;let s=r(e.wpsuite);return s||null}async function Ge(e,t){return await He(e,t)}function te(e){let t={...e,status:"queued"};return delete t.startedAt,delete t.endedAt,delete t.exitCode,delete t.error,delete t.stopRequestedAt,delete t.stopRequestedByUserId,delete t.stopRequestedByLogin,delete t.stopMode,delete t.stoppedStep,t}async function Ke(e,t){let r=await w(B(e.runtimeDir),null),i=r&&r.details&&typeof r.details.phase=="string"?r.details.phase.trim():"";if(i)return i;let n=r&&typeof r.currentStep=="string"?r.currentStep.trim():"";if(n)return n;let s=await X(e).catch(()=>"");if(s){let o=await w(g.join(s,"current-crawl-event.json"),null),u=o&&typeof o.currentStep=="string"?o.currentStep.trim():"";if(u)return u}return t}function Ve(e,t){if((e.command==="publish"||e.command==="crawl")&&t==="rewrite-text")return "rewrite-text"}async function Ye(e){let t=g.join(e.runtimeDir,"queue.json"),r=g.join(e.runtimeDir,"current-run.json"),i=await I(e.runtimeDir,async()=>{let n=await w(r,null);if(!n||n.status!=="running"&&n.status!=="queued")return null;let s=await w(t,[]),o=Array.isArray(s)?s.filter(a=>a?.id!==n.id):[],u=te(n);return await y(t,[u,...o]),await y(r,null),u});i&&(await M(e.runtimeDir,i.id),await R(e.runtimeDir,{eventType:"job-recovered",status:"queued",actorSource:"queue-runner",jobId:i.id,command:i.command,message:"Recovered stale current-run entry back into queue."}));}async function Ze(e,t,r){try{if((r.shouldEnforceSubscriptionOnJobExecution?.(e)??r.enforceSubscriptionOnJobExecution)&&r.assertActiveSubscriptionForIdentity){let u=await Ge(e,t);await r.assertActiveSubscriptionForIdentity(u);}let n=$e(e),s=e.resumeFromStep==="rewrite-text"?["--resume-rewrite"]:e.crawlMode==="incremental"?["--crawl-mode","incremental"]:[],o=e.deploymentProfile?["--profile",e.deploymentProfile]:[];if(e.command==="publish")return await b(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:e.resumeFromStep==="rewrite-text"?"rewrite-text":"crawl"}),await A(t.exporterDir,t.runtimeDir,"crawl",s,t.configPath,n,e.id),await b(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"deploy"}),await A(t.exporterDir,t.runtimeDir,"deploy",o,t.configPath,n,e.id),await b(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"invalidate"}),await A(t.exporterDir,t.runtimeDir,"invalidate",o,t.configPath,n,e.id),{exitCode:0};if(e.command==="crawl")return await b(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:e.resumeFromStep==="rewrite-text"?"rewrite-text":"crawl"}),await A(t.exporterDir,t.runtimeDir,"crawl",s,t.configPath,n,e.id),{exitCode:0};if(e.command==="deploy")return await b(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"deploy"}),await A(t.exporterDir,t.runtimeDir,"deploy",o,t.configPath,n,e.id),{exitCode:0};if(e.command==="invalidate")return await b(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"invalidate"}),await A(t.exporterDir,t.runtimeDir,"invalidate",o,t.configPath,n,e.id),{exitCode:0};if(e.command==="retry-timeouts")return await b(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"retry-timeouts"}),await A(t.exporterDir,t.runtimeDir,"crawl",["--retry-timeouts"],t.configPath,n,e.id),{exitCode:0};if(e.command==="url"){let u=(e.url||"").trim();return u?(await b(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"url"}),await A(t.exporterDir,t.runtimeDir,"crawl",["--url",u],t.configPath,n,e.id),{exitCode:0}):{exitCode:2,error:"Missing url for command 'url'"}}return {exitCode:2,error:`Unsupported command: ${e.command}`}}catch(i){return i instanceof D?{exitCode:130,error:"Job stop requested.",stopped:true,stopRequest:i.request,stoppedStep:i.step}:{exitCode:1,error:i instanceof Error?i.message:String(i)}}}function re(e){return async function(r=process.argv.slice(2)){let i=De(r),n=g.join(i.runtimeDir,"export.lock"),s=g.join(i.runtimeDir,"last-run.json");await q(i.runtimeDir),await b(i,"starting",{message:"queue-runner starting"});try{await ze(n);}catch(o){if((o&&typeof o=="object"&&"code"in o?String(o.code||""):"")!=="EEXIST")throw o;console.log("[queue-runner] lock active, skipping"),await b(i,"lock-active",{message:"lock active, skipped this cron tick"});return}try{await Ye(i);let o=await Qe(i,e),u=0;for(let a=0;a<i.maxJobs;a++){let c=await et(i,e);if(c==="none"||(u+=1,c==="stopped"))break}if(u===0)await q(i.runtimeDir),await b(i,"idle",{processedJobs:u,schedulerEnqueued:o,message:"no queued jobs"});else {await q(i.runtimeDir);let a=await w(s,null),c=String(a?.status||"").trim();await b(i,c==="success"?"job-success":c==="stopped"?"job-stopped":"job-failed",{processedJobs:u,schedulerEnqueued:o,lastJobId:a?.id,lastJobCommand:a?.command,lastJobStatus:a?.status,lastJobExitCode:a?.exitCode,lastJobError:a?.error,...c==="stopped"?{currentStep:a?.stoppedStep,stopRequestedAt:a?.stopRequestedAt,stopRequestedByLogin:a?.stopRequestedByLogin,stopRequestedMode:a?.stopMode,lastStoppedStep:a?.stoppedStep,message:a?.stopMode==="requeue"?`Job stopped during ${a?.stoppedStep||a?.command||"active step"} and requeued.`:`Job stopped during ${a?.stoppedStep||a?.command||"active step"} and left out of queue.`}:{}});}}catch(o){let u=o instanceof Error?o.message:String(o);throw await b(i,"error",{message:u}),await R(i.runtimeDir,{eventType:"queue-runner-error",status:"failed",actorSource:"queue-runner",message:"Unhandled queue-runner error.",details:{error:u}}),o}finally{await Ne(n);}}}async function Xe(e,t,r){let i=g.join(e.runtimeDir,"queue.json"),n=g.join(e.runtimeDir,"current-run.json");await I(e.runtimeDir,async()=>{let s=await w(i,[]),o=Array.isArray(s)?s.filter(c=>c?.id!==t.id):[],u=te(t),a=Ve(t,r);a?u.resumeFromStep=a:delete u.resumeFromStep,await y(i,[u,...o]),await y(n,null);});}async function et(e,t){let r=g.join(e.runtimeDir,"queue.json"),i=g.join(e.runtimeDir,"current-run.json"),n=g.join(e.runtimeDir,"last-run.json"),s=new Date().toISOString(),o=await I(e.runtimeDir,async()=>{let p=await w(r,[]);if(!Array.isArray(p)||p.length===0)return null;let l={...p[0],status:"running",startedAt:s};return await y(r,p.slice(1)),await y(i,l),l});if(!o)return "none";await q(e.runtimeDir),await R(e.runtimeDir,{eventType:"job-run-started",status:"running",actorSource:"queue-runner",jobId:o.id,command:o.command,message:"Job execution started.",details:{createdAt:o.createdAt||"",startedAt:s,createdBy:o.createdBy??null,deploymentProfile:o.deploymentProfile||"",queuedWithTempAwsCreds:!!o.awsTempCreds}}),await b(e,"running",{currentJobId:o.id,currentJobCommand:o.command,currentStep:o.command});let u=await Ze(o,e,t),a=new Date().toISOString();if(u.stopped){let p=await Ke(e,u.stoppedStep||o.command),l=u.stopRequest?.mode==="requeue"?"requeue":"stop",m={...o,status:"stopped",endedAt:a,exitCode:u.exitCode,...u.error?{error:u.error}:{},stopRequestedAt:u.stopRequest?.requestedAt||"",stopRequestedByUserId:typeof u.stopRequest?.requestedByUserId=="number"?u.stopRequest.requestedByUserId:null,stopRequestedByLogin:u.stopRequest?.requestedByLogin||"",stopMode:l,stoppedStep:p};l==="requeue"?await Xe(e,o,p):await y(i,null);try{let h=await G(m,e);m.logArchiveDir=h.archiveDir,m.logArchiveCreatedAt=h.archiveCreatedAt,m.logArchiveFileCount=h.archivedFiles.length;}catch(h){m.logArchiveError=h instanceof Error?h.message:String(h);}return await y(n,m),await M(e.runtimeDir,o.id),await q(e.runtimeDir),await R(e.runtimeDir,{eventType:"job-run-stopped",status:"stopped",actorSource:"queue-runner",jobId:o.id,command:o.command,message:l==="requeue"?"Job stop requested and requeued.":"Job stop requested and removed from active execution without requeue.",details:{startedAt:o.startedAt||"",endedAt:a,deploymentProfile:o.deploymentProfile||"",stopMode:l,stopRequestedAt:u.stopRequest?.requestedAt||"",stopRequestedByLogin:u.stopRequest?.requestedByLogin||"",stopRequestedByUserId:typeof u.stopRequest?.requestedByUserId=="number"?u.stopRequest.requestedByUserId:null,stoppedStep:p,logArchiveKey:m.logArchiveError||!m.logArchiveDir?"":g.basename(m.logArchiveDir),logArchiveDir:m.logArchiveDir||"",logArchiveCreatedAt:m.logArchiveCreatedAt||"",logArchiveFileCount:m.logArchiveFileCount??0,logArchiveError:m.logArchiveError||""}}),"stopped"}let c={...o,status:u.exitCode===0?"success":"failed",endedAt:a,exitCode:u.exitCode,...u.error?{error:u.error}:{}};await y(i,null),await M(e.runtimeDir,o.id);try{let p=await G(c,e);c.logArchiveDir=p.archiveDir,c.logArchiveCreatedAt=p.archiveCreatedAt,c.logArchiveFileCount=p.archivedFiles.length;}catch(p){c.logArchiveError=p instanceof Error?p.message:String(p);}await y(n,c);let d=o.startedAt&&c.endedAt?Math.max(0,Math.round((new Date(c.endedAt).getTime()-new Date(o.startedAt).getTime())/1e3)):void 0;return await R(e.runtimeDir,{eventType:"job-run-finished",status:c.status==="success"?"success":"failed",actorSource:"queue-runner",jobId:c.id,command:c.command,message:c.status==="success"?"Job execution finished successfully.":"Job execution finished with failure.",details:{startedAt:o.startedAt||"",endedAt:c.endedAt||"",durationSec:d,deploymentProfile:c.deploymentProfile||"",exitCode:c.exitCode??null,error:c.error||"",logArchiveKey:c.logArchiveError||!c.logArchiveDir?"":g.basename(c.logArchiveDir),logArchiveDir:c.logArchiveDir||"",logArchiveCreatedAt:c.logArchiveCreatedAt||"",logArchiveFileCount:c.logArchiveFileCount??0,logArchiveError:c.logArchiveError||""}}),"processed"}async function rt(e){if(!e)throw new Error("Missing remote WPSuite publisher state. Refresh the runtime config before running subscription-gated jobs.");if(e.subscriptionType!=="PROFESSIONAL"&&e.subscriptionType!=="AGENCY")throw new Error("This job requires an active WPSuite publisher subscription in the remote site configuration.")}var nt={allowSchedulerAutoEnqueue:true,enforceSubscriptionOnJobExecution:false,shouldEnforceSubscriptionOnJobExecution:e=>Y(e)||e.enqueueSource==="scheduler"||e.createdBy===0,assertActiveSubscriptionForIdentity:rt},ne=re(nt),it=ne,Pt=ne;process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href&&it().catch(e=>{console.error(e),process.exit(1);});export{Pt as default,it as main,ne as runQueueRunner};
1
+ import {pathToFileURL}from'url';import w from'fs/promises';import {existsSync,createReadStream,createWriteStream}from'fs';import g from'path';import {spawn}from'child_process';import {randomUUID,createHash}from'crypto';import De from'http';import se from'https';import {pipeline}from'stream/promises';import {createGzip}from'zlib';function re(e){return [...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function U(e){return Array.isArray(e)?e.map(U):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,U(n)])):e}function qe(e){return JSON.stringify(U(e))}function F(e){return createHash("sha256").update(qe(e)).digest("hex")}function xe(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 J(e){let t=re((e.postTypes??[]).map(i=>String(i).toLowerCase().replace(/[^a-z0-9_-]/g,"")));if(t.length===0)throw new Error("Content-sync requires at least one public post type.");let n=re((e.listingPaths??[]).map(i=>{let r=String(i).trim();if(!r)return "";let u=new URL(r,"https://content-sync.invalid/");if(u.origin!=="https://content-sync.invalid"&&/^https?:\/\//i.test(r))throw new Error("Content-sync listing routes must be same-site paths.");let o=`/${u.pathname.replace(/^\/+|\/+$/g,"")}`;return o==="/"?"/":`${o}/`}));return {postTypes:t,listingPaths:n,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 ie(e,t,n){return F({schemaVersion:1,sourceOrigin:xe(e),ruleId:t.trim(),scope:J(n)})}function oe(e){return F({schemaVersion:1,...e})}var Te="wp-json/smartcloud-static-publisher/v1/content-sync/",ke=25*1024*1024,D=class extends Error{status;code;constructor(t,n,i){super(i),this.name="ContentSyncApiError",this.status=t,this.code=n;}},O=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(`${Te}${t}`,n)}async post(t,n){let i=this.endpoint(t),r=Buffer.from(JSON.stringify(n),"utf8"),u=i.protocol==="https:"?se:De,o=i.protocol==="https:"?new se.Agent({rejectUnauthorized:!this.options.ignoreHttpsErrors}):void 0;return new Promise((s,a)=>{let c=u.request(i,{method:"POST",agent:o,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",h=>{if(p+=h.byteLength,p>ke){l.destroy(new Error("Content-sync API response exceeded the size limit."));return}d.push(h);}),l.on("error",a),l.on("end",()=>{let h=Buffer.concat(d).toString("utf8"),m;try{m=h?JSON.parse(h):{};}catch{a(new D(l.statusCode??500,"invalid-json","Content-sync API returned invalid JSON."));return}let b=l.statusCode??500;if(b<200||b>=300){a(new D(b,String(m.code??"request-failed"),String(m.message??`Content-sync API request failed (${b}).`)));return}s(m);});});c.on("timeout",()=>c.destroy(new Error(`Content-sync API request timed out: ${t}`))),c.on("error",a),c.end(r);})}async head(t){return this.post("head",t)}async unboundHead(t){return this.post("head",{postTypes:t})}async events(t){let n=[],i=t.afterSequence,r=new Set(t.postTypes);for(;i<t.throughSequence;){let u=await this.post("events",{...t,afterSequence:i,limit:250});if(u.fromSequence!==i||u.throughSequence!==t.throughSequence||u.nextSequence<i||u.nextSequence>t.throughSequence)throw new Error("Content-sync API returned an inconsistent event page.");if(!Array.isArray(u.items))throw new Error("Content-sync API returned a malformed event page.");let o=i;for(let s of u.items){if(!Number.isSafeInteger(s.sequence)||s.sequence<=o||s.sequence>t.throughSequence||!Number.isSafeInteger(s.postId)||s.postId<=0||!r.has(s.postType)||typeof s.operation!="string"||!s.operation)throw new Error("Content-sync API returned an invalid or out-of-scope journal event.");o=s.sequence;}if(u.items.length>0&&u.nextSequence!==o)throw new Error("Content-sync API event cursor does not match the final returned event.");if(n.push(...u.items),!u.hasMore)break;if(u.nextSequence===i)throw new Error("Content-sync API event pagination did not advance.");i=u.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){let n=await this.post("impact",{families:t});return Array.isArray(n.families)?n.families:[]}async releaseFingerprint(){let t=await this.post("fingerprint",{}),n=String(t.fingerprint||"").trim();if(!/^[a-f0-9]{64}$/.test(n))throw new Error("WordPress returned an invalid release fingerprint.");return n}async establishBaseline(t){return this.post("baseline",t)}async acknowledge(t){return this.post("ack",t)}};function Ee(e){return typeof e.subscriptionType=="string"&&e.subscriptionType.trim()!==""}function Fe(e,t){return {...e,...t??{}}}function Je(e,t){return {...e,...t??{},invalidationPaths:[...(t?.invalidationPaths??e.invalidationPaths)||[]]}}function ue(e,t){let n=String(t??e.deploymentTargetOverride??"").trim();if(!Ee(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 i=String(n||e.defaultDeploymentProfile||"").trim();if(!i)return {name:null,profile:null,config:e};let r=e.deploymentProfiles?.[i];if(!r)throw new Error(`Unknown deployment profile "${i}". Check the linked WPSuite publisher configuration.`);return {name:i,profile:r,config:{...e,targetOrigin:r.targetOrigin??e.targetOrigin,s3:Fe(e.s3,r.s3),cloudFront:Je(e.cloudFront,r.cloudFront)}}}function ce(e){let t=e.trim();return t==="."?".":t.replace(/\/$/,"")}function Me(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 i=n.endsWith("/"),r=n.replace(/^\/+/,"").split("/").map(o=>o.replace(/[^A-Za-z0-9._-]/g,"")).filter(o=>o.length>0&&o!=="."&&o!=="..");if(r.length===0)return "";let u=`/${r.join("/")}`;return i&&g.extname(u)===""&&(u+="/"),u==="/"?"":u}function L(e){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).map(([t,n])=>[t.trim(),String(n??"")]).filter(([t])=>t.length>0))}function Ue(e){if(!e||typeof e!="object")return {};let t={};for(let[n,i]of Object.entries(e)){let r=n.trim();if(!r||!i||typeof i!="object")continue;let u=i,o={};if(typeof u.targetOrigin=="string"){let a=ce(u.targetOrigin);a&&(o.targetOrigin=a);}let s=L(u.extraReplacements);if(Object.keys(s).length>0&&(o.extraReplacements=s),u.s3&&typeof u.s3=="object"){let a={},c=u.s3;typeof c.bucket=="string"&&(a.bucket=c.bucket.trim()),typeof c.prefix=="string"&&(a.prefix=c.prefix.trim()),typeof c.region=="string"&&(a.region=c.region.trim()),typeof c.htmlCacheControl=="string"&&(a.htmlCacheControl=c.htmlCacheControl.trim()),typeof c.assetCacheControl=="string"&&(a.assetCacheControl=c.assetCacheControl.trim()),Object.keys(a).length>0&&(o.s3=a);}if(u.cloudFront&&typeof u.cloudFront=="object"){let a={},c=u.cloudFront;typeof c.distributionId=="string"&&(a.distributionId=c.distributionId.trim()),Array.isArray(c.invalidationPaths)&&(a.invalidationPaths=c.invalidationPaths.map(l=>String(l??"").trim()).filter(l=>l.length>0)),Object.keys(a).length>0&&(o.cloudFront=a);}t[r]=o;}return t}function Q(e){return e==="PROFESSIONAL"||e==="AGENCY"?e:void 0}function Le(e,t){if(!e||typeof e!="object")return null;let n=e,i=n.command;if(i!=="publish"&&i!=="crawl"&&i!=="deploy"&&i!=="invalidate"&&i!=="retry-timeouts"&&i!=="url"&&i!=="content-sync")return null;let r=Number.parseInt(String(n.intervalMinutes??"0"),10);if(!Number.isFinite(r)||r<1)return null;let u=String(n.id??`${i}-${t+1}`).trim();if(!u)return null;let o=String(n.deploymentProfile??"").trim(),s=String(n.url??"").trim(),a=Array.isArray(n.postTypes)?[...new Set(n.postTypes.map(l=>String(l??"").trim().toLowerCase().replace(/[^a-z0-9_-]/g,"")).filter(Boolean))]:[],c=Array.isArray(n.listingPaths)?[...new Set(n.listingPaths.map(l=>String(l??"").trim()).filter(Boolean))]:[];return i==="content-sync"&&a.length===0?null:{id:u,enabled:n.enabled!==false,command:i,intervalMinutes:r,...i==="publish"||i==="crawl"?{crawlMode:n.crawlMode==="incremental"?"incremental":"full"}:{},...(i==="publish"||i==="deploy"||i==="invalidate"||i==="content-sync")&&o?{deploymentProfile:o}:{},...s?{url:s}:{},...a.length>0?{postTypes:a}:{},...c.length>0?{listingPaths:c}:{},...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 le(e){let t=e&&typeof e=="object"?e:{},n=Array.isArray(t.rules)?t.rules.map((i,r)=>Le(i,r)).filter(i=>!!i):[];return {enabled:t.enabled===true,timezone:typeof t.timezone=="string"&&t.timezone.trim()!==""?t.timezone.trim():"UTC",rules:n}}function We(e){if(!e||typeof e!="object")return;let t=e,n={};for(let r of ["accountId","siteId"]){let u=t[r];typeof u=="string"&&u.trim()!==""&&(n[r]=u.trim());}let i=Number(t.lastUpdate??0);return Number.isFinite(i)&&i>0&&(n.lastUpdate=Math.floor(i)),t.subscriber===true&&(n.subscriber=true),Object.keys(n).length>0?n:void 0}function $(e){let t=e&&typeof e=="object"?e:{},n=String(t.accountId??"").trim(),i=String(t.siteId??"").trim(),r=t.subscriber===true,u=We(t.siteSettings),o={...u??{},...n?{accountId:u?.accountId??n}:{},...i?{siteId:u?.siteId??i}:{},...u?.subscriber===true||r?{subscriber:true}:{}},s={},a=String(t.apiBase??"").trim();a&&(s.apiBase=a);let c=String(t.runtimeToken??t.nonce??"").trim();c&&(s.runtimeToken=c);let l=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();l&&(s.virtualAssetBaseUrl=l),Object.keys(o).length>0&&(s.siteSettings=o);let d=Q(t.subscriptionType);return d&&(s.subscriptionType=d),s}function Qe(e){try{let t=new URL(e);globalThis.location=t;}catch{}}function de(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}function $e(e,t){let n=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers)for(let[i,r]of new Headers(t.headers).entries())n.set(i,r);return n}async function me(e,t,n=5){let i=new URL(de(e)),r=String(t?.method??(e instanceof Request?e.method:"GET")).toUpperCase(),u=i.protocol==="http:"?De:se,o=$e(e,t);return await new Promise((s,a)=>{let c=u.request(i,{method:r,headers:Object.fromEntries(o.entries()),...i.protocol==="https:"?{rejectUnauthorized:false}:{}},l=>{let d=[];l.on("data",p=>{d.push(Buffer.isBuffer(p)?p:Buffer.from(p));}),l.on("error",a),l.on("end",()=>{let p=l.statusCode??0,h=l.headers.location;if(n>0&&h&&[301,302,303,307,308].includes(p)){s(me(new URL(h,i),{method:p===303?"GET":r},n-1));return}let m=new Headers;for(let[b,y]of Object.entries(l.headers))Array.isArray(y)?m.set(b,y.join(", ")):typeof y=="string"&&m.set(b,y);s(new Response(Buffer.concat(d),{status:p,statusText:l.statusMessage??"",headers:m}));});});c.on("error",a),c.end();})}function Ne(e){let t=$(e.wpsuite),n={...t.siteSettings??{},...t.siteSettings?.subscriber===true||t.subscriptionType==="PROFESSIONAL"||t.subscriptionType==="AGENCY"?{subscriber:true}:{}},i=String(n.accountId??"").trim(),r=String(n.siteId??"").trim(),u=String(t.virtualAssetBaseUrl??t.uploadUrl??"").trim();if(e.wpsuite={...t.apiBase?{apiBase:t.apiBase}:{},...t.runtimeToken?{runtimeToken:t.runtimeToken}:{},...u?{virtualAssetBaseUrl:u}:{},...Object.keys(n).length>0?{siteSettings:n}:{},...t.subscriptionType?{subscriptionType:t.subscriptionType}:{}},!i||!r||!u)return false;Qe(e.sourceOrigin);let o=globalThis,a={...o.WpSuite??{},siteSettings:n,uploadUrl:u};return t.apiBase&&(a.apiBase=t.apiBase),o.WpSuite=a,true}async function ze(e){let t=String(e.wpsuite?.virtualAssetBaseUrl??e.wpsuite?.uploadUrl??"").trim();if(!Ne(e)){let r=e.wpsuite?.siteSettings,u=[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): ${u.join(", ")}.`,requests:[]}}}let n=globalThis.fetch,i=[];try{typeof n=="function"&&/^https?:\/\//i.test(t)&&(globalThis.fetch=(async(a,c)=>{let l=de(a);if(l.startsWith(t)){let d=(()=>{try{return new URL(l).pathname}catch{return l}})();try{let p=e.ignoreHttpsErrors&&l.startsWith("https://")?await me(a,c):await n(a,c);return i.push({path:d,status:p.status,ok:p.ok,error:null}),p}catch(p){throw i.push({path:d,status:null,ok:!1,error:p instanceof Error?p.message:String(p)}),p}}return n(a,c)}));let{getConfig:r}=await import('@smart-cloud/wpsuite-core'),u=await r("publisher"),o=u&&typeof u=="object"?u:null,s=Q(o?.subscriptionType);return {remote:o,diagnostic:{status:o?"loaded":"unavailable",virtualAssetBaseUrl:t,subscriptionType:s??null,error:o?null:"WP Suite publisher config loader returned no configuration.",requests:i}}}catch(r){return {remote:null,diagnostic:{status:"unavailable",virtualAssetBaseUrl:t,subscriptionType:null,error:r instanceof Error?r.message:String(r),requests:i}}}finally{typeof n=="function"&&(globalThis.fetch=n);}}function Ke(e,t){let n=Ue(t?.deploymentProfiles),i=String(t?.defaultDeploymentProfile??"").trim(),r=n[i]?i:"",u=Q(t?.subscriptionType),o=$(e.wpsuite);return {...e,scheduler:le(t?.scheduler),deploymentProfiles:n,defaultDeploymentProfile:r,...u?{subscriptionType:u}:{},wpsuite:{...o,...o.siteSettings||u?{siteSettings:{...o.siteSettings??{},...o.siteSettings?.subscriber===true||u==="PROFESSIONAL"||u==="AGENCY"?{subscriber:true}:{}}}:{},...u?{subscriptionType:u}:{}}}}function W(e,t){let i=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!i)return t;let r=i.split("/").map(u=>u.trim()).filter(u=>u.length>0&&u!=="."&&u!=="..");return r.length>0?r.join("/"):t}function _e(){let e=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"";return e.trim()?g.resolve(e):""}function ae(e,t,n){let i=String(t||"").trim();return i&&g.isAbsolute(i)?g.resolve(i):g.resolve(e,W(i,n))}async function N(e,t={}){let n=String(e??"").trim()||process.env.PUBLISHER_CONFIG||"publisher.config.json",i=await w.readFile(n,"utf8"),r=JSON.parse(i);r.sourceOrigin=r.sourceOrigin.replace(/\/$/,""),r.targetOrigin=ce(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=Me(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=L(r.extraReplacements),r.postCrawlCopyMap=L(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=$(r.wpsuite),r.scheduler=le(void 0),r.deploymentProfiles={},r.defaultDeploymentProfile="",r.deploymentTargetOverride=String(r.deploymentTargetOverride??"").trim();let u=await ze(r);t.onRemotePublisherConfigDiagnostic?.(u.diagnostic);let o=Ke(r,u.remote),s=_e(),a=s?g.resolve(s,".."):"";return a?(o.outputDir=ae(a,o.outputDir,"export"),o.logDir=ae(a,o.logDir,"logs")):(g.isAbsolute(o.outputDir)||(o.outputDir=W(o.outputDir,"export")),g.isAbsolute(o.logDir)||(o.logDir=W(o.logDir,"logs"))),o}function ye(e){let t=String(e.command??"").trim();return (t==="publish"||t==="crawl")&&e.crawlMode==="incremental"||t==="content-sync"}var z=new Map;async function pe(e){let t=g.resolve(e),n=z.get(t);if(n!==void 0)return n;try{let i=JSON.parse(await w.readFile(t,"utf8")),r=String(i.version??"").trim();return z.set(t,r),r}catch{return z.set(t,""),""}}var E=class extends Error{request;step;constructor(t,n){super(`Stop requested during ${n}.`),this.name="StopRequestedError",this.request=t,this.step=n;}},Xe="queue-mutation.lock",et=5e3,tt=3e4;function nt(e){let t=process.env.STATIC_PUBLISHER_RUNTIME_DIR||process.env.WPSUITE_STATIC_PUBLISHER_RUNTIME_DIR||"",n=process.env.STATIC_PUBLISHER_EXPORTER_DIR||process.cwd(),i=process.env.PUBLISHER_CONFIG||"",r=1;for(let s=0;s<e.length;s++){let a=e[s];a==="--runtime-dir"?t=e[++s]||"":a.startsWith("--runtime-dir=")?t=a.slice(14):a==="--exporter-dir"?n=e[++s]||n:a.startsWith("--exporter-dir=")?n=a.slice(15):a==="--config"?i=e[++s]||"":a.startsWith("--config=")?i=a.slice(9):a==="--max-jobs"?r=Number.parseInt(e[++s]||"1",10):a.startsWith("--max-jobs=")&&(r=Number.parseInt(a.slice(11),10));}if(!t)throw new Error("Missing runtime dir. Use --runtime-dir or STATIC_PUBLISHER_RUNTIME_DIR.");let u=g.resolve(t),o=i?g.resolve(i):g.join(u,"config.json");return {runtimeDir:u,exporterDir:g.resolve(n),configPath:o,maxJobs:Number.isFinite(r)&&r>0?r:1}}async function S(e,t){try{let n=await w.readFile(e,"utf8");return JSON.parse(n)}catch(n){if((n&&typeof n=="object"&&"code"in n?String(n.code||""):"")!=="ENOENT"){let r=n instanceof Error?n.message:String(n);console.warn(`[queue-runner] failed to read JSON ${e}: ${r}`);}return t}}async function P(e,t){await w.mkdir(g.dirname(e),{recursive:true}),await w.writeFile(e,JSON.stringify(t,null,2),"utf8");}function be(e){return g.join(e,Xe)}async function rt(e){await new Promise(t=>setTimeout(t,e));}async function it(e){let t=be(e),n=Date.now()+et;for(;;)try{await w.mkdir(g.dirname(t),{recursive:!0}),await w.writeFile(t,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()},null,2),{encoding:"utf8",flag:"wx"});return}catch(i){if((i&&typeof i=="object"&&"code"in i?String(i.code||""):"")!=="EEXIST")throw i;let u=await w.stat(t).catch(()=>null);if(u&&Date.now()-u.mtimeMs>tt){await w.unlink(t).catch(()=>{});continue}if(Date.now()>=n)throw new Error("Timed out acquiring queue mutation lock.",{cause:i});await rt(50);}}async function ot(e){await w.unlink(be(e)).catch(()=>{});}async function T(e,t){await it(e);try{return await t()}finally{await ot(e);}}function Se(e){return g.join(e,"queue-runner-heartbeat.json")}function X(e){return g.join(e,"current-progress.json")}function K(e){return g.join(e,"scheduler-state.json")}function st(e,t){let i=String(e||"").replace(/\\/g,"/").trim().replace(/^\/+|\/+$/g,"");if(!i)return t;let r=i.split("/").map(u=>u.trim()).filter(u=>u.length>0&&u!=="."&&u!=="..");return r.length>0?r.join("/"):t}async function we(e){let t=await S(e.configPath||"",null),n=g.resolve(e.runtimeDir,".."),r=(typeof t?.logDir=="string"?t.logDir:"").trim();return r&&g.isAbsolute(r)?g.resolve(r):g.resolve(n,st(r,"logs"))}function _(e,t){return String(e||"").trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||t}function ut(e){let t=e?new Date(e):new Date;return (Number.isNaN(t.getTime())?new Date:t).toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function at(e){return [ut(e.endedAt||e.startedAt),_(e.command||"job","job"),_(e.id||"job","job"),_(e.status||"finished","finished")].join("-")}function ct(e){return e.endsWith(".log.jsonl")||e.endsWith(".errors.jsonl")||e.endsWith(".rejected.jsonl")?true:["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"].includes(e)}function lt(e){return e==="errors.json"||e==="errors.jsonl"||e.endsWith(".errors.jsonl")?"errors":e==="ignored.json"||e==="ignored.jsonl"?"ignored":e==="rejected.json"||e==="rejected.jsonl"||e.endsWith(".rejected.jsonl")?"rejected":e==="skipped-http.json"||e==="skipped-http.jsonl"?"skipped-http":e==="timings.json"||e==="timings.jsonl"?"timings":e==="current-progress.json"?"current-progress":e==="current-crawl-event.json"?"current-crawl-event":e.endsWith(".log.jsonl")?e.replace(/\.log\.jsonl$/i,"-log"):e.replace(/\.[^.]+$/u,"")||"artifact"}function dt(e){return e.endsWith(".gz")?"application/gzip":e.endsWith(".jsonl")?"application/x-ndjson":e.endsWith(".json")?"application/json":"text/plain"}async function H(e,t,n){let i=`${n}.gz`,r=g.join(t,i);await pipeline(createReadStream(e),createGzip({level:9}),createWriteStream(r));let[u,o]=await Promise.all([w.stat(e),w.stat(r)]);return {role:lt(n),originalFileName:n,storedFileName:i,compressed:true,compression:"gzip",contentType:dt(i),originalSize:u.size,storedSize:o.size}}async function G(e,t){let n=await we(t),i=new Date().toISOString(),r=at(e),u=g.join(n,"archive",r),o=[],s=[];await w.mkdir(u,{recursive:true});try{let l=await w.readdir(n,{withFileTypes:!0});for(let d of l){if(!d.isFile()||!ct(d.name))continue;let p=await H(g.join(n,d.name),u,d.name);s.push(p),o.push(p.storedFileName);}}catch(l){if((l&&typeof l=="object"&&"code"in l?String(l.code||""):"")!=="ENOENT")throw l}let a=X(t.runtimeDir);if(existsSync(a)){let l=await H(a,u,"current-progress.json");s.push(l),o.push(l.storedFileName);}if(e.command==="content-sync")for(let l of ["content-sync-current.json","content-sync-impact-plan.json","content-sync-checkpoint.json","content-sync-state.json","content-sync-invalidation.json","deploy-plan.json"]){let d=g.join(t.runtimeDir,l);if(!existsSync(d))continue;let p=await H(d,u,l);s.push(p),o.push(p.storedFileName);}let c=[...o,"job.json"];return await P(g.join(u,"job.json"),{manifestVersion:1,archivedAt:i,archiveKey:r,archiveDir:u,logDir:n,runtimeDir:t.runtimeDir,exporterDir:t.exporterDir,configPath:t.configPath||"",archivedFiles:c,artifacts:s,job:e}),{archiveKey:r,archiveDir:u,archiveCreatedAt:i,archivedFiles:c,artifacts:s}}function mt(e){return g.join(e,"audit-events.jsonl")}function Y(e){return g.join(e,"stop-request.json")}async function Pe(e){try{let t=await w.readFile(Y(e),"utf8"),n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}async function ge(e,t){let n=await Pe(e);if(!n)return null;let i=String(n.targetJobId||"").trim();return i&&i!==t?null:n}async function j(e,t){if(!t){await w.unlink(Y(e)).catch(()=>{});return}let n=await Pe(e);if(!n)return;let i=String(n.targetJobId||"").trim();(!i||i===t)&&await w.unlink(Y(e)).catch(()=>{});}async function A(e,t){try{let n={occurredAt:t.occurredAt||new Date().toISOString(),status:t.status||"info",actorSource:t.actorSource||"queue-runner",...t};await w.mkdir(e,{recursive:!0}),await w.appendFile(mt(e),`${JSON.stringify(n)}
2
+ `,"utf8");}catch{}}async function v(e,t,n){let[i,r]=await Promise.all([pe(g.join(e.exporterDir,"package.json")),pe(g.join(e.exporterDir,"node_modules","@smart-cloud","wpsuite-core","package.json"))]),u={checkedAt:new Date().toISOString(),status:t,pid:process.pid,nodePath:process.execPath,nodeVersion:process.version,exporterVersion:i,wpsuiteCoreVersion:r,runtimeDir:e.runtimeDir,exporterDir:e.exporterDir,...n??{}};try{await P(Se(e.runtimeDir),u);}catch{}}async function k(e){try{await w.unlink(X(e));}catch{}}function pt(e,t){let n=e.command;if(n!=="publish"&&n!=="crawl"&&n!=="deploy"&&n!=="invalidate"&&n!=="retry-timeouts"&&n!=="url"&&n!=="content-sync")return null;let i=Number.parseInt(String(e.intervalMinutes??"0"),10);if(!Number.isFinite(i)||i<1)return null;let r=(e.id||`${n}-${t+1}`).trim();if(!r)return null;let u=e.enabled!==false,o=typeof e.url=="string"?e.url.trim():"",s=typeof e.deploymentProfile=="string"?e.deploymentProfile.trim():"",a=Array.isArray(e.postTypes)?[...new Set(e.postTypes.map(d=>String(d).trim()).filter(Boolean))]:[],c=Array.isArray(e.listingPaths)?[...new Set(e.listingPaths.map(d=>String(d).trim()).filter(Boolean))]:[],l=(n==="publish"||n==="crawl")&&e.crawlMode==="incremental"?"incremental":"full";return n==="url"&&!o||n==="content-sync"&&a.length===0?null:{id:r,enabled:u,command:n,intervalMinutes:i,...n==="publish"||n==="crawl"?{crawlMode:l}:{},...(n==="publish"||n==="deploy"||n==="invalidate"||n==="content-sync")&&s?{deploymentProfile:s}:{},...o?{url:o}:{},...a.length>0?{postTypes:a}:{},...c.length>0?{listingPaths:c}:{},...typeof e.includePostTypeArchives=="boolean"?{includePostTypeArchives:e.includePostTypeArchives}:{},...typeof e.includeTaxonomyArchives=="boolean"?{includeTaxonomyArchives:e.includeTaxonomyArchives}:{},...typeof e.includeAuthorArchives=="boolean"?{includeAuthorArchives:e.includeAuthorArchives}:{},...typeof e.includeDateArchives=="boolean"?{includeDateArchives:e.includeDateArchives}:{},...typeof e.includePostsPage=="boolean"?{includePostsPage:e.includePostsPage}:{},...typeof e.includeSitemapChain=="boolean"?{includeSitemapChain:e.includeSitemapChain}:{}}}async function gt(e){let t=await N(e.configPath).catch(()=>null),n=t?.scheduler,i=Array.isArray(n?.rules)?n.rules.map((r,u)=>pt(r,u)).filter(r=>!!r):[];return {enabled:!!n?.enabled,timezone:typeof n?.timezone=="string"&&n.timezone.trim()?n.timezone.trim():"UTC",rules:i,wpsuite:t?.wpsuite,publisherConfig:t}}function he(e,t){if(!t)throw new Error("Content-sync scheduler requires a valid publisher config.");let n=J({postTypes:e.postTypes??[],listingPaths:e.listingPaths??[],includePostTypeArchives:e.includePostTypeArchives,includeTaxonomyArchives:e.includeTaxonomyArchives,includeAuthorArchives:e.includeAuthorArchives,includeDateArchives:e.includeDateArchives,includePostsPage:e.includePostsPage,includeSitemapChain:e.includeSitemapChain}),i=ie(t.sourceOrigin,e.id,n),r=ue(t,e.deploymentProfile),u=oe({sourceOrigin:t.sourceOrigin,targetOrigin:r.config.targetOrigin,deploymentProfile:r.name||"",s3Bucket:r.config.s3.bucket,s3Prefix:r.config.s3.prefix,cloudFrontDistributionId:r.config.cloudFront.distributionId,urlRewriteMode:r.config.urlRewriteMode,extraReplacements:r.profile?.extraReplacements??{}});return `content-sync:${e.id}:${F({scopeFingerprint:i,targetFingerprint:u}).slice(0,32)}`}async function ht(e,t,n,i,r){let o=(await S(g.join(e.runtimeDir,"content-sync-baseline.json"),{})).entries?.[i];if(!o?.consumerId||!o.scopeFingerprint||!o.baselineId)return {status:"baseline-required",reason:"No verified normal-release baseline exists for this rule scope."};try{let s=t.publisherConfig;if(!s)throw new Error("Publisher configuration is unavailable.");let a=J({postTypes:n.postTypes??[],listingPaths:n.listingPaths??[],includePostTypeArchives:n.includePostTypeArchives,includeTaxonomyArchives:n.includeTaxonomyArchives,includeAuthorArchives:n.includeAuthorArchives,includeDateArchives:n.includeDateArchives,includePostsPage:n.includePostsPage,includeSitemapChain:n.includeSitemapChain}),l=await new O({sourceOrigin:s.sourceOrigin,runtimeToken:String(s.wpsuite?.runtimeToken||""),ignoreHttpsErrors:s.ignoreHttpsErrors}).head({consumerId:o.consumerId,scopeFingerprint:o.scopeFingerprint,baselineId:o.baselineId,postTypes:a.postTypes}),d=l.committedSequence;if(r?.command==="content-sync"&&r.coalesceKey===i){let p=await S(g.join(e.runtimeDir,"content-sync-current.json"),null);p?.coalesceKey===i&&Number.isSafeInteger(p.toSequence)&&(d=Math.max(d,Number(p.toSequence)));}return {status:l.headSequence>d?"pending":"current",headSequence:l.headSequence,committedSequence:l.committedSequence}}catch(s){return s instanceof D&&s.code==="baseline-required"?{status:"baseline-required",reason:s.message}:{status:"unavailable",reason:s instanceof Error?s.message:String(s)}}}function Z(e,t){let n=(t.url||"").trim(),i=t.crawlMode||"full",r=(t.deploymentProfile||"").trim(),u=(t.coalesceKey||"").trim();return e.some(o=>o.command===t.command&&(t.command!=="content-sync"||(o.coalesceKey||"").trim()===u)&&(o.url||"").trim()===n&&(o.crawlMode||"full")===i&&(o.deploymentProfile||"").trim()===r&&(o.status===void 0||o.status==="queued"||o.status==="retry-wait"||o.status==="running"))}async function ft(e,t){if(!t.allowSchedulerAutoEnqueue)return 0;let n=await gt(e);if(!n.enabled||n.rules.length===0)return 0;if(t.assertActiveSubscriptionForIdentity)try{await t.assertActiveSubscriptionForIdentity(n.wpsuite??null);}catch(m){let b=m instanceof Error?m.message:String(m);return console.warn(`[queue-runner] scheduler auto-enqueue skipped: ${b}`),0}let i=g.join(e.runtimeDir,"queue.json"),r=g.join(e.runtimeDir,"current-run.json"),u=Date.now(),o=0,s=[],a=[],c=[],l=new Map,[d,p,h]=await Promise.all([S(i,[]),S(r,null),S(K(e.runtimeDir),{lastEnqueuedBucketByRuleId:{},lastEvaluatedBucketByRuleId:{},lastCreatedBucketByRuleId:{},coalescedCountByRuleId:{}})]);for(let m of n.rules){if(!m.enabled||m.command!=="content-sync")continue;let b=Math.floor(u/(m.intervalMinutes*60*1e3)),y=h.lastEvaluatedBucketByRuleId?.[m.id]??h.lastEnqueuedBucketByRuleId?.[m.id]??-1;if(b<=y)continue;let q=he(m,n.publisherConfig);Z(d,{command:m.command,deploymentProfile:m.deploymentProfile,coalesceKey:q})||l.set(m.id,await ht(e,n,m,q,p));}await T(e.runtimeDir,async()=>{let m=await S(i,[]),b=await S(r,null),y=await S(K(e.runtimeDir),{lastEnqueuedBucketByRuleId:{},lastEvaluatedBucketByRuleId:{},lastCreatedBucketByRuleId:{},coalescedCountByRuleId:{}});y.lastEnqueuedBucketByRuleId??={},y.lastEvaluatedBucketByRuleId??={...y.lastEnqueuedBucketByRuleId},y.lastCreatedBucketByRuleId??={...y.lastEnqueuedBucketByRuleId},y.coalescedCountByRuleId??={};let q=[...m];b&&b.status==="running"&&q.unshift(b);for(let f of n.rules){if(!f.enabled)continue;let C=f.intervalMinutes*60*1e3,R=Math.floor(u/C),Ae=y.lastEvaluatedBucketByRuleId[f.id]??y.lastEnqueuedBucketByRuleId[f.id]??-1;if(R<=Ae)continue;let te=f.command==="content-sync"?he(f,n.publisherConfig):"";y.lastEvaluatedBucketByRuleId[f.id]=R;let Ie=f.command==="content-sync"?m:q;if(Z(Ie,{command:f.command,url:f.url,crawlMode:f.crawlMode,deploymentProfile:f.deploymentProfile,coalesceKey:te})){y.coalescedCountByRuleId[f.id]=(y.coalescedCountByRuleId[f.id]??0)+1,a.push(f);continue}if(f.command==="content-sync"){let M=l.get(f.id);if(!M||M.status!=="pending"){let ne=M??{status:"unavailable",reason:"Content-sync demand was not checked."};ne.status!=="current"&&c.push({rule:f,check:ne});continue}}let B={id:randomUUID(),command:f.command,...f.command==="content-sync"?{ruleId:f.id,coalesceKey:te,attempt:0}:{},...(f.command==="publish"||f.command==="crawl")&&f.crawlMode?{crawlMode:f.crawlMode}:{},...(f.command==="publish"||f.command==="deploy"||f.command==="invalidate"||f.command==="content-sync")&&f.deploymentProfile?{deploymentProfile:f.deploymentProfile}:{},...f.url?{url:f.url}:{},enqueueSource:"scheduler",...n.wpsuite?{wpsuite:n.wpsuite}:{},status:"queued",createdAt:new Date().toISOString(),createdBy:0};m.push(B),q.push(B),s.push({job:B,rule:f}),y.lastEnqueuedBucketByRuleId[f.id]=R,y.lastCreatedBucketByRuleId[f.id]=R,o+=1;}o>0&&await P(i,m),await P(K(e.runtimeDir),y);});for(let m of s){if(m.rule.command==="content-sync"){let b=l.get(m.rule.id);await A(e.runtimeDir,{eventType:"content-sync-demand-detected",status:"queued",actorSource:"queue-runner-scheduler",jobId:m.job.id,command:m.job.command,message:"Pending journal changes require a content-sync job.",details:{ruleId:m.rule.id,headSequence:b?.headSequence??0,committedSequence:b?.committedSequence??0}});}await A(e.runtimeDir,{eventType:"job-created",status:"queued",actorSource:"queue-runner-scheduler",jobId:m.job.id,command:m.job.command,message:"Scheduler auto-enqueued a job.",details:{ruleId:m.rule.id,intervalMinutes:m.rule.intervalMinutes,timezone:n.timezone,deploymentProfile:m.rule.deploymentProfile||"",url:m.rule.url||""}});}for(let m of a)await A(e.runtimeDir,{eventType:"content-sync-coalesced",status:"queued",actorSource:"queue-runner-scheduler",command:m.command,message:"Scheduler demand was coalesced into an existing content-sync job.",details:{ruleId:m.id}});for(let m of c)await A(e.runtimeDir,{eventType:m.check.status==="baseline-required"?"content-sync-baseline-required":"content-sync-demand-check-failed",status:m.check.status==="unavailable"?"failed":"info",actorSource:"queue-runner-scheduler",command:"content-sync",message:m.check.reason||"The content-sync consumer is already at the current journal head.",details:{ruleId:m.rule.id,headSequence:m.check.headSequence??0,committedSequence:m.check.committedSequence??0}});return o}async function yt(e){let t={pid:process.pid,startedAt:new Date().toISOString()};await w.writeFile(e,JSON.stringify(t,null,2),{encoding:"utf8",flag:"wx"});}async function bt(e){try{await w.unlink(e);}catch{}}function St(e,t){let n=[g.join(e,"dist",`${t}.js`),g.join(e,`${t}.js`)];for(let i of n)if(existsSync(i))return i;throw new Error(`Cannot find ${t}.js in ${g.join(e,"dist")} or ${e}`)}async function I(e,t,n,i,r,u,o){if(o){let c=await ge(t,o);if(c)throw new E(c,n)}let s=St(e,n),a={...process.env,...u??{}};return a.STATIC_PUBLISHER_RUNTIME_DIR=t,r&&(a.PUBLISHER_CONFIG=r),await new Promise((c,l)=>{let d=null,p=null,h=null,m=null,b=false,y=spawn(process.execPath,[s,...i],{cwd:e,env:a,stdio:"inherit"}),q=()=>{p&&clearInterval(p),h&&clearInterval(h),m&&clearTimeout(m);},f=async()=>{if(!(!o||d||b)){b=true;try{let C=await ge(t,o);if(!C)return;d=C,y.kill("SIGTERM"),m=setTimeout(()=>{y.kill("SIGKILL");},1e4);}finally{b=false;}}};o&&(p=setInterval(()=>{f();},1e3),h=setInterval(()=>{(async()=>{let C=Se(t),R=await S(C,{});await P(C,{...R,checkedAt:new Date().toISOString(),status:"running",currentJobId:o||R.currentJobId||"",currentStep:n});})().catch(()=>{});},15e3)),y.on("error",C=>{q(),l(C);}),y.on("close",(C,R)=>{if(q(),d){l(new E(d,n));return}C===0?c():l(new Error(`${n} exited with code ${C??-1}${R?` (signal ${R})`:""}`));});}),0}function wt(e){let t=e.awsTempCreds;if(!t)return {};let n={};return typeof t.accessKeyId=="string"&&t.accessKeyId.trim()!==""&&(n.AWS_ACCESS_KEY_ID=t.accessKeyId.trim()),typeof t.secretAccessKey=="string"&&t.secretAccessKey.trim()!==""&&(n.AWS_SECRET_ACCESS_KEY=t.secretAccessKey.trim()),typeof t.sessionToken=="string"&&t.sessionToken.trim()!==""&&(n.AWS_SESSION_TOKEN=t.sessionToken.trim()),n}async function Pt(e,t){let n=o=>{if(!o||typeof o!="object")return null;let s=o,a={...s.siteSettings??{},...String(s.accountId??"").trim()&&!s.siteSettings?.accountId?{accountId:String(s.accountId).trim()}:{},...String(s.siteId??"").trim()&&!s.siteSettings?.siteId?{siteId:String(s.siteId).trim()}:{},...s.siteSettings?.subscriber===true||s.subscriber===true?{subscriber:true}:{}},c={...String(s.apiBase??"").trim()?{apiBase:String(s.apiBase).trim()}:{},...String(s.runtimeToken??s.nonce??"").trim()?{runtimeToken:String(s.runtimeToken??s.nonce).trim()}:{},...String(s.virtualAssetBaseUrl??s.uploadUrl??"").trim()?{virtualAssetBaseUrl:String(s.virtualAssetBaseUrl??s.uploadUrl).trim()}:{},...Object.keys(a).length>0?{siteSettings:a}:{},...s.subscriptionType?{subscriptionType:s.subscriptionType}:{}};return Object.keys(c).length>0?c:null},i=await N(t.configPath).catch(()=>null),r=n(i?.wpsuite);if(r)return r;let u=n(e.wpsuite);return u||null}async function vt(e,t){return await Pt(e,t)}function ee(e){let t={...e,status:"queued"};return delete t.startedAt,delete t.endedAt,delete t.exitCode,delete t.error,delete t.stopRequestedAt,delete t.stopRequestedByUserId,delete t.stopRequestedByLogin,delete t.stopMode,delete t.stoppedStep,t}async function Ct(e,t){let n=await S(X(e.runtimeDir),null),i=n&&n.details&&typeof n.details.phase=="string"?n.details.phase.trim():"";if(i)return i;let r=n&&typeof n.currentStep=="string"?n.currentStep.trim():"";if(r)return r;let u=await we(e).catch(()=>"");if(u){let o=await S(g.join(u,"current-crawl-event.json"),null),s=o&&typeof o.currentStep=="string"?o.currentStep.trim():"";if(s)return s}return t}function At(e,t){if((e.command==="publish"||e.command==="crawl")&&t==="rewrite-text")return "rewrite-text"}async function It(e){let t=g.join(e.runtimeDir,"queue.json"),n=g.join(e.runtimeDir,"current-run.json"),i=await T(e.runtimeDir,async()=>{let r=await S(n,null);if(!r||r.status!=="running"&&r.status!=="queued")return null;let u=await S(t,[]),o=Array.isArray(u)?u.filter(a=>a?.id!==r.id):[],s=ee(r);return await P(t,[s,...o]),await P(n,null),s});i&&(await j(e.runtimeDir,i.id),await A(e.runtimeDir,{eventType:"job-recovered",status:"queued",actorSource:"queue-runner",jobId:i.id,command:i.command,message:"Recovered stale current-run entry back into queue."}));}async function Rt(e,t,n){try{if((n.shouldEnforceSubscriptionOnJobExecution?.(e)??n.enforceSubscriptionOnJobExecution)&&n.assertActiveSubscriptionForIdentity){let s=await vt(e,t);await n.assertActiveSubscriptionForIdentity(s);}let r=wt(e),u=e.resumeFromStep==="rewrite-text"?["--resume-rewrite"]:e.crawlMode==="incremental"?["--crawl-mode","incremental"]:[],o=e.deploymentProfile?["--profile",e.deploymentProfile]:[];if(e.command==="publish")return await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync-release-cutoff"}),await I(t.exporterDir,t.runtimeDir,"content-sync",["--capture-baseline-cutoffs",e.id],t.configPath,r,e.id),await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:e.resumeFromStep==="rewrite-text"?"rewrite-text":"crawl"}),await I(t.exporterDir,t.runtimeDir,"crawl",u,t.configPath,r,e.id),await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"deploy"}),await I(t.exporterDir,t.runtimeDir,"deploy",o,t.configPath,r,e.id),await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"invalidate"}),await I(t.exporterDir,t.runtimeDir,"invalidate",o,t.configPath,r,e.id),await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync-baseline"}),await I(t.exporterDir,t.runtimeDir,"content-sync",["--establish-baselines",e.id],t.configPath,r,e.id),{exitCode:0};if(e.command==="crawl")return await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:e.resumeFromStep==="rewrite-text"?"rewrite-text":"crawl"}),await I(t.exporterDir,t.runtimeDir,"crawl",u,t.configPath,r,e.id),{exitCode:0};if(e.command==="deploy")return await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"deploy"}),await I(t.exporterDir,t.runtimeDir,"deploy",o,t.configPath,r,e.id),{exitCode:0};if(e.command==="invalidate")return await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"invalidate"}),await I(t.exporterDir,t.runtimeDir,"invalidate",o,t.configPath,r,e.id),{exitCode:0};if(e.command==="retry-timeouts")return await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"retry-timeouts"}),await I(t.exporterDir,t.runtimeDir,"crawl",["--retry-timeouts"],t.configPath,r,e.id),{exitCode:0};if(e.command==="url"){let s=(e.url||"").trim();return s?(await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"url"}),await I(t.exporterDir,t.runtimeDir,"crawl",["--url",s],t.configPath,r,e.id),{exitCode:0}):{exitCode:2,error:"Missing url for command 'url'"}}return e.command==="content-sync"?!e.ruleId||!e.coalesceKey?{exitCode:2,error:"Content-sync queue jobs require ruleId and coalesceKey."}:(await v(t,"running",{currentJobId:e.id,currentJobCommand:e.command,currentStep:"content-sync"}),await I(t.exporterDir,t.runtimeDir,"content-sync",["--job-id",e.id],t.configPath,r,e.id),{exitCode:0}):{exitCode:2,error:`Unsupported command: ${e.command}`}}catch(i){return i instanceof E?{exitCode:130,error:"Job stop requested.",stopped:true,stopRequest:i.request,stoppedStep:i.step}:{exitCode:1,error:i instanceof Error?i.message:String(i)}}}function ve(e){return async function(n=process.argv.slice(2)){let i=nt(n),r=g.join(i.runtimeDir,"export.lock"),u=g.join(i.runtimeDir,"last-run.json");await k(i.runtimeDir),await v(i,"starting",{message:"queue-runner starting"});try{await yt(r);}catch(o){if((o&&typeof o=="object"&&"code"in o?String(o.code||""):"")!=="EEXIST")throw o;console.log("[queue-runner] lock active, skipping"),await v(i,"lock-active",{message:"lock active, skipped this cron tick"});return}try{await It(i);let o=await ft(i,e),s=0;for(let a=0;a<i.maxJobs;a++){let c=await Tt(i,e);if(c==="none"||(s+=1,c==="stopped"))break}if(s===0)await k(i.runtimeDir),await v(i,"idle",{processedJobs:s,schedulerEnqueued:o,message:"no queued jobs"});else {await k(i.runtimeDir);let a=await S(u,null),c=String(a?.status||"").trim();await v(i,c==="success"?"job-success":c==="stopped"?"job-stopped":"job-failed",{processedJobs:s,schedulerEnqueued:o,lastJobId:a?.id,lastJobCommand:a?.command,lastJobStatus:a?.status,lastJobExitCode:a?.exitCode,lastJobError:a?.error,...c==="stopped"?{currentStep:a?.stoppedStep,stopRequestedAt:a?.stopRequestedAt,stopRequestedByLogin:a?.stopRequestedByLogin,stopRequestedMode:a?.stopMode,lastStoppedStep:a?.stoppedStep,message:a?.stopMode==="requeue"?`Job stopped during ${a?.stoppedStep||a?.command||"active step"} and requeued.`:`Job stopped during ${a?.stoppedStep||a?.command||"active step"} and left out of queue.`}:{}});}}catch(o){let s=o instanceof Error?o.message:String(o);throw await v(i,"error",{message:s}),await A(i.runtimeDir,{eventType:"queue-runner-error",status:"failed",actorSource:"queue-runner",message:"Unhandled queue-runner error.",details:{error:s}}),o}finally{await bt(r);}}}async function qt(e,t,n){let i=g.join(e.runtimeDir,"queue.json"),r=g.join(e.runtimeDir,"current-run.json");await T(e.runtimeDir,async()=>{let u=await S(i,[]),o=Array.isArray(u)?u.filter(c=>c?.id!==t.id):[],s=ee(t),a=At(t,n);a?s.resumeFromStep=a:delete s.resumeFromStep,await P(i,[s,...o]),await P(r,null);});}async function xt(e,t,n){let i=Math.max(0,t.attempt??0)+1,r=Math.min(3600*1e3,6e4*2**(i-1)),u=Math.floor(r*.2*Math.random()),o=new Date(Date.now()+r+u).toISOString(),s={...ee(t),status:"retry-wait",attempt:i,nextAttemptAt:o,error:n};if(await T(e.runtimeDir,async()=>{let a=g.join(e.runtimeDir,"queue.json"),c=g.join(e.runtimeDir,"current-run.json"),d=(await S(a,[])).filter(p=>p.id!==t.id);await P(a,[s,...d]),await P(c,null);}),t.coalesceKey){let a=g.join(e.runtimeDir,"content-sync-state.json"),l=(await S(a,{})).rules??{};l[t.coalesceKey]={...l[t.coalesceKey]??{},ruleId:t.ruleId||"",coalesceKey:t.coalesceKey,retryAttempt:i,nextRetryAt:o,lastError:n,trailingWorkDetected:true},await P(a,{schemaVersion:1,updatedAt:new Date().toISOString(),rules:l});}return s}async function Dt(e,t){if(!t.coalesceKey||!t.ruleId||!(await S(g.join(e.runtimeDir,"content-sync-state.json"),null))?.rules?.[t.coalesceKey]?.trailingWorkDetected)return null;let i=null;await T(e.runtimeDir,async()=>{let u=g.join(e.runtimeDir,"queue.json"),o=await S(u,[]);Z(o,{command:"content-sync",coalesceKey:t.coalesceKey,deploymentProfile:t.deploymentProfile})||(i={id:randomUUID(),command:"content-sync",ruleId:t.ruleId,coalesceKey:t.coalesceKey,deploymentProfile:t.deploymentProfile,enqueueSource:"scheduler",wpsuite:t.wpsuite,status:"queued",attempt:0,createdAt:new Date().toISOString(),createdBy:0},await P(u,[...o,i]));});let r=i;return r&&await A(e.runtimeDir,{eventType:"content-sync-trailing-job-created",status:"queued",actorSource:"queue-runner",jobId:r.id,command:r.command,message:"Content changes after the stable cutoff created one trailing job.",details:{predecessorJobId:t.id,ruleId:t.ruleId,coalesceKey:t.coalesceKey}}),r}async function Tt(e,t){let n=g.join(e.runtimeDir,"queue.json"),i=g.join(e.runtimeDir,"current-run.json"),r=g.join(e.runtimeDir,"last-run.json"),u=new Date().toISOString(),o=await T(e.runtimeDir,async()=>{let d=await S(n,[]);if(!Array.isArray(d)||d.length===0)return null;let p=Date.parse(String(d[0]?.nextAttemptAt||""));if(Number.isFinite(p)&&p>Date.now())return null;let h={...d[0],status:"running",startedAt:u};return delete h.nextAttemptAt,await P(n,d.slice(1)),await P(i,h),h});if(!o)return "none";await k(e.runtimeDir),await A(e.runtimeDir,{eventType:"job-run-started",status:"running",actorSource:"queue-runner",jobId:o.id,command:o.command,message:"Job execution started.",details:{createdAt:o.createdAt||"",startedAt:u,createdBy:o.createdBy??null,deploymentProfile:o.deploymentProfile||"",queuedWithTempAwsCreds:!!o.awsTempCreds}}),await v(e,"running",{currentJobId:o.id,currentJobCommand:o.command,currentStep:o.command});let s=await Rt(o,e,t),a=new Date().toISOString();if(s.stopped){let d=await Ct(e,s.stoppedStep||o.command),p=s.stopRequest?.mode==="requeue"?"requeue":"stop",h={...o,status:"stopped",endedAt:a,exitCode:s.exitCode,...s.error?{error:s.error}:{},stopRequestedAt:s.stopRequest?.requestedAt||"",stopRequestedByUserId:typeof s.stopRequest?.requestedByUserId=="number"?s.stopRequest.requestedByUserId:null,stopRequestedByLogin:s.stopRequest?.requestedByLogin||"",stopMode:p,stoppedStep:d};p==="requeue"?await qt(e,o,d):await P(i,null);try{let m=await G(h,e);h.logArchiveDir=m.archiveDir,h.logArchiveCreatedAt=m.archiveCreatedAt,h.logArchiveFileCount=m.archivedFiles.length;}catch(m){h.logArchiveError=m instanceof Error?m.message:String(m);}return await P(r,h),await j(e.runtimeDir,o.id),await k(e.runtimeDir),await A(e.runtimeDir,{eventType:"job-run-stopped",status:"stopped",actorSource:"queue-runner",jobId:o.id,command:o.command,message:p==="requeue"?"Job stop requested and requeued.":"Job stop requested and removed from active execution without requeue.",details:{startedAt:o.startedAt||"",endedAt:a,deploymentProfile:o.deploymentProfile||"",stopMode:p,stopRequestedAt:s.stopRequest?.requestedAt||"",stopRequestedByLogin:s.stopRequest?.requestedByLogin||"",stopRequestedByUserId:typeof s.stopRequest?.requestedByUserId=="number"?s.stopRequest.requestedByUserId:null,stoppedStep:d,logArchiveKey:h.logArchiveError||!h.logArchiveDir?"":g.basename(h.logArchiveDir),logArchiveDir:h.logArchiveDir||"",logArchiveCreatedAt:h.logArchiveCreatedAt||"",logArchiveFileCount:h.logArchiveFileCount??0,logArchiveError:h.logArchiveError||""}}),"stopped"}if(o.command==="content-sync"&&s.exitCode!==0){await A(e.runtimeDir,{eventType:"content-sync-failed",status:"failed",actorSource:"queue-runner",jobId:o.id,command:o.command,message:"Content-sync execution failed before cursor acknowledgement.",details:{attempt:o.attempt??0,error:s.error||"Content-sync execution failed."}});let d=await xt(e,o,s.error||"Content-sync execution failed."),p={...o,status:"retry-wait",endedAt:a,exitCode:s.exitCode,error:d.error,attempt:d.attempt,nextAttemptAt:d.nextAttemptAt};try{let h=await G(p,e);p.logArchiveDir=h.archiveDir,p.logArchiveCreatedAt=h.archiveCreatedAt,p.logArchiveFileCount=h.archivedFiles.length;}catch(h){p.logArchiveError=h instanceof Error?h.message:String(h);}return await P(r,p),await j(e.runtimeDir,o.id),await A(e.runtimeDir,{eventType:"content-sync-retry-scheduled",status:"retry-wait",actorSource:"queue-runner",jobId:o.id,command:o.command,message:"Content-sync retry was scheduled with bounded backoff.",details:{attempt:d.attempt??0,nextAttemptAt:d.nextAttemptAt||"",error:d.error||""}}),"processed"}let c={...o,status:s.exitCode===0?"success":"failed",endedAt:a,exitCode:s.exitCode,...s.error?{error:s.error}:{}};await P(i,null),c.status==="success"&&c.command==="content-sync"&&await Dt(e,c),await j(e.runtimeDir,o.id);try{let d=await G(c,e);c.logArchiveDir=d.archiveDir,c.logArchiveCreatedAt=d.archiveCreatedAt,c.logArchiveFileCount=d.archivedFiles.length;}catch(d){c.logArchiveError=d instanceof Error?d.message:String(d);}await P(r,c);let l=o.startedAt&&c.endedAt?Math.max(0,Math.round((new Date(c.endedAt).getTime()-new Date(o.startedAt).getTime())/1e3)):void 0;return await A(e.runtimeDir,{eventType:"job-run-finished",status:c.status==="success"?"success":"failed",actorSource:"queue-runner",jobId:c.id,command:c.command,message:c.status==="success"?"Job execution finished successfully.":"Job execution finished with failure.",details:{startedAt:o.startedAt||"",endedAt:c.endedAt||"",durationSec:l,deploymentProfile:c.deploymentProfile||"",exitCode:c.exitCode??null,error:c.error||"",logArchiveKey:c.logArchiveError||!c.logArchiveDir?"":g.basename(c.logArchiveDir),logArchiveDir:c.logArchiveDir||"",logArchiveCreatedAt:c.logArchiveCreatedAt||"",logArchiveFileCount:c.logArchiveFileCount??0,logArchiveError:c.logArchiveError||""}}),"processed"}async function Et(e){if(!e)throw new Error("Missing remote WPSuite publisher state. Refresh the runtime config before running subscription-gated jobs.");if(e.subscriptionType!=="PROFESSIONAL"&&e.subscriptionType!=="AGENCY")throw new Error("This job requires an active WPSuite publisher subscription in the remote site configuration.")}var Ft={allowSchedulerAutoEnqueue:true,enforceSubscriptionOnJobExecution:false,shouldEnforceSubscriptionOnJobExecution:e=>ye(e)||e.enqueueSource==="scheduler"||e.createdBy===0,assertActiveSubscriptionForIdentity:Et},Ce=ve(Ft),Jt=Ce,un=Ce;process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href&&Jt().catch(e=>{console.error(e),process.exit(1);});export{un as default,Jt as main,Ce as runQueueRunner};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smart-cloud/publisher-exporter",
3
- "version": "1.1.38",
3
+ "version": "1.1.40",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Headless Playwright static publisher for WordPress/Elementor sites with sitemap-only page discovery, strict asset capture, escaped URL rewrite, structured logs, and targeted retry modes.",
@@ -43,7 +43,7 @@
43
43
  "@aws-sdk/client-cloudfront": "^3.1100.0",
44
44
  "@aws-sdk/client-s3": "^3.1100.0",
45
45
  "@aws-sdk/lib-storage": "^3.1100.0",
46
- "@smart-cloud/publisher-core": "^1.1.6",
46
+ "@smart-cloud/publisher-core": "^1.1.7",
47
47
  "@smart-cloud/wpsuite-core": "^2.3.2",
48
48
  "baseline-browser-mapping": "^2.11.12",
49
49
  "caniuse-lite": "^1.0.30001809",