@stacksjs/buddy 0.75.514 → 0.75.518
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/app-store-connect.js +2 -2
- package/dist/cli.js +4 -4
- package/dist/cloud-tenants.js +1 -1
- package/dist/commands/about.js +1 -1
- package/dist/commands/add.js +1 -1
- package/dist/commands/ai-access.js +2 -2
- package/dist/commands/ai-context.js +2 -2
- package/dist/commands/auth-prune-options.js +1 -1
- package/dist/commands/auth.js +1 -1
- package/dist/commands/build.js +1 -1
- package/dist/commands/cd.js +3 -3
- package/dist/commands/changelog.js +1 -1
- package/dist/commands/clean.js +1 -1
- package/dist/commands/cloud.js +7 -7
- package/dist/commands/comments.js +2 -2
- package/dist/commands/commerce-import.js +3 -3
- package/dist/commands/commit.js +1 -1
- package/dist/commands/completion.js +7 -7
- package/dist/commands/config-migrate.js +5 -5
- package/dist/commands/configure.js +2 -2
- package/dist/commands/create.js +1 -1
- package/dist/commands/db.js +1 -1
- package/dist/commands/deploy-fly.js +2 -2
- package/dist/commands/deploy-preview.js +1 -1
- package/dist/commands/deploy-ssh-target.js +1 -1
- package/dist/commands/deploy.js +588 -19
- package/dist/commands/desktop-apple.js +12 -12
- package/dist/commands/desktop-probe.js +1 -1
- package/dist/commands/dev.js +4 -4
- package/dist/commands/dns.js +2 -2
- package/dist/commands/docs/agent-counts.js +2 -2
- package/dist/commands/docs/buddy-commands.js +11 -11
- package/dist/commands/docs/capabilities.js +2 -2
- package/dist/commands/docs/desktop-matrix.js +2 -2
- package/dist/commands/docs/framework-repo.js +1 -1
- package/dist/commands/docs/generated-artifacts.js +3 -3
- package/dist/commands/docs/links.js +2 -2
- package/dist/commands/docs/native-skills.js +2 -2
- package/dist/commands/docs/snippets.js +7 -7
- package/dist/commands/doctor.js +3 -3
- package/dist/commands/domains.js +2 -2
- package/dist/commands/email.js +26 -26
- package/dist/commands/env.js +1 -1
- package/dist/commands/extension.js +3 -3
- package/dist/commands/features.js +3 -3
- package/dist/commands/feedback.js +3 -3
- package/dist/commands/fresh.js +1 -1
- package/dist/commands/gdpr.js +6 -6
- package/dist/commands/generate.js +5 -5
- package/dist/commands/http.js +1 -1
- package/dist/commands/install.js +1 -1
- package/dist/commands/integrations-probe.js +2 -2
- package/dist/commands/key.js +1 -1
- package/dist/commands/libs.js +1 -1
- package/dist/commands/link.js +2 -2
- package/dist/commands/lint.js +2 -2
- package/dist/commands/list.js +2 -2
- package/dist/commands/mail.js +13 -13
- package/dist/commands/maintenance.js +1 -1
- package/dist/commands/make.js +1 -1
- package/dist/commands/migrate-project.js +1 -1
- package/dist/commands/migrate.js +59 -59
- package/dist/commands/outdated.js +1 -1
- package/dist/commands/package.js +1 -1
- package/dist/commands/phone.js +13 -13
- package/dist/commands/ports.js +2 -2
- package/dist/commands/prepublish.js +1 -1
- package/dist/commands/preview-deploy.js +1 -1
- package/dist/commands/projects.js +1 -1
- package/dist/commands/publish.js +8 -8
- package/dist/commands/queue.js +1 -1
- package/dist/commands/release.js +7 -7
- package/dist/commands/route.js +1 -1
- package/dist/commands/saas.js +1 -1
- package/dist/commands/schedule.js +1 -1
- package/dist/commands/search.js +1 -1
- package/dist/commands/security.js +2 -2
- package/dist/commands/seed.js +1 -1
- package/dist/commands/serve.js +1 -1
- package/dist/commands/server-image.js +2 -2
- package/dist/commands/server-trust.js +2 -2
- package/dist/commands/server.js +10 -8
- package/dist/commands/setup-ai.js +2 -2
- package/dist/commands/setup.js +5 -5
- package/dist/commands/share.js +1 -1
- package/dist/commands/simulator.js +1 -1
- package/dist/commands/sms.js +25 -25
- package/dist/commands/socials.js +3 -3
- package/dist/commands/stacks.js +1 -1
- package/dist/commands/storage-backup.js +1 -1
- package/dist/commands/telemetry.js +1 -1
- package/dist/commands/test.js +1 -1
- package/dist/commands/tinker.js +1 -1
- package/dist/commands/types.js +1 -1
- package/dist/commands/upgrade.js +1 -1
- package/dist/commands/user.js +2 -2
- package/dist/config.js +1 -1
- package/dist/custom-cli.js +1 -1
- package/dist/database-backup.js +2 -2
- package/dist/database-preflight.js +1 -1
- package/dist/deploy-notify.js +3 -3
- package/dist/deployment-inputs.d.ts +6 -0
- package/dist/deployment-inputs.js +1 -0
- package/dist/deployment-revision.js +4 -4
- package/dist/dns-credentials.js +1 -1
- package/dist/email-reprocess.js +1 -1
- package/dist/feedback-links.js +1 -1
- package/dist/global-options.js +1 -1
- package/dist/lazy-commands.js +1 -1
- package/dist/mail-dns-health.js +1 -1
- package/dist/mail-users.js +1 -1
- package/dist/migrators/index.js +1 -1
- package/dist/migrators/laravel/index.js +1 -1
- package/dist/migrators/laravel/migrations.js +4 -4
- package/dist/migrators/laravel/models.js +4 -4
- package/dist/native-project.js +7 -7
- package/dist/native-site.js +2 -2
- package/dist/pantry-service-ports.js +2 -2
- package/dist/production-server.js +1 -1
- package/dist/project-setup.js +1 -1
- package/dist/publish-stx.js +1 -1
- package/dist/registry.js +1 -1
- package/dist/release-ios.js +1 -1
- package/dist/result.js +1 -1
- package/dist/scaffold-app.js +4 -4
- package/dist/scaffold-desktop.js +1 -1
- package/dist/scaffold-package-app.js +7 -7
- package/dist/scaffold-site.js +1 -1
- package/dist/storage-backup.js +1 -1
- package/dist/system-dependencies.js +1 -1
- package/dist/unbacked-data.js +1 -1
- package/dist/unvendor-rewrite.js +2 -2
- package/dist/version-info.js +1 -1
- package/dist/workflow-prune.js +3 -3
- package/package.json +55 -55
package/dist/email-reprocess.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extractEmailPreview,inboundMailboxRecipient,inboundMessageStorageId,normalizeEmailPreview,parseInboundEmail}from"@stacksjs/email";function errorMessage(error){return error instanceof Error?error.message:String(error)}async function withOperationTimeout(promise,milliseconds){let timeout;const expired=new Promise((_resolve,reject)=>{timeout=setTimeout(()=>reject(Error(`Email reprocess operation timed out after ${milliseconds}ms.`)),milliseconds)});try{return await Promise.race([promise,expired])}finally{if(timeout)clearTimeout(timeout)}}export async function reprocessInboundEmails(options){const domain=options.domain.trim().toLowerCase();if(!inboundMailboxRecipient(`validation@${domain}`,domain))throw TypeError(`Invalid email domain: ${options.domain}`);const objects=await withOperationTimeout(options.storage.listAllObjects({bucket:options.bucket,prefix:options.prefix}),60000)
|
|
1
|
+
import{extractEmailPreview,inboundMailboxRecipient,inboundMessageStorageId,normalizeEmailPreview,parseInboundEmail}from"@stacksjs/email";function errorMessage(error){return error instanceof Error?error.message:String(error)}async function withOperationTimeout(promise,milliseconds){let timeout;const expired=new Promise((_resolve,reject)=>{timeout=setTimeout(()=>reject(new Error(`Email reprocess operation timed out after ${milliseconds}ms.`)),milliseconds)});try{return await Promise.race([promise,expired])}finally{if(timeout)clearTimeout(timeout)}}export async function reprocessInboundEmails(options){const domain=options.domain.trim().toLowerCase();if(!inboundMailboxRecipient(`validation@${domain}`,domain))throw new TypeError(`Invalid email domain: ${options.domain}`);const objects=await withOperationTimeout(options.storage.listAllObjects({bucket:options.bucket,prefix:options.prefix}),60000);const inboxes=new Map;const skipped=[];let processed=0;for(const object of objects){if(!object.Key||object.Key.endsWith("/"))continue;try{const rawResult=await withOperationTimeout(options.storage.getObjectBytes(options.bucket,object.Key),15000);const rawEmail=rawResult.body;if(!rawEmail.byteLength)continue;const messageId=object.Key.split("/").pop()||object.Key;const storageMessageId=inboundMessageStorageId(messageId);const parsedEmail=await parseInboundEmail(rawEmail);const parsedDate=parsedEmail.date?new Date(parsedEmail.date):null;const date=parsedDate&&!Number.isNaN(parsedDate.getTime())?parsedDate.toISOString():object.LastModified||new Date().toISOString();const fallbackRaw=new TextDecoder().decode(rawEmail);const preview=normalizeEmailPreview(parsedEmail.text||parsedEmail.html||extractEmailPreview(fallbackRaw));const hasAttachments=parsedEmail.attachments.length>0;const recipients=parsedEmail.recipients.length>0?parsedEmail.recipients:[`unknown@${domain}`];for(const recipient of recipients){const mailbox=inboundMailboxRecipient(recipient,domain);if(!mailbox)continue;const instant=new Date(date);const year=instant.getFullYear();const month=String(instant.getMonth()+1).padStart(2,"0");const day=String(instant.getDate()).padStart(2,"0");const emailPath=`mailboxes/${mailbox.domain}/${mailbox.localPart}/${year}/${month}/${day}/${storageMessageId}`;const attachmentMetadata=parsedEmail.attachments.map((attachment)=>({name:attachment.name,contentType:attachment.contentType,size:attachment.content.byteLength,...attachment.contentId?{contentId:attachment.contentId}:{},...attachment.disposition?{disposition:attachment.disposition}:{}}));const metadata={messageId,from:parsedEmail.from,fromName:parsedEmail.fromName,to:mailbox.address,subject:parsedEmail.subject,date,preview,hasAttachments,attachments:attachmentMetadata};const writes=[options.storage.putObject({bucket:options.bucket,key:`${emailPath}/raw.eml`,body:rawEmail,contentType:"message/rfc822"}),options.storage.putObject({bucket:options.bucket,key:`${emailPath}/metadata.json`,body:JSON.stringify(metadata,null,2),contentType:"application/json"}),...parsedEmail.attachments.map((attachment)=>options.storage.putObject({bucket:options.bucket,key:`${emailPath}/attachments/${attachment.storageName}`,body:attachment.content,contentType:attachment.contentType}))];if(parsedEmail.text){writes.push(options.storage.putObject({bucket:options.bucket,key:`${emailPath}/body.txt`,body:parsedEmail.text,contentType:"text/plain; charset=utf-8"}))}if(parsedEmail.html){writes.push(options.storage.putObject({bucket:options.bucket,key:`${emailPath}/body.html`,body:parsedEmail.html,contentType:"text/html; charset=utf-8"}))}await withOperationTimeout(Promise.all(writes),30000);const inboxKey=`${mailbox.domain}/${mailbox.localPart}`;const inbox=inboxes.get(inboxKey)||[];inbox.push({messageId,from:parsedEmail.from,fromName:parsedEmail.fromName,to:mailbox.address,subject:parsedEmail.subject,date,read:false,preview,hasAttachments,path:emailPath});inboxes.set(inboxKey,inbox)}processed++;options.onProgress?.(processed,objects.length)}catch(error){skipped.push({key:object.Key,error:errorMessage(error)})}}const mailboxes=[];for(const[key,emails]of inboxes){const[mailboxDomain,localPart]=key.split("/");const inboxJsonKey=`mailboxes/${mailboxDomain}/${localPart}/inbox.json`;let existing=[];try{const existingData=await options.storage.getObject(options.bucket,inboxJsonKey);existing=existingData?JSON.parse(existingData):[]}catch{existing=[]}const existingIds=new Set(existing.map((email)=>email.messageId));const refreshedIds=new Set(emails.map((email)=>email.messageId));const existingById=new Map(existing.map((email)=>[email.messageId,email]));const refreshed=emails.map((email)=>{const current=existingById.get(email.messageId);return current?{...email,read:current.read===true}:email});const merged=[...refreshed,...existing.filter((email)=>!refreshedIds.has(email.messageId))].sort((left,right)=>new Date(right.date).getTime()-new Date(left.date).getTime()).slice(0,1000);const newCount=emails.filter((email)=>!existingIds.has(email.messageId)).length;const refreshedCount=emails.length-newCount;await withOperationTimeout(options.storage.putObject({bucket:options.bucket,key:inboxJsonKey,body:JSON.stringify(merged,null,2),contentType:"application/json"}),30000);mailboxes.push({mailbox:`${localPart}@${mailboxDomain}`,newCount,refreshedCount,total:merged.length})}return{discovered:objects.length,processed,skipped,mailboxes}}
|
package/dist/feedback-links.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export const FEEDBACK_BOARD_NAME="Feedback"
|
|
1
|
+
export const FEEDBACK_BOARD_NAME="Feedback";export const FEEDBACK_BOARD_COLUMNS=["Inbox","Triaged","In Progress","Done"];export function parseRowRef(value){const input=(value??"").trim();if(!input)return null;if(/^\d+$/.test(input)){const id=Number(input);return Number.isSafeInteger(id)&&id>0?{kind:"id",id}:null}return{kind:"name",name:input}}export function parseBoardRef(value){return parseRowRef(value)??{kind:"name",name:FEEDBACK_BOARD_NAME}}export function parseExpiryDays(value,now){if(value===undefined)return{ok:true,at:null};const input=String(value).trim();if(!input)return{ok:false,message:"--expires needs a number of days, for example --expires 30."};if(!/^\d+$/.test(input))return{ok:false,message:`--expires takes a whole number of days, not \`${input}\`.`};const days=Number(input);if(days<1)return{ok:false,message:"--expires must be at least 1 day. To stop a link now, use `buddy feedback:revoke`."};return{ok:true,at:new Date(now.getTime()+days*86400000)}}export function toStoredTimestamp(at){return at.toISOString().slice(0,19).replace("T"," ")}export function feedbackSubmitUrl(appUrl,rawToken){const base=(appUrl??"").trim();if(!base)throw new Error("No app URL configured. Set APP_URL or config.app.url.");const url=new URL(/^https?:\/\//i.test(base)?base:`https://${base}`);url.pathname=`/feedback/${rawToken}`;url.search="";url.hash="";return url.toString()}export function renderFeedbackTokens(rows){if(rows.length===0)return" No feedback links. Create one with `buddy feedback:invite <label>`.";const widest=(pick,header)=>Math.max(header.length,...rows.map((row)=>pick(row).length));const label=widest((row)=>row.label,"LABEL");const status=widest((row)=>row.status,"STATUS");const used=widest((row)=>row.lastUsedAt??"never","LAST USED");const lines=[` ${"ID".padStart(4)} ${"LABEL".padEnd(label)} ${"BOARD".padStart(5)} ${"STATUS".padEnd(status)} ${"LAST USED".padEnd(used)} EXPIRES`];for(const row of rows){lines.push([` ${String(row.id).padStart(4)}`,row.label.padEnd(label),String(row.boardId).padStart(5),row.status.padEnd(status),(row.lastUsedAt??"never").padEnd(used),row.expiresAt??"never"].join(" "))}return lines.join(`
|
|
2
2
|
`)}
|
package/dist/global-options.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{versionDescriptor}from"./version-info";export function registerGlobalOptions(buddy,options={}){
|
|
1
|
+
import{versionDescriptor}from"./version-info";export function registerGlobalOptions(buddy,options={}){const command=options.version===false?buddy:buddy.version(versionDescriptor,"-V, --version");command.option("-v, --verbose","Enable verbose output").option("-q, --quiet","Suppress non-essential output").option("--debug","Enable debug output and stack traces").option("--no-interaction","Do not ask interactive questions").option("--env <environment>","Target an environment").option("--no-emoji","Disable emoji in output").option("--no-cache","Disable command metadata caching")}
|
package/dist/lazy-commands.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export async function withTimeout(work,ms){let timeoutId;const deadline=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("timeout")),ms)});try{return await Promise.race([work,deadline])}finally{if(timeoutId!==void 0)clearTimeout(timeoutId)}}const commandRegistry={about:{path:"./commands/about.js",load:()=>import("./commands/about.js"),exportName:"about"},add:{path:"./commands/add.js",load:()=>import("./commands/add.js"),exportName:"add"},"ai:access":{path:"./commands/ai-access.js",load:()=>import("./commands/ai-access.js"),exportName:"aiAccess"},"ai:context":{path:"./commands/ai-context.js",load:()=>import("./commands/ai-context.js"),exportName:"aiContext"},auth:{path:"./commands/auth.js",load:()=>import("./commands/auth.js"),exportName:"auth"},build:{path:"./commands/build.js",load:()=>import("./commands/build.js"),exportName:"build"},cd:{path:"./commands/cd.js",load:()=>import("./commands/cd.js"),exportName:"cd"},changelog:{path:"./commands/changelog.js",load:()=>import("./commands/changelog.js"),exportName:"changelog"},clean:{path:"./commands/clean.js",load:()=>import("./commands/clean.js"),exportName:"clean"},cloud:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},commit:{path:"./commands/commit.js",load:()=>import("./commands/commit.js"),exportName:"commit"},completion:{path:"./commands/completion.js",load:()=>import("./commands/completion.js"),exportName:"completion"},"config:migrate":{path:"./commands/config-migrate.js",load:()=>import("./commands/config-migrate.js"),exportName:"configMigrate"},configure:{path:"./commands/configure.js",load:()=>import("./commands/configure.js"),exportName:"configure"},create:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},new:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},deploy:{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},"deploy:rollback":{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},dev:{path:"./commands/dev.js",load:()=>import("./commands/dev.js"),exportName:"dev"},"desktop:apple:doctor":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:csr":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:init":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:package":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:provision":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:publish":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:probe":{path:"./commands/desktop-probe.js",load:()=>import("./commands/desktop-probe.js"),exportName:"desktopProbe"},"integrations:probe":{path:"./commands/integrations-probe.js",load:()=>import("./commands/integrations-probe.js"),exportName:"integrationsProbe"},dns:{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:pull":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:diff":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:sync":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},doctor:{path:"./commands/doctor.js",load:()=>import("./commands/doctor.js"),exportName:"doctor"},domains:{path:"./commands/domains.js",load:()=>import("./commands/domains.js"),exportName:"domains"},email:{path:"./commands/email.js",load:()=>import("./commands/email.js"),exportName:"email"},env:{path:"./commands/env.js",load:()=>import("./commands/env.js"),exportName:"env"},"extension:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:build":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:package":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:status":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:firefox:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:provision":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:app":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"dashboard:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"dashboard:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:import":{path:"./commands/commerce-import.js",load:()=>import("./commands/commerce-import.js"),exportName:"commerceImport"},"cms:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"cms:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"db:backup":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:backups":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:restore":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"storage:backup":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:backups":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:restore":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"feedback:invite":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:tokens":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:revoke":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"socials:identities":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},"socials:authorize":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},fresh:{path:"./commands/fresh.js",load:()=>import("./commands/fresh.js"),exportName:"fresh"},generate:{path:"./commands/generate.js",load:()=>import("./commands/generate.js"),exportName:"generate"},"gdpr:export":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:erase":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:prune":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register:check":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},http:{path:"./commands/http.js",load:()=>import("./commands/http.js"),exportName:"http"},install:{path:"./commands/install.js",load:()=>import("./commands/install.js"),exportName:"install"},key:{path:"./commands/key.js",load:()=>import("./commands/key.js"),exportName:"key"},lint:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},format:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},"format:check":{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},libs:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},libraries:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},list:{path:"./commands/list.js",load:()=>import("./commands/list.js"),exportName:"list"},mail:{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},"mail:preview":{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},maintenance:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},down:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},up:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},status:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon:status":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},launch:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},make:{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},"scaffold:crud":{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},migrate:{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:fresh":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:switch":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:project":{path:"./commands/migrate-project.js",load:()=>import("./commands/migrate-project.js"),exportName:"migrateProject"},outdated:{path:"./commands/outdated.js",load:()=>import("./commands/outdated.js"),exportName:"outdated"},package:{path:"./commands/package.js",load:()=>import("./commands/package.js"),exportName:"packageCommands"},phone:{path:"./commands/phone.js",load:()=>import("./commands/phone.js"),exportName:"phone"},ports:{path:"./commands/ports.js",load:()=>import("./commands/ports.js"),exportName:"ports"},"security:scan":{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},audit:{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},"server:flash":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:first-boot":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:doctor":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:setup":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:trust":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"link:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},"comments:list":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:approve":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:reject":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:delete":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"user:add":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"user:list":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"unlink:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},prepublish:{path:"./commands/prepublish.js",load:()=>import("./commands/prepublish.js"),exportName:"prepublish"},projects:{path:"./commands/projects.js",load:()=>import("./commands/projects.js"),exportName:"projects"},publish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:model":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:controller":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:middleware":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:action":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:component":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:view":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:core":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"core:status":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:defaults":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},unpublish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},queue:{path:"./commands/queue.js",load:()=>import("./commands/queue.js"),exportName:"queue"},release:{path:"./commands/release.js",load:()=>import("./commands/release.js"),exportName:"release"},route:{path:"./commands/route.js",load:()=>import("./commands/route.js"),exportName:"route"},saas:{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},"stripe:setup":{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},schedule:{path:"./commands/schedule.js",load:()=>import("./commands/schedule.js"),exportName:"schedule"},search:{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:update":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:settings":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},seed:{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:roles":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"roles:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:admins":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"admins:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},preview:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"preview"},serve:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serve"},"serve:api":{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serveApi"},setup:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},ensure:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ai":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ssl":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ios":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:oh-my-zsh":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"ai:setup":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},share:{path:"./commands/share.js",load:()=>import("./commands/share.js"),exportName:"share"},"simulator:doctor":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},"simulator:open":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},stack:{path:"./commands/stacks.js",load:()=>import("./commands/stacks.js"),exportName:"stacks"},sms:{path:"./commands/sms.js",load:()=>import("./commands/sms.js"),exportName:"sms"},telemetry:{path:"./commands/telemetry.js",load:()=>import("./commands/telemetry.js"),exportName:"telemetryCommand"},test:{path:"./commands/test.js",load:()=>import("./commands/test.js"),exportName:"test"},tinker:{path:"./commands/tinker.js",load:()=>import("./commands/tinker.js"),exportName:"tinker"},types:{path:"./commands/types.js",load:()=>import("./commands/types.js"),exportName:"types"},undeploy:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},upgrade:{path:"./commands/upgrade.js",load:()=>import("./commands/upgrade.js"),exportName:"upgrade"},version:{path:"./commands/version.js",load:()=>import("./commands/version.js"),exportName:"version"},"docs:buddy":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:buddy:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"}},commandGroups={minimal:["version","help"],development:["dev","build","test","lint"],database:["migrate","seed","fresh"],scaffolding:["make","generate"],deployment:["deploy","release","cloud","server"],info:["about","doctor","list"]},loadedRegistrars=new WeakMap;function loaderKey(loader){return`${loader.path}#${loader.exportName}`}export function markLoaded(buddy,commandName){const loader=commandRegistry[commandName];if(!loader)return;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}set.add(loaderKey(loader))}export async function loadCommand(commandName,buddy){const loader=commandRegistry[commandName];if(!loader)return!1;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}const key=loaderKey(loader);if(set.has(key))return!0;set.add(key);try{const commandFunction=(await loader.load())[loader.exportName];if(typeof commandFunction==="function"){commandFunction(buddy);return!0}else return!1}catch{return!1}}export async function loadCommands(commandNames,buddy){const seen=new Set,unique=[];for(const name of commandNames){const loader=commandRegistry[name],key=loader?`${loader.path}#${loader.exportName}`:`name:${name}`;if(seen.has(key))continue;seen.add(key);unique.push(name)}await Promise.all(unique.map(async(name)=>{try{await withTimeout(loadCommand(name,buddy),5000)}catch{}}))}export async function loadCommandGroup(groupName,buddy){const commands=commandGroups[groupName];if(commands)await loadCommands(commands,buddy)}export async function loadAllCommands(buddy){const allCommands=Object.keys(commandRegistry);await loadCommands(allCommands,buddy)}export function getCommandNames(){return Object.keys(commandRegistry)}export function getCommandsToLoad(args){const requestedCommand=args[0],isVersionFlag=requestedCommand==="--version"||requestedCommand==="-v",isHelpFlag=requestedCommand==="--help"||requestedCommand==="-h",isHelpWord=requestedCommand==="help";if(isVersionFlag)return["version"];if(!requestedCommand||isHelpFlag||isHelpWord)return Object.keys(commandRegistry);const baseCommand=requestedCommand.split(":")[0];if(baseCommand==="list")return["list",...Object.keys(commandRegistry).filter((k)=>k!=="list")];if(commandRegistry[requestedCommand])return[requestedCommand];if(commandRegistry[baseCommand])return[baseCommand];return Object.keys(commandRegistry)}
|
|
1
|
+
export async function withTimeout(work,ms){let timeoutId;const deadline=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(new Error("timeout")),ms)});try{return await Promise.race([work,deadline])}finally{if(timeoutId!==undefined)clearTimeout(timeoutId)}}const commandRegistry={about:{path:"./commands/about.js",load:()=>import("./commands/about.js"),exportName:"about"},add:{path:"./commands/add.js",load:()=>import("./commands/add.js"),exportName:"add"},"ai:access":{path:"./commands/ai-access.js",load:()=>import("./commands/ai-access.js"),exportName:"aiAccess"},"ai:context":{path:"./commands/ai-context.js",load:()=>import("./commands/ai-context.js"),exportName:"aiContext"},auth:{path:"./commands/auth.js",load:()=>import("./commands/auth.js"),exportName:"auth"},build:{path:"./commands/build.js",load:()=>import("./commands/build.js"),exportName:"build"},cd:{path:"./commands/cd.js",load:()=>import("./commands/cd.js"),exportName:"cd"},changelog:{path:"./commands/changelog.js",load:()=>import("./commands/changelog.js"),exportName:"changelog"},clean:{path:"./commands/clean.js",load:()=>import("./commands/clean.js"),exportName:"clean"},cloud:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},commit:{path:"./commands/commit.js",load:()=>import("./commands/commit.js"),exportName:"commit"},completion:{path:"./commands/completion.js",load:()=>import("./commands/completion.js"),exportName:"completion"},"config:migrate":{path:"./commands/config-migrate.js",load:()=>import("./commands/config-migrate.js"),exportName:"configMigrate"},configure:{path:"./commands/configure.js",load:()=>import("./commands/configure.js"),exportName:"configure"},create:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},new:{path:"./commands/create.js",load:()=>import("./commands/create.js"),exportName:"create"},deploy:{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},"deploy:rollback":{path:"./commands/deploy.js",load:()=>import("./commands/deploy.js"),exportName:"deploy"},dev:{path:"./commands/dev.js",load:()=>import("./commands/dev.js"),exportName:"dev"},"desktop:apple:doctor":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:csr":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:init":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:package":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:provision":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:apple:publish":{path:"./commands/desktop-apple.js",load:()=>import("./commands/desktop-apple.js"),exportName:"desktopApple"},"desktop:probe":{path:"./commands/desktop-probe.js",load:()=>import("./commands/desktop-probe.js"),exportName:"desktopProbe"},"integrations:probe":{path:"./commands/integrations-probe.js",load:()=>import("./commands/integrations-probe.js"),exportName:"integrationsProbe"},dns:{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:pull":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:diff":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},"dns:sync":{path:"./commands/dns.js",load:()=>import("./commands/dns.js"),exportName:"dns"},doctor:{path:"./commands/doctor.js",load:()=>import("./commands/doctor.js"),exportName:"doctor"},domains:{path:"./commands/domains.js",load:()=>import("./commands/domains.js"),exportName:"domains"},email:{path:"./commands/email.js",load:()=>import("./commands/email.js"),exportName:"email"},env:{path:"./commands/env.js",load:()=>import("./commands/env.js"),exportName:"env"},"extension:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:build":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:package":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:chrome:status":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:firefox:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:init":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:provision":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:app":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"extension:safari:publish":{path:"./commands/extension.js",load:()=>import("./commands/extension.js"),exportName:"extension"},"dashboard:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"dashboard:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"commerce:import":{path:"./commands/commerce-import.js",load:()=>import("./commands/commerce-import.js"),exportName:"commerceImport"},"cms:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"cms:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"marketing:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"monitoring:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"realtime:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:install":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"queue:uninstall":{path:"./commands/features.js",load:()=>import("./commands/features.js"),exportName:"features"},"db:backup":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:backups":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"db:restore":{path:"./commands/db.js",load:()=>import("./commands/db.js"),exportName:"db"},"storage:backup":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:backups":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"storage:restore":{path:"./commands/storage-backup.js",load:()=>import("./commands/storage-backup.js"),exportName:"storageBackup"},"feedback:invite":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:tokens":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"feedback:revoke":{path:"./commands/feedback.js",load:()=>import("./commands/feedback.js"),exportName:"feedback"},"socials:identities":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},"socials:authorize":{path:"./commands/socials.js",load:()=>import("./commands/socials.js"),exportName:"socials"},fresh:{path:"./commands/fresh.js",load:()=>import("./commands/fresh.js"),exportName:"fresh"},generate:{path:"./commands/generate.js",load:()=>import("./commands/generate.js"),exportName:"generate"},"gdpr:export":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:erase":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:prune":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},"gdpr:register:check":{path:"./commands/gdpr.js",load:()=>import("./commands/gdpr.js"),exportName:"gdpr"},http:{path:"./commands/http.js",load:()=>import("./commands/http.js"),exportName:"http"},install:{path:"./commands/install.js",load:()=>import("./commands/install.js"),exportName:"install"},key:{path:"./commands/key.js",load:()=>import("./commands/key.js"),exportName:"key"},lint:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},format:{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},"format:check":{path:"./commands/lint.js",load:()=>import("./commands/lint.js"),exportName:"lint"},libs:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},libraries:{path:"./commands/libs.js",load:()=>import("./commands/libs.js"),exportName:"libs"},list:{path:"./commands/list.js",load:()=>import("./commands/list.js"),exportName:"list"},mail:{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},"mail:preview":{path:"./commands/mail.js",load:()=>import("./commands/mail.js"),exportName:"mailCommands"},maintenance:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},down:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},up:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},status:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},"coming-soon:status":{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},launch:{path:"./commands/maintenance.js",load:()=>import("./commands/maintenance.js"),exportName:"maintenance"},make:{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},"scaffold:crud":{path:"./commands/make.js",load:()=>import("./commands/make.js"),exportName:"make"},migrate:{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:fresh":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:switch":{path:"./commands/migrate.js",load:()=>import("./commands/migrate.js"),exportName:"migrate"},"migrate:project":{path:"./commands/migrate-project.js",load:()=>import("./commands/migrate-project.js"),exportName:"migrateProject"},outdated:{path:"./commands/outdated.js",load:()=>import("./commands/outdated.js"),exportName:"outdated"},package:{path:"./commands/package.js",load:()=>import("./commands/package.js"),exportName:"packageCommands"},phone:{path:"./commands/phone.js",load:()=>import("./commands/phone.js"),exportName:"phone"},ports:{path:"./commands/ports.js",load:()=>import("./commands/ports.js"),exportName:"ports"},"security:scan":{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},audit:{path:"./commands/security.js",load:()=>import("./commands/security.js"),exportName:"security"},"server:flash":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:first-boot":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:doctor":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:setup":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"server:trust":{path:"./commands/server.js",load:()=>import("./commands/server.js"),exportName:"server"},"link:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},"comments:list":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:approve":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:reject":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"comments:delete":{path:"./commands/comments.js",load:()=>import("./commands/comments.js"),exportName:"commentsCommands"},"user:add":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"user:list":{path:"./commands/user.js",load:()=>import("./commands/user.js"),exportName:"user"},"unlink:core":{path:"./commands/link.js",load:()=>import("./commands/link.js"),exportName:"link"},prepublish:{path:"./commands/prepublish.js",load:()=>import("./commands/prepublish.js"),exportName:"prepublish"},projects:{path:"./commands/projects.js",load:()=>import("./commands/projects.js"),exportName:"projects"},publish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:model":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:controller":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:middleware":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:action":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:component":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:view":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:core":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"core:status":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},"publish:defaults":{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},unpublish:{path:"./commands/publish.js",load:()=>import("./commands/publish.js"),exportName:"publish"},queue:{path:"./commands/queue.js",load:()=>import("./commands/queue.js"),exportName:"queue"},release:{path:"./commands/release.js",load:()=>import("./commands/release.js"),exportName:"release"},route:{path:"./commands/route.js",load:()=>import("./commands/route.js"),exportName:"route"},saas:{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},"stripe:setup":{path:"./commands/saas.js",load:()=>import("./commands/saas.js"),exportName:"saas"},schedule:{path:"./commands/schedule.js",load:()=>import("./commands/schedule.js"),exportName:"schedule"},search:{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:update":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},"search-engine:settings":{path:"./commands/search.js",load:()=>import("./commands/search.js"),exportName:"search"},seed:{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:roles":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"roles:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"seed:admins":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},"admins:seed":{path:"./commands/seed.js",load:()=>import("./commands/seed.js"),exportName:"seed"},preview:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"preview"},serve:{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serve"},"serve:api":{path:"./commands/serve.js",load:()=>import("./commands/serve.js"),exportName:"serveApi"},setup:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},ensure:{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ai":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ssl":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:ios":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"setup:oh-my-zsh":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},"ai:setup":{path:"./commands/setup.js",load:()=>import("./commands/setup.js"),exportName:"setup"},share:{path:"./commands/share.js",load:()=>import("./commands/share.js"),exportName:"share"},"simulator:doctor":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},"simulator:open":{path:"./commands/simulator.js",load:()=>import("./commands/simulator.js"),exportName:"simulator"},stack:{path:"./commands/stacks.js",load:()=>import("./commands/stacks.js"),exportName:"stacks"},sms:{path:"./commands/sms.js",load:()=>import("./commands/sms.js"),exportName:"sms"},telemetry:{path:"./commands/telemetry.js",load:()=>import("./commands/telemetry.js"),exportName:"telemetryCommand"},test:{path:"./commands/test.js",load:()=>import("./commands/test.js"),exportName:"test"},tinker:{path:"./commands/tinker.js",load:()=>import("./commands/tinker.js"),exportName:"tinker"},types:{path:"./commands/types.js",load:()=>import("./commands/types.js"),exportName:"types"},undeploy:{path:"./commands/cloud.js",load:()=>import("./commands/cloud.js"),exportName:"cloud"},upgrade:{path:"./commands/upgrade.js",load:()=>import("./commands/upgrade.js"),exportName:"upgrade"},version:{path:"./commands/version.js",load:()=>import("./commands/version.js"),exportName:"version"},"docs:buddy":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:native-skills:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:buddy:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:artifacts:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"},"docs:links:check":{path:"./commands/docs.js",load:()=>import("./commands/docs.js"),exportName:"docs"}};const commandGroups={minimal:["version","help"],development:["dev","build","test","lint"],database:["migrate","seed","fresh"],scaffolding:["make","generate"],deployment:["deploy","release","cloud","server"],info:["about","doctor","list"]};const loadedRegistrars=new WeakMap;function loaderKey(loader){return`${loader.path}#${loader.exportName}`}export function markLoaded(buddy,commandName){const loader=commandRegistry[commandName];if(!loader)return;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}set.add(loaderKey(loader))}export async function loadCommand(commandName,buddy){const loader=commandRegistry[commandName];if(!loader){return false}let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}const key=loaderKey(loader);if(set.has(key))return true;set.add(key);try{const module=await loader.load();const commandFunction=module[loader.exportName];if(typeof commandFunction==="function"){commandFunction(buddy);return true}else{return false}}catch{return false}}export async function loadCommands(commandNames,buddy){const seen=new Set;const unique=[];for(const name of commandNames){const loader=commandRegistry[name];const key=loader?`${loader.path}#${loader.exportName}`:`name:${name}`;if(seen.has(key))continue;seen.add(key);unique.push(name)}await Promise.all(unique.map(async(name)=>{try{await withTimeout(loadCommand(name,buddy),5000)}catch{}}))}export async function loadCommandGroup(groupName,buddy){const commands=commandGroups[groupName];if(commands){await loadCommands(commands,buddy)}}export async function loadAllCommands(buddy){const allCommands=Object.keys(commandRegistry);await loadCommands(allCommands,buddy)}export function getCommandNames(){return Object.keys(commandRegistry)}export function getCommandsToLoad(args){const requestedCommand=args[0];const isVersionFlag=requestedCommand==="--version"||requestedCommand==="-v";const isHelpFlag=requestedCommand==="--help"||requestedCommand==="-h";const isHelpWord=requestedCommand==="help";if(isVersionFlag)return["version"];if(!requestedCommand||isHelpFlag||isHelpWord)return Object.keys(commandRegistry);const baseCommand=requestedCommand.split(":")[0];if(baseCommand==="list"){return["list",...Object.keys(commandRegistry).filter((k)=>k!=="list")]}if(commandRegistry[requestedCommand]){return[requestedCommand]}if(commandRegistry[baseCommand]){return[baseCommand]}return Object.keys(commandRegistry)}
|
package/dist/mail-dns-health.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dnsProviderNameFromNameservers,findMailDnsAnomalies,postmasterHint,resolveDmarcPolicy,resolvePostmasterRecord}from"./commands/deploy";import{dnsCredentialFix,dnsCredentialPresence,dnsProviderLabel}from"./dns-credentials";export function mailDomainFromConfig(cfg){if(typeof cfg?.domain==="string"&&cfg.domain.trim())return cfg.domain.trim().toLowerCase();const address=cfg?.from?.address;if(typeof address==="string"&&address.includes("@"))return address.split("@")[1].trim().toLowerCase()||
|
|
1
|
+
import{dnsProviderNameFromNameservers,findMailDnsAnomalies,postmasterHint,resolveDmarcPolicy,resolvePostmasterRecord}from"./commands/deploy";import{dnsCredentialFix,dnsCredentialPresence,dnsProviderLabel}from"./dns-credentials";export function mailDomainFromConfig(cfg){if(typeof cfg?.domain==="string"&&cfg.domain.trim())return cfg.domain.trim().toLowerCase();const address=cfg?.from?.address;if(typeof address==="string"&&address.includes("@"))return address.split("@")[1].trim().toLowerCase()||undefined;return}export function describeMailDnsProvider(input){const{domain,zone,nameservers,declared,envFile}=input;if(nameservers.length===0)return{status:"warn",message:`Could not resolve the nameservers for ${domain}'s zone, so which provider holds it is unknown (a deploy will try every configured one).`};const provider=dnsProviderNameFromNameservers([...nameservers]);if(!provider){return{status:"warn",message:`${zone} is served by ${nameservers.slice(0,2).join(", ")}, which no deploy can write: ${dnsCredentialFix(null,envFile,nameservers)}`}}const label=dnsProviderLabel(provider);if(declared&&declared!==provider){return{status:"warn",message:`config/cloud.ts declares '${declared}' as the DNS provider, but ${zone}'s nameservers are ${label}'s. A deploy only tries '${declared}', so ${domain}'s mail records land in a zone nobody resolves. Fix the declaration, or move the zone.`}}const presence=dnsCredentialPresence(provider,input.fileKeys,input.env??process.env);if(!presence.configured){return{status:"warn",message:`${zone} is on ${label}, but ${presence.missing.join(" and ")} ${presence.missing.length===1?"is":"are"} not set in ${envFile} or this environment, so no deploy publishes ${domain}'s mail records. Fix: ${dnsCredentialFix(provider,envFile)}`}}const where=presence.source==="file"?envFile:`this environment (not ${envFile}, so a deploy from elsewhere will not have it)`;return{status:"pass",message:`${zone} is on ${label}; credentials found in ${where}`}}function dmarcPolicy(record){return record.match(/(?:^|;)\s*p\s*=\s*([a-z]+)/i)?.[1]?.toLowerCase()}export function describeMailDnsRecords(input){const{domain,records,dkimSelector}=input;const dkimFqdn=`${dkimSelector}._domainkey.${domain}`;const anomalies=findMailDnsAnomalies([...records],[{label:"MX",fqdn:domain,type:"MX"},{label:"SPF",fqdn:domain,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=spf1")},{label:"DMARC",fqdn:`_dmarc.${domain}`,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=dmarc1")}],domain);const dkim=records.filter((record)=>record.type==="TXT"&&record.name===dkimFqdn);const notes=[...anomalies];if(dkim.length===0)notes.push(`DKIM: nothing at ${dkimSelector}._domainkey (the selector the server signs under may differ; a deploy reads the real one)`);else if(dkim.length>1)notes.push(`DKIM: ${dkim.length} records at ${dkimFqdn}, expected 1`);const dmarc=records.filter((record)=>record.type==="TXT"&&record.name===`_dmarc.${domain}`&&record.content.toLowerCase().startsWith("v=dmarc1"));const wanted=resolveDmarcPolicy(input.dmarcPolicy);const live=dmarc.length===1?dmarcPolicy(dmarc[0].content):undefined;if(live&&live!==wanted)notes.push(`DMARC: live policy is p=${live}, config says p=${wanted}, so the last deploy did not publish it`);const spf=records.filter((record)=>record.type==="TXT"&&record.name===domain&&record.content.toLowerCase().startsWith("v=spf1"));const addresses=input.mxAddresses??[];if(spf.length===1&&addresses.length>0){const mechanisms=spf[0].content.toLowerCase().split(/\s+/);const delegated=mechanisms.some((term)=>/^[+~?-]?(?:(?:a|mx)(?:[:/]|$)|include:|redirect=)/.test(term));if(!delegated&&!addresses.some((address)=>mechanisms.some((term)=>term.replace(/^[+~?-]/,"")===`ip4:${address}`||term.replace(/^[+~?-]/,"").startsWith(`ip4:${address}/`))))notes.push(`SPF: does not authorize ${addresses.join(", ")}, the address the MX host resolves to`)}if(notes.length===0)return{status:"pass",message:`MX, SPF, DKIM (${dkimSelector}) and DMARC each published once for ${domain}`};return{status:"warn",message:`${domain}: ${notes.join("; ")}`}}export function describePostmaster(domain,postmaster,apexTxt){const hint=postmasterHint(domain,postmaster);if(hint)return{status:"warn",message:hint};if(postmaster===false)return{status:"pass",message:"Not used (email.server.postmaster is false)"};const record=resolvePostmasterRecord(postmaster.google);if(!apexTxt.includes(record))return{status:"warn",message:`email.server.postmaster.google is set but ${domain} does not publish it yet; the next deploy that can write the zone will.`};return{status:"pass",message:`Verification record published for ${domain}`}}export function joinTxtAnswers(answers){const records=[];let continues=false;for(const chunks of answers){const value=chunks.join("");if(continues&&records.length>0)records[records.length-1]+=value;else records.push(value);continues=chunks.length===1&&chunks[0].length===255}return records}export async function gatherMailDnsFacts(domain,dkimSelector,timeoutMs=1500){const{Resolver}=await import("node:dns/promises");const{resolveZoneNameservers}=await import("./dns-credentials");const resolver=new Resolver({timeout:timeoutMs,tries:1});const txt=async(name)=>joinTxtAnswers(await resolver.resolveTxt(name).catch(()=>[])).map((content)=>({name,type:"TXT",content}));const[ns,mx,apex,dmarc,dkim]=await Promise.all([resolveZoneNameservers(domain,timeoutMs),resolver.resolveMx(domain).catch(()=>[]),txt(domain),txt(`_dmarc.${domain}`),txt(`${dkimSelector}._domainkey.${domain}`)]);const exchange=[...mx].sort((a,b)=>a.priority-b.priority)[0]?.exchange;const mxAddresses=exchange?await resolver.resolve4(exchange).catch(()=>[]):[];return{zone:ns.zone,nameservers:ns.nameservers,records:[...mx.map((record)=>({name:domain,type:"MX",content:record.exchange})),...apex,...dmarc,...dkim],mxAddresses}}
|
package/dist/mail-users.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";export function resolveMailUserBackend(settings){if(settings?.driver!=="dynamodb")throw Error('mail:user:* requires config/email.ts server.mailboxUsers with driver: "dynamodb" and the existing verifier table. For SQLite or external mail servers, manage users through that server or its deployment configuration; this command does not modify them.');if(typeof settings.table!=="string"||!/^[a-z0-9_.-]{3,255}$/i.test(settings.table))throw Error("server.mailboxUsers.table must name the existing DynamoDB mailbox verifier table.");return{table:settings.table,region:settings.region||process.env.AWS_REGION||"us-east-1"}}const defaultClient=async(region)=>{const{DynamoDBClient}=await import("@stacksjs/ts-cloud");return new DynamoDBClient(region)};export async function mailUserClient(settings,factory=defaultClient){const{table,region}=resolveMailUserBackend(settings);return{client:await factory(region),table}}export function parseMailUserPassword(input){const password=input.replace(/\r?\n$/,"");if(!password||password.length>1024||/[\r\n\0]/.test(password))throw Error("Provide one non-empty password (at most 1024 characters) through --password-stdin.");return password}export async function addMailUser(email,input,settings,factory=defaultClient){if(!/^[^\s@]+@[^\s@]+$/.test(email))throw Error("Provide a valid mailbox email address.");const password=parseMailUserPassword(input)
|
|
1
|
+
import{createHash}from"node:crypto";export function resolveMailUserBackend(settings){if(settings?.driver!=="dynamodb")throw new Error('mail:user:* requires config/email.ts server.mailboxUsers with driver: "dynamodb" and the existing verifier table. For SQLite or external mail servers, manage users through that server or its deployment configuration; this command does not modify them.');if(typeof settings.table!=="string"||!/^[a-z0-9_.-]{3,255}$/i.test(settings.table))throw new Error("server.mailboxUsers.table must name the existing DynamoDB mailbox verifier table.");return{table:settings.table,region:settings.region||process.env.AWS_REGION||"us-east-1"}}const defaultClient=async(region)=>{const{DynamoDBClient}=await import("@stacksjs/ts-cloud");return new DynamoDBClient(region)};export async function mailUserClient(settings,factory=defaultClient){const{table,region}=resolveMailUserBackend(settings);return{client:await factory(region),table}}export function parseMailUserPassword(input){const password=input.replace(/\r?\n$/,"");if(!password||password.length>1024||/[\r\n\0]/.test(password))throw new Error("Provide one non-empty password (at most 1024 characters) through --password-stdin.");return password}export async function addMailUser(email,input,settings,factory=defaultClient){if(!/^[^\s@]+@[^\s@]+$/.test(email))throw new Error("Provide a valid mailbox email address.");const password=parseMailUserPassword(input);const{client,table}=await mailUserClient(settings,factory);await client.putItem({TableName:table,Item:{email:{S:email.toLowerCase()},passwordHash:{S:createHash("sha256").update(password).digest("hex")},createdAt:{S:new Date().toISOString()}}})}
|
package/dist/migrators/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{laravelDriver}from"./laravel";import{railsDriver}from"./rails";export const DRIVERS={laravel:laravelDriver,rails:railsDriver};export async function runMigrator(req){const driver=DRIVERS[req.from];if(!driver)throw Error(`Unknown source framework: ${req.from}. Supported: ${Object.keys(DRIVERS).join(", ")}`);const startedAt=new Date().toISOString()
|
|
1
|
+
import{laravelDriver}from"./laravel";import{railsDriver}from"./rails";export const DRIVERS={laravel:laravelDriver,rails:railsDriver};export async function runMigrator(req){const driver=DRIVERS[req.from];if(!driver)throw new Error(`Unknown source framework: ${req.from}. Supported: ${Object.keys(DRIVERS).join(", ")}`);const startedAt=new Date().toISOString();const entries=await driver.migrate(req);const finishedAt=new Date().toISOString();return{source:req.source,target:req.target,from:req.from,startedAt,finishedAt,entries}}export function renderReport(report){const lines=[];lines.push(`# Migration report - ${report.from} → Stacks`);lines.push("");lines.push(`- **Source**: \`${report.source}\``);lines.push(`- **Target**: \`${report.target}\``);lines.push(`- **Started**: ${report.startedAt}`);lines.push(`- **Finished**: ${report.finishedAt}`);lines.push("");const groups=groupEntriesByStatus(report.entries);for(const[status,label]of[["translated","Translated"],["copied","Copied verbatim"],["skipped","Skipped (hand-port required)"],["failed","Failed"]]){const group=groups[status]??[];if(group.length===0)continue;lines.push(`## ${label} (${group.length})`);lines.push("");for(const e of group){const arrow=e.target?` → \`${e.target}\``:"";const note=e.note?` - ${e.note}`:"";lines.push(`- \`${e.source}\`${arrow}${note}`)}lines.push("")}lines.push("---");lines.push("");lines.push("Re-run `./buddy migrate:project <name> --from="+report.from+"` after fixing the source project to refresh emitted files. Translated outputs are overwritten; skipped entries are not.");return lines.join(`
|
|
2
2
|
`)}function groupEntriesByStatus(entries){const out={};for(const e of entries){if(!out[e.status])out[e.status]=[];out[e.status].push(e)}return out}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readdirSync}from"node:fs";import{copyFile,mkdir,readFile,writeFile}from"node:fs/promises";import{join}from"node:path";import{laravelFilenameToStacks,parseLaravelMigration}from"./migrations";import{parseLaravelModel}from"./models";export const laravelDriver={name:"laravel",async migrate(req){const entries=[];entries.push(...await migrateEnv(req));entries.push(...await migrateMigrations(req));entries.push(...await migrateModels(req));entries.push(...summariseDeferred(req));return entries}};async function migrateEnv(req){const out=[];for(const file of[".env",".env.example"]){const sourcePath=join(req.source,file);if(!existsSync(sourcePath))continue;const targetPath=join(req.target,file);if(!req.dryRun){await mkdir(req.target,{recursive
|
|
1
|
+
import{existsSync,readdirSync}from"node:fs";import{copyFile,mkdir,readFile,writeFile}from"node:fs/promises";import{join}from"node:path";import{laravelFilenameToStacks,parseLaravelMigration}from"./migrations";import{parseLaravelModel}from"./models";export const laravelDriver={name:"laravel",async migrate(req){const entries=[];entries.push(...await migrateEnv(req));entries.push(...await migrateMigrations(req));entries.push(...await migrateModels(req));entries.push(...summariseDeferred(req));return entries}};async function migrateEnv(req){const out=[];for(const file of[".env",".env.example"]){const sourcePath=join(req.source,file);if(!existsSync(sourcePath))continue;const targetPath=join(req.target,file);if(!req.dryRun){await mkdir(req.target,{recursive:true});await copyFile(sourcePath,targetPath)}out.push({source:file,target:file,status:"copied",note:"Laravel-specific keys (BROADCAST_DRIVER, FILESYSTEM_DISK names) may need renaming; Stacks reads APP_*/DB_*/MAIL_* keys as-is."})}return out}async function migrateMigrations(req){const dir=join(req.source,"database","migrations");if(!existsSync(dir))return[];const files=readdirSync(dir).filter((f)=>f.endsWith(".php")).sort();const targetDir=join(req.target,"database","migrations");if(!req.dryRun)await mkdir(targetDir,{recursive:true});const out=[];for(let i=0;i<files.length;i++){const file=files[i];const rel=`database/migrations/${file}`;try{const body=await readFile(join(dir,file),"utf8");const parsed=parseLaravelMigration(body);if(!parsed){out.push({source:rel,target:"",status:"skipped",note:"No `Schema::create(...)` block found (likely an alter / drop / data-only migration)."});continue}const sequence=i+1;const outName=laravelFilenameToStacks(file,sequence,parsed.table);const outRel=`database/migrations/${outName}`;if(!req.dryRun)await writeFile(join(req.target,outRel),parsed.sql);const skippedNote=parsed.skipped.length>0?` Skipped ${parsed.skipped.length} line(s) inside the create block - hand-port from the source migration.`:"";out.push({source:rel,target:outRel,status:"translated",note:`CREATE TABLE \`${parsed.table}\` emitted.${skippedNote}`})}catch(err){out.push({source:rel,target:"",status:"failed",note:`Parse error: ${err instanceof Error?err.message:String(err)}`})}}return out}async function migrateModels(req){const dir=join(req.source,"app","Models");if(!existsSync(dir))return[];const files=readdirSync(dir).filter((f)=>f.endsWith(".php"));const targetDir=join(req.target,"app","Models");if(!req.dryRun)await mkdir(targetDir,{recursive:true});const out=[];for(const file of files){const rel=`app/Models/${file}`;try{const body=await readFile(join(dir,file),"utf8");const parsed=parseLaravelModel(body);if(!parsed){out.push({source:rel,target:"",status:"skipped",note:"No class declaration found."});continue}const outName=`${parsed.className}.ts`;const outRel=`app/Models/${outName}`;if(!req.dryRun)await writeFile(join(req.target,outRel),parsed.tsSource);const notes=[`Attributes: ${parsed.fillable.length} fillable, ${Object.keys(parsed.casts).length} cast`,parsed.relationships.length>0?`Relationships: ${parsed.relationships.map((r)=>`${r.name}(${r.kind})`).join(", ")}`:null,...parsed.notes].filter(Boolean).join(" | ");out.push({source:rel,target:outRel,status:"translated",note:notes||`Model ${parsed.className} emitted.`})}catch(err){out.push({source:rel,target:"",status:"failed",note:`Parse error: ${err instanceof Error?err.message:String(err)}`})}}return out}const DEFERRED_SURFACES=[{path:"routes",note:"routes/web.php + routes/api.php - port to routes/web.ts + routes/api.ts using the Stacks router DSL."},{path:"app/Http/Controllers",note:"Controllers → Stacks Actions in app/Actions/. Each controller method maps to one Action file."},{path:"resources/views",note:"Blade templates → stx components in resources/views/."},{path:"database/seeders",note:"Seeders → database/seeders/*.ts using Stacks SeederContract."},{path:"app/Console/Commands",note:"Artisan commands → app/Commands/*.ts in your Stacks project."},{path:"app/Jobs",note:"Queue jobs → app/Jobs/*.ts; pair with config/queue.ts driver settings."},{path:"composer.json",note:"Dependency map - Laravel packages don't translate 1:1; the Stacks docs cover the closest @stacksjs/* equivalents."}];function summariseDeferred(req){const out=[];for(const surface of DEFERRED_SURFACES){const sourcePath=join(req.source,surface.path);if(!existsSync(sourcePath))continue;out.push({source:surface.path,target:"",status:"skipped",note:surface.note})}return out}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export function parseLaravelMigration(source){const createMatch=source.match(/Schema::create\(\s*['"]([a-z0-9_]+)['"]\s*,\s*function\s*\([^)]*\)\s*\{([\s\S]*?)\}\s*\)\s*;/i);if(!createMatch?.[1]||createMatch[2]===
|
|
2
|
-
`).map((line)=>line.trim()).filter((line)=>line.length>0&&!line.startsWith("//")&&!line.startsWith("*")&&!line.startsWith("/*"));for(const line of lines){const trimmed=line.replace(/;\s*$/,"");if(!trimmed.startsWith("$table->")){skipped.push(line);continue}const parsed=parseColumnLine(trimmed);if(!parsed){skipped.push(line);continue}if(parsed.kind==="columns"){columns.push(...parsed.columns);if(parsed.indexes)indexes.push(...parsed.indexes)}else if(parsed.kind==="index")indexes.push(parsed.index)
|
|
3
|
-
`));lines.push(");");for(const idx of indexes){const cols=idx.columns.join(", ")
|
|
1
|
+
export function parseLaravelMigration(source){const createMatch=source.match(/Schema::create\(\s*['"]([a-z0-9_]+)['"]\s*,\s*function\s*\([^)]*\)\s*\{([\s\S]*?)\}\s*\)\s*;/i);if(!createMatch?.[1]||createMatch[2]===undefined)return null;const table=createMatch[1];const body=createMatch[2];const skipped=[];const columns=[];const indexes=[];const lines=body.split(`
|
|
2
|
+
`).map((line)=>line.trim()).filter((line)=>line.length>0&&!line.startsWith("//")&&!line.startsWith("*")&&!line.startsWith("/*"));for(const line of lines){const trimmed=line.replace(/;\s*$/,"");if(!trimmed.startsWith("$table->")){skipped.push(line);continue}const parsed=parseColumnLine(trimmed);if(!parsed){skipped.push(line);continue}if(parsed.kind==="columns"){columns.push(...parsed.columns);if(parsed.indexes)indexes.push(...parsed.indexes)}else if(parsed.kind==="index"){indexes.push(parsed.index)}else if(parsed.kind==="skip"){skipped.push(line)}}const sql=emitCreateTable(table,columns,indexes);return{table,sql,skipped}}function parseColumnLine(line){const methodMatch=line.match(/^\$table->([a-zA-Z_]+)\s*\(([^)]*)\)(.*)$/);if(!methodMatch?.[1]||methodMatch[2]===undefined||methodMatch[3]===undefined)return null;const method=methodMatch[1];const args=methodMatch[2].trim();const rest=methodMatch[3];if(method==="timestamps"){return{kind:"columns",columns:[{name:"created_at",type:"DATETIME",nullable:true,unique:false,primaryKey:false,autoIncrement:false,defaultValue:"CURRENT_TIMESTAMP",index:false},{name:"updated_at",type:"DATETIME",nullable:true,unique:false,primaryKey:false,autoIncrement:false,defaultValue:null,index:false}]}}if(method==="softDeletes"){return{kind:"columns",columns:[{name:"deleted_at",type:"DATETIME",nullable:true,unique:false,primaryKey:false,autoIncrement:false,defaultValue:null,index:false}]}}if(method==="rememberToken"){return{kind:"columns",columns:[{name:"remember_token",type:"TEXT",nullable:true,unique:false,primaryKey:false,autoIncrement:false,defaultValue:null,index:false}]}}if(method==="id"||method==="increments"||method==="bigIncrements"){const name=parseStringArg(args)||"id";return{kind:"columns",columns:[{name,type:"INTEGER",nullable:false,unique:false,primaryKey:true,autoIncrement:true,defaultValue:null,index:false}]}}if(method==="index"||method==="unique"){const cols=parseIndexArg(args);if(cols.length===0)return{kind:"skip"};return{kind:"index",index:{name:"",columns:cols,unique:method==="unique"}}}const columnName=parseStringArg(args);if(!columnName)return null;const sqlType=mapType(method);if(!sqlType)return{kind:"skip"};const column={name:columnName,type:sqlType,nullable:false,unique:false,primaryKey:false,autoIncrement:false,defaultValue:null,index:false};applyModifiers(rest,column);const indexes=[];if(column.unique)indexes.push({name:"",columns:[columnName],unique:true});if(column.index)indexes.push({name:"",columns:[columnName],unique:false});return{kind:"columns",columns:[column],indexes}}function applyModifiers(rest,column){const modRegex=/->([a-zA-Z_]+)\s*\(([^)]*)\)/g;let match;while((match=modRegex.exec(rest))!==null){const mod=match[1];const args=match[2]?.trim()??"";if(!mod)continue;switch(mod){case"nullable":column.nullable=true;break;case"unique":column.unique=true;break;case"index":column.index=true;break;case"default":column.defaultValue=parseDefaultArg(args);break;case"primary":column.primaryKey=true;break;case"autoIncrement":column.autoIncrement=true;break;case"unsigned":case"comment":case"after":case"change":break;default:break}}}function parseStringArg(args){const m=args.match(/^['"]([^'"]+)['"]/);return m?.[1]??null}function parseIndexArg(args){const single=parseStringArg(args);if(single)return[single];const arr=args.match(/\[([^\]]*)\]/);if(!arr?.[1])return[];return arr[1].split(",").map((s)=>s.trim().replace(/^['"]|['"]$/g,"")).filter(Boolean)}function parseDefaultArg(args){const stringMatch=args.match(/^['"]([^'"]*)['"]/);if(stringMatch?.[1]!==undefined)return`'${stringMatch[1].replace(/'/g,"''")}'`;const trimmed=args.trim();if(trimmed==="true")return"1";if(trimmed==="false")return"0";if(trimmed==="null")return"NULL";if(/^-?\d+(\.\d+)?$/.test(trimmed))return trimmed;return trimmed}const TYPE_MAP={string:"TEXT",text:"TEXT",mediumText:"TEXT",longText:"TEXT",char:"TEXT",integer:"INTEGER",tinyInteger:"INTEGER",smallInteger:"INTEGER",mediumInteger:"INTEGER",bigInteger:"INTEGER",unsignedBigInteger:"INTEGER",unsignedInteger:"INTEGER",foreignId:"INTEGER",boolean:"INTEGER",date:"DATE",dateTime:"DATETIME",dateTimeTz:"DATETIME",timestamp:"DATETIME",timestampTz:"DATETIME",time:"TIME",timeTz:"TIME",year:"INTEGER",json:"TEXT",jsonb:"TEXT",uuid:"TEXT",ulid:"TEXT",ipAddress:"TEXT",macAddress:"TEXT",float:"REAL",double:"REAL",decimal:"REAL",binary:"BLOB",enum:"TEXT",set:"TEXT"};function mapType(laravelMethod){return TYPE_MAP[laravelMethod]??null}function emitCreateTable(table,columns,indexes){const lines=[];lines.push(`CREATE TABLE IF NOT EXISTS ${table} (`);const colDefs=columns.map((c)=>{const parts=[` ${c.name} ${c.type}`];if(c.primaryKey)parts.push("PRIMARY KEY");if(c.autoIncrement)parts.push("AUTOINCREMENT");if(!c.nullable&&!c.primaryKey)parts.push("NOT NULL");if(c.defaultValue!==null)parts.push(`DEFAULT ${c.defaultValue}`);return parts.join(" ")});lines.push(colDefs.join(`,
|
|
3
|
+
`));lines.push(");");for(const idx of indexes){const cols=idx.columns.join(", ");const indexName=idx.name||`${table}_${idx.columns.join("_")}_${idx.unique?"unique":"index"}`;const verb=idx.unique?"CREATE UNIQUE INDEX":"CREATE INDEX";lines.push(`${verb} IF NOT EXISTS ${indexName} ON ${table}(${cols});`)}return`${lines.join(`
|
|
4
4
|
`)}
|
|
5
|
-
`}export function laravelFilenameToStacks(filename,sequence,table){const padded=String(sequence).padStart(10,"0")
|
|
5
|
+
`}export function laravelFilenameToStacks(filename,sequence,table){const padded=String(sequence).padStart(10,"0");const base=filename.toLowerCase();if(base.includes("create_")&&base.includes("_table"))return`${padded}-create-${table}-table.sql`;if(base.includes("add_")||base.includes("alter_"))return`${padded}-alter-${table}-migration.sql`;return`${padded}-create-${table}-table.sql`}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
const RELATION_KINDS=["belongsTo","hasMany","hasOne","belongsToMany"];export function parseLaravelModel(source){const classMatch=source.match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/);if(!classMatch?.[1])return null;const className=classMatch[1]
|
|
1
|
+
const RELATION_KINDS=["belongsTo","hasMany","hasOne","belongsToMany"];export function parseLaravelModel(source){const classMatch=source.match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/);if(!classMatch?.[1])return null;const className=classMatch[1];const table=extractStringProperty(source,"table")??snakeCasePlural(className);const fillable=extractArrayProperty(source,"fillable");const hidden=extractArrayProperty(source,"hidden");const casts=extractKeyedArrayProperty(source,"casts");const relationships=extractRelationships(source);const notes=[];if(/protected\s+\$appends\s*=/.test(source))notes.push("$appends accessors require a custom Stacks computed-attribute setup");if(/protected\s+\$dates\s*=/.test(source))notes.push("$dates is implicit in Stacks - datetime columns are already typed via validation rules");if(/\buse\b[^;]*\bSoftDeletes\b/.test(source))notes.push("SoftDeletes trait → enable `useDeletedAt` (or matching trait) in the Stacks model traits block");if(/\buse\b[^;]*\bHasFactory\b/.test(source))notes.push("HasFactory → Stacks generates factories automatically when `useSeeder` is enabled");const tsSource=emitStacksModel({className,table,fillable,hidden,casts,relationships});return{className,table,fillable,hidden,casts,relationships,tsSource,notes}}function extractStringProperty(source,name){const re=new RegExp(`protected\\s+\\$${name}\\s*=\\s*['"]([^'"]+)['"]`);const m=source.match(re);return m?.[1]??null}function extractArrayProperty(source,name){const re=new RegExp(`protected\\s+\\$${name}\\s*=\\s*\\[([^\\]]*)\\]`,"s");const m=source.match(re);if(!m?.[1])return[];return m[1].split(",").map((s)=>s.trim().replace(/^['"]|['"]$/g,"")).filter(Boolean)}function extractKeyedArrayProperty(source,name){const re=new RegExp(`protected\\s+\\$${name}\\s*=\\s*\\[([^\\]]*)\\]`,"s");const m=source.match(re);if(!m?.[1])return{};const out={};const pairs=m[1].split(",");for(const pair of pairs){const kv=pair.match(/['"]([^'"]+)['"]\s*=>\s*['"]([^'"]+)['"]/);if(kv?.[1]&&kv[2]!==undefined)out[kv[1]]=kv[2]}return out}function extractRelationships(source){const found=[];const methodRegex=/public\s+function\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\([^)]*\)\s*(?::\s*[^\{]+)?\{[\s\S]*?return\s+\$this\s*->\s*(belongsTo|hasMany|hasOne|belongsToMany)\s*\(\s*([A-Z][A-Za-z0-9_]*)::class/g;let m;while((m=methodRegex.exec(source))!==null){const name=m[1];const kind=m[2];const target=m[3];if(!name||!kind||!target)continue;found.push({name,kind,target})}return found}function emitStacksModel(args){const attributeNames=unique([...args.fillable,...Object.keys(args.casts)]);const attrBlock=attributeNames.length===0?" attributes: {},":` attributes: {
|
|
2
2
|
${attributeNames.map((n)=>emitAttribute(n,args)).join(`
|
|
3
3
|
`)}
|
|
4
|
-
}
|
|
4
|
+
},`;const relationsBlock=args.relationships.length===0?"":`
|
|
5
5
|
// Relationships translated from Eloquent - refine targets / foreign keys to match your schema.
|
|
6
6
|
relations: {
|
|
7
7
|
${args.relationships.map((r)=>` ${r.name}: { type: '${r.kind}', target: '${r.target}' },`).join(`
|
|
@@ -22,10 +22,10 @@ export default defineModel({
|
|
|
22
22
|
${relationsBlock}
|
|
23
23
|
${attrBlock}
|
|
24
24
|
} as const)
|
|
25
|
-
`}function emitAttribute(name,args){const rule=ruleForCast(args.casts[name])??"schema.string()"
|
|
25
|
+
`}function emitAttribute(name,args){const rule=ruleForCast(args.casts[name])??"schema.string()";const fillable=args.fillable.includes(name);const hidden=args.hidden.includes(name);const notes=[];if(hidden)notes.push("hidden from API responses in source - handle via your Stacks resource/transformer");const noteLine=notes.length>0?` // ${notes.join("; ")}
|
|
26
26
|
`:"";return` ${name}: {
|
|
27
27
|
fillable: ${fillable},
|
|
28
28
|
${noteLine} validation: {
|
|
29
29
|
rule: ${rule},
|
|
30
30
|
},
|
|
31
|
-
},`}function ruleForCast(cast){if(!cast)return null;
|
|
31
|
+
},`}function ruleForCast(cast){if(!cast)return null;const head=cast.split(":")[0];switch(head){case"integer":case"int":return"schema.number().int()";case"float":case"double":case"real":return"schema.number()";case"boolean":case"bool":return"schema.boolean()";case"string":return"schema.string()";case"array":case"collection":case"json":case"object":return"schema.unknown()";case"date":case"datetime":case"immutable_date":case"immutable_datetime":return"schema.string()";case"decimal":return"schema.number()";default:return null}}function snakeCasePlural(className){const snake=className.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase();if(snake.endsWith("y")&&!/[aeiou]y$/.test(snake))return`${snake.slice(0,-1)}ies`;if(snake.endsWith("s")||snake.endsWith("x")||snake.endsWith("z")||snake.endsWith("ch")||snake.endsWith("sh"))return`${snake}es`;return`${snake}s`}function unique(arr){return[...new Set(arr)]}
|
package/dist/native-project.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{chmodSync,existsSync,mkdirSync,readdirSync,readFileSync,writeFileSync}from"node:fs";import{basename,join,resolve}from"node:path";import{pathToFileURL}from"node:url";import{nativeProjectTemplates}from"./native-project-templates";import{setEnv}from"@stacksjs/env/cli";import{generateAppKey}from"@stacksjs/security/key";import{auditNativeEnvironment,defaultCraftRuntime,prepareNativeAppBuild,readNativeAppConfig,recordNativeArtifact}from"ts-pantry/native";export function isNativeProject(root){try{return JSON.parse(readFileSync(join(root,"package.json"),"utf8")).stacks?.type==="native"}catch{return
|
|
1
|
+
import{chmodSync,existsSync,mkdirSync,readdirSync,readFileSync,writeFileSync}from"node:fs";import{basename,join,resolve}from"node:path";import{pathToFileURL}from"node:url";import{nativeProjectTemplates}from"./native-project-templates";import{setEnv}from"@stacksjs/env/cli";import{generateAppKey}from"@stacksjs/security/key";import{auditNativeEnvironment,defaultCraftRuntime,prepareNativeAppBuild,readNativeAppConfig,recordNativeArtifact}from"ts-pantry/native";export function isNativeProject(root){try{return JSON.parse(readFileSync(join(root,"package.json"),"utf8")).stacks?.type==="native"}catch{return false}}export function scaffoldNativeProject(root,options){const manifest=join(root,"package.json");if(existsSync(root)&&readdirSync(root).some((name)=>name!==".git")&&!options.adopt)throw new Error(`Path ${root} already exists. Use --adopt to integrate an existing native app.`);if(options.adopt&&(!existsSync(manifest)||!existsSync(join(root,"craft.config.ts"))))throw new Error("--adopt requires package.json and craft.config.ts; no files were changed.");const pkg=existsSync(manifest)?JSON.parse(readFileSync(manifest,"utf8")):{name:basename(root),version:"0.1.0",description:"A Stacks native app"};if(pkg.stacks?.type&&pkg.stacks.type!=="native")throw new Error("This project already declares a different Stacks application type.");const name=basename(root).replace(/(^|[-_ ])\w/g,(word)=>word.replace(/[-_ ]/g," ").toUpperCase());pkg.stacks={...pkg.stacks,type:"native"};pkg.devDependencies={"@buddysh/buddy":"^0.11.13","@stacksjs/buddy":`^${options.buddyVersion}`,...pkg.devDependencies};pkg.dependencies={"@stacksjs/stx":`^${options.stxVersion}`,"@stacksjs/desktop":`^${options.stxVersion}`,...pkg.dependencies};pkg.scripts={dev:"./buddy dev",build:"./buddy build",package:"./buddy package","release:patch":"./buddy release --bump patch","release:minor":"./buddy release --bump minor","release:major":"./buddy release --bump major",...pkg.scripts};mkdirSync(root,{recursive:true});const writeMissing=(name,content)=>{const file=join(root,name);if(existsSync(file))return;mkdirSync(resolve(file,".."),{recursive:true});writeFileSync(file,content)};writeMissing("buddy",`#!/bin/sh
|
|
2
2
|
set -eu
|
|
3
3
|
cd -- "$(dirname -- "$0")"
|
|
4
4
|
BUDDY_NATIVE_ENTRY=$(bun --print 'Bun.resolveSync("@stacksjs/buddy/cli", process.cwd())')
|
|
@@ -10,29 +10,29 @@ exec bun "$BUDDY_NATIVE_ENTRY" "$@"
|
|
|
10
10
|
bundleId: ${JSON.stringify(`com.example.${basename(root).toLowerCase().replace(/[^a-z0-9-]/g,"-")}`)},
|
|
11
11
|
window: { title: ${JSON.stringify(name)}, width: 640, height: 480 },
|
|
12
12
|
}
|
|
13
|
-
`);const pantryFile=join(root,"pantry.json")
|
|
13
|
+
`);const pantryFile=join(root,"pantry.json");const pantry=existsSync(pantryFile)?JSON.parse(readFileSync(pantryFile,"utf8")):{};pantry.native={environment:"production",runtime:defaultCraftRuntime,...pantry.native,macos:{notarize:true,...pantry.native?.macos}};writeFileSync(pantryFile,`${JSON.stringify(pantry,null,2)}
|
|
14
14
|
`);if(!options.adopt)writeMissing("src/app.stx",`<!doctype html>
|
|
15
15
|
<html lang="en">
|
|
16
16
|
<head><meta charset="utf-8"><title>${name.replace(/&/g,"&").replace(/</g,"<")}</title></head>
|
|
17
17
|
<body><h1>${name.replace(/&/g,"&").replace(/</g,"<")}</h1><p>Your Stacks native app is ready.</p></body>
|
|
18
18
|
</html>
|
|
19
|
-
`);for(const[destination,source]of Object.entries(nativeProjectTemplates))writeMissing(destination,source.replaceAll("__APP_SLUG__",pkg.name??basename(root)));writeMissing(".github/renovate.json",`${JSON.stringify({enabled
|
|
19
|
+
`);for(const[destination,source]of Object.entries(nativeProjectTemplates))writeMissing(destination,source.replaceAll("__APP_SLUG__",pkg.name??basename(root)));writeMissing(".github/renovate.json",`${JSON.stringify({enabled:false},null,2)}
|
|
20
20
|
`);writeMissing(".gitignore",`node_modules/
|
|
21
21
|
dist/
|
|
22
22
|
.stx/
|
|
23
23
|
.pantry/
|
|
24
|
-
`);const ignoreFile=join(root,".gitignore");let ignore=readFileSync(ignoreFile,"utf8");for(const pattern of[".env.keys",".env.local",".env.*.local"])if(!ignore.split(`
|
|
24
|
+
`);const ignoreFile=join(root,".gitignore");let ignore=readFileSync(ignoreFile,"utf8");for(const pattern of[".env.keys",".env.local",".env.*.local"]){if(!ignore.split(`
|
|
25
25
|
`).includes(pattern))ignore=`${ignore.trimEnd()}
|
|
26
26
|
${pattern}
|
|
27
|
-
|
|
27
|
+
`}writeFileSync(ignoreFile,ignore);if(!existsSync(join(root,".env.production"))){for(const[key,value]of Object.entries({APP_ENV:"production",APP_KEY:generateAppKey()})){const result=setEnv(key,value,{cwd:root,file:".env.production"});if(!result.success)throw new Error(result.error||"Could not create the native production environment")}}auditNativeEnvironment(root,"production");if(!ignore.split(`
|
|
28
28
|
`).includes("!.env.production"))writeFileSync(ignoreFile,`${ignore.trimEnd()}
|
|
29
29
|
!.env.production
|
|
30
30
|
`);writeFileSync(manifest,`${JSON.stringify(pkg,null,2)}
|
|
31
|
-
`)}export async function buildNativeProject(root,args=[]){const pkg=await Bun.file(join(root,"package.json")).json()
|
|
31
|
+
`)}export async function buildNativeProject(root,args=[]){const pkg=await Bun.file(join(root,"package.json")).json();const loaded=await import(pathToFileURL(join(root,"craft.config.ts")).href);const config=loaded.default??loaded.config;if(!config||typeof config!=="object")throw new Error("craft.config.ts must export a native build configuration.");const{buildNative}=await import(pathToFileURL(Bun.resolveSync("@stacksjs/stx/craft",root)).href);const prepared=await prepareNativeAppBuild(root,config);try{const output=resolve(root,prepared.overrides.output??config.output??"dist");if(output===root||!output.startsWith(`${root}/`))throw new Error("Native output must be a directory inside the app.");const buildNumber=process.env.PANTRY_BUILD_NUMBER||config.infoPlist?.CFBundleVersion||pkg.version;const result=await buildNative({...config,...prepared.overrides,input:resolve(root,config.input??"src/app.stx"),output,version:pkg.version,description:pkg.description,author:pkg.author,infoPlist:{...config.infoPlist,CFBundleVersion:buildNumber},...config.icon?{icon:resolve(root,config.icon)}:{},...config.backend?{backend:{...config.backend,entry:resolve(root,config.backend.entry)}}:{},...args.includes("--dmg")?{format:"dmg"}:{},verbose:args.includes("--verbose")});if(!result.success||!result.outputPath)throw new Error(result.error??"Native build produced no artifact.");if(readNativeAppConfig(root))recordNativeArtifact(root,{path:result.outputPath,...result.target==="macos"?{appPath:join(output,`${config.name}.app`)}:{},name:config.name,bundleId:config.bundleId,version:pkg.version,buildNumber:String(buildNumber),target:result.target,minimumSystemVersion:config.minimumSystemVersion});return result.outputPath}finally{prepared.cleanup()}}export async function runNativeProjectCommand(root,args){const[command="help",...flags]=args;if(!["build","build:desktop","build:native","package","dev","dev:desktop","dev:native","upgrade","update","release","desktop:apple:package","desktop:apple:publish","desktop:apple:submit"].includes(command))return false;if(flags.includes("--site")){const{runNativeSiteCommand}=await import("./native-site");await runNativeSiteCommand(root,command,flags);return true}if(flags.includes("--help")||flags.includes("-h")){console.log(`buddy ${command} (native app)
|
|
32
32
|
|
|
33
33
|
Build: --dmg --verbose
|
|
34
34
|
Upgrade: --dry-run
|
|
35
35
|
Release: --bump patch|minor|major --dry-run
|
|
36
36
|
Apple: --build-number N --validate-only --submit-for-review
|
|
37
37
|
|
|
38
|
-
Application: craft.config.ts. Runtime and publishing: pantry.json. Development runtime override: CRAFT_BIN.`);return
|
|
38
|
+
Application: craft.config.ts. Runtime and publishing: pantry.json. Development runtime override: CRAFT_BIN.`);return true}if(command.startsWith("desktop:apple:")){const options=parseNativeAppleFlags(flags);const{publishNativeApple,submitNativeApple}=await import("ts-pantry/native");if(command==="desktop:apple:submit"){if(!options.buildNumber)throw new Error("Submitting an uploaded build requires --build-number N");if(options.validateOnly||options.packageOnly)throw new Error("Submit does not support package-only or validation-only");const loaded=await import(pathToFileURL(join(root,"craft.config.ts")).href);const config=loaded.default??loaded.config;if(!config?.bundleId)throw new Error("craft.config.ts must declare bundleId");await submitNativeApple(root,{...options,buildNumber:options.buildNumber,bundleId:config.bundleId})}else{await publishNativeApple(root,{...options,...command==="desktop:apple:package"?{packageOnly:true}:{}})}return true}if(command==="release"){const index=flags.indexOf("--bump");const bump=index>=0?flags[index+1]:"patch";if(!bump||!["patch","minor","major"].includes(bump)||flags.some((flag,position)=>flag!=="--dry-run"&&flag!=="--bump"&&!(index>=0&&position===index+1)))throw new Error("Native releases support --bump patch|minor|major and --dry-run");const{releaseNativeApp}=await import("ts-pantry/native/release");await releaseNativeApp(root,{bump,dryRun:flags.includes("--dry-run")});return true}if(command==="upgrade"||command==="update"){if(flags.some((flag)=>flag!=="--dry-run"&&flag!=="--verbose"))throw new Error("Native upgrades support --dry-run and --verbose. Use bun add to select a specific package version.");if(flags.includes("--dry-run"))console.log("Would run bun update for the native app; no files changed.");else{const proc=Bun.spawn(["bun","update"],{cwd:root,stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(await proc.exited!==0)throw new Error("Native dependency upgrade failed.")}return true}const artifact=await buildNativeProject(root,command==="package"?[...flags,"--dmg"]:flags);console.log(`Built ${artifact}`);if(command.startsWith("dev")){const config=(await import(pathToFileURL(join(root,"craft.config.ts")).href)).default;if(process.platform!=="darwin")throw new Error("Native development launch currently requires macOS.");const executable=join(artifact,"Contents","MacOS",config.name);const child=Bun.spawn([executable],{cwd:root,stdin:"inherit",stdout:"inherit",stderr:"inherit"});let interrupted=false;const stop=()=>{interrupted=true;child.kill("SIGTERM")};process.once("SIGINT",stop);process.once("SIGTERM",stop);try{const code=await child.exited;if(code!==0&&!interrupted)throw new Error(`Native app exited with ${child.signalCode??`code ${code}`}.`)}finally{process.removeListener("SIGINT",stop);process.removeListener("SIGTERM",stop)}}return true}export function parseNativeAppleFlags(flags){const options={};for(let index=0;index<flags.length;index++){const flag=flags[index];if(flag==="--build-number"){const value=flags[++index];if(!value||!/^[1-9]\d*$/.test(value))throw new Error("--build-number requires a positive integer");options.buildNumber=value}else if(flag==="--package-only")options.packageOnly=true;else if(flag==="--validate-only")options.validateOnly=true;else if(flag==="--submit-for-review")options.submitForReview=true;else throw new Error(`Unsupported native Apple option: ${flag}`)}if(options.packageOnly&&(options.validateOnly||options.submitForReview))throw new Error("Package-only cannot validate or submit a release");if(options.validateOnly&&options.submitForReview)throw new Error("Validation-only cannot submit a release");return options}
|
package/dist/native-site.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{join}from"node:path";import{pathToFileURL}from"node:url";export async function runNativeSiteCommand(root,command,flags){if(!["dev","build"].includes(command))throw Error("--site supports buddy dev and buddy build. Desktop packaging uses craft.config.ts.");if(flags.includes("--help")||flags.includes("-h")){console.log(`buddy dev --site [--port N]
|
|
1
|
+
import{join}from"node:path";import{pathToFileURL}from"node:url";export async function runNativeSiteCommand(root,command,flags){if(!["dev","build"].includes(command))throw new Error("--site supports buddy dev and buddy build. Desktop packaging uses craft.config.ts.");if(flags.includes("--help")||flags.includes("-h")){console.log(`buddy dev --site [--port N]
|
|
2
2
|
buddy build --site
|
|
3
3
|
|
|
4
|
-
Website pages: stx.config.ts root/pagesDir. Static assets: publicDir. Output: dist/site. Desktop entry: craft.config.ts.`);return}let port=3000;for(let index=0;index<flags.length;index++){const flag=flags[index];if(flag==="--site")continue;if(command==="dev"&&flag==="--port"){const value=flags[++index];if(!value||!/^\d+$/.test(value)||Number(value)<1||Number(value)>65535)throw Error("--port requires an integer from 1 to 65535");port=Number(value);continue}throw Error(`Unsupported website option: ${flag}`)}const load=(entry)=>import(pathToFileURL(Bun.resolveSync(`@stacksjs/stx/${entry}`,root)).href);if(command==="build"){const{buildApp}=await load("build")
|
|
4
|
+
Website pages: stx.config.ts root/pagesDir. Static assets: publicDir. Output: dist/site. Desktop entry: craft.config.ts.`);return}let port=3000;for(let index=0;index<flags.length;index++){const flag=flags[index];if(flag==="--site")continue;if(command==="dev"&&flag==="--port"){const value=flags[++index];if(!value||!/^\d+$/.test(value)||Number(value)<1||Number(value)>65535)throw new Error("--port requires an integer from 1 to 65535");port=Number(value);continue}throw new Error(`Unsupported website option: ${flag}`)}const load=(entry)=>import(pathToFileURL(Bun.resolveSync(`@stacksjs/stx/${entry}`,root)).href);if(command==="build"){const{buildApp}=await load("build");const outputDir=join(root,"dist/site");const result=await buildApp({root,ssg:{outputDir},ssr:{outputDir}});if(result.ssg?.failedCount)throw new Error("Website build failed. See the stx diagnostics above.");console.log(`Built website: ${outputDir}`);return}const{serveApp}=await load("dev-server");if(!await serveApp(root,{port,hostname:"127.0.0.1",native:false}))throw new Error("Website development server could not start. Configure website pages in stx.config.ts.");await new Promise(()=>{})}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync,readFileSync,realpathSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{join}from"node:path";const DATABASE_SERVICES={mysql:"mysql",postgres:"postgres"};function canonical(path){try{return realpathSync(path)}catch{return path}}export function pantryPortsFile(home=homedir()){return join(home,".local","share","pantry","ports.json")}export function assignedServicePort(root,service,home=homedir()){const file=pantryPortsFile(home);if(!existsSync(file))return;let assignments;try{assignments=JSON.parse(readFileSync(file,"utf8")).assignments??[]}catch{return}const wanted=canonical(root);
|
|
1
|
+
import{existsSync,readFileSync,realpathSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{join}from"node:path";const DATABASE_SERVICES={mysql:"mysql",postgres:"postgres"};function canonical(path){try{return realpathSync(path)}catch{return path}}export function pantryPortsFile(home=homedir()){return join(home,".local","share","pantry","ports.json")}export function assignedServicePort(root,service,home=homedir()){const file=pantryPortsFile(home);if(!existsSync(file))return;let assignments;try{assignments=JSON.parse(readFileSync(file,"utf8")).assignments??[]}catch{return}const wanted=canonical(root);const match=assignments.find((entry)=>entry.service===service&&typeof entry.port==="number"&&!!entry.root&&canonical(entry.root)===wanted);return match?.port}function envValue(contents,key){const match=contents.match(new RegExp(`^${key}=(.*)$`,"m"));return match?.[1]?.trim().replace(/^['"]|['"]$/g,"")}export function syncDatabasePortToEnv(cwd,home=homedir()){const envPath=join(cwd,".env");if(!existsSync(envPath))return{changed:false};const contents=readFileSync(envPath,"utf8");const service=DATABASE_SERVICES[envValue(contents,"DB_CONNECTION")??""];if(!service)return{changed:false};const host=envValue(contents,"DB_HOST")||"127.0.0.1";if(!["127.0.0.1","localhost","::1"].includes(host))return{service,changed:false};const port=assignedServicePort(cwd,service,home);if(port===undefined||envValue(contents,"DB_PORT")===String(port))return{service,port,changed:false};const next=/^DB_PORT=.*$/m.test(contents)?contents.replace(/^DB_PORT=.*$/m,`DB_PORT=${port}`):`${contents.replace(/\n*$/,`
|
|
2
2
|
`)}DB_PORT=${port}
|
|
3
|
-
`;writeFileSync(envPath,next);return{service,port,changed
|
|
3
|
+
`;writeFileSync(envPath,next);return{service,port,changed:true}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{enterRequestScope,installRequestScope}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{siteConfigPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resolveStxSource}from"@stacksjs/actions";import{serverRequestBodyOptions}from"@stacksjs/server/request-body";import{beginRequestCapture,finishRequestCapture}from"@stacksjs/router/request-capture";installRequestScope();export function resolveUserPartialsPath(cwd=process.cwd(),configuredDir){if(configuredDir){const configured=[join(cwd,"resources",configuredDir),join(cwd,configuredDir)].find((candidate)=>existsSync(candidate));if(configured)return configured}const existing=["resources/partials","resources/views/partials","partials","resources/components"].filter((candidate)=>existsSync(join(cwd,candidate)));if(existing.length===0)return;const populated=existing.find((candidate)=>containsTemplates(join(cwd,candidate)));return join(cwd,populated??existing[0])}function containsTemplates(dir){try{return[...new Bun.Glob("**/*.stx").scanSync({cwd:dir,onlyFiles:!0})].length>0}catch{return!1}}export async function loadStxPartialsDir(cwd=process.cwd()){for(const name of["stx","ui"]){const configPath=join(cwd,`config/${name}.ts`);if(!existsSync(configPath))continue;try{const dir=(await import(configPath)).default?.partialsDir;if(typeof dir==="string"&&dir.length>0)return dir}catch{}}return}function resolveCsrfMiddlewarePath(){const rel="app/Middleware/Csrf.ts",vendored=join(process.cwd(),"storage/framework/defaults",rel);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return`${pkgJson.slice(0,pkgJson.lastIndexOf("/"))}/${rel}`}catch{return vendored}}export async function startProductionServer(options){if(options?.port)process.env.PORT=String(options.port);process.env.APP_ENV=process.env.APP_ENV||"production";const port=Number(process.env.PORT)||3000,{config,feature,overridesReady,resolveViewPatterns}=await import("@stacksjs/config");await overridesReady;const{ensureDiscoveredPackages}=await import("@stacksjs/actions");await ensureDiscoveredPackages();const{applyResponseHeaders,applyViewSecurityHeaders,describeApiProxyRules,describeRedirectRules,describeRewriteRules,injectGlobalAutoImports,loadRouteRedirects,resolveApiBase,resolveApiProxyRules,resolveEmbeddableRules,resolveRedirectRules,resolveRewriteRules,viewClientAddress}=await import("@stacksjs/server"),{resolveDefaultsResources}=await import("@stacksjs/actions/dev/defaults-resources"),{stxPageAuthMiddleware}=await import("@stacksjs/auth"),{enhanceRequest,loadMiddlewareHandlers,registerPeerSource}=await import("@stacksjs/router"),pageMiddleware=await loadMiddlewareHandlers();try{const{autoImportsAreStale,generateAutoImportFiles}=await import("@stacksjs/server");if(autoImportsAreStale()){log.info("[server] Installed packages moved since the auto-import barrel was written; rebuilding it.");await generateAutoImportFiles({declarations:!1})}}catch(error){log.warn(`[server] Could not refresh the auto-import barrel: ${error instanceof Error?error.message:String(error)}`)}await injectGlobalAutoImports();let stxServe;const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing")await log.exit(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`,ExitCode.FatalError);if(serveSource.kind==="override"){({serve:stxServe}=await import(serveSource.path));log.warn(`Serving views through ${serveSource.path} instead of the installed bun-plugin-stx.`)}else({serve:stxServe}=await import("bun-plugin-stx/serve"));log.debug(`stx serve implementation: ${serveSource.kind==="override"?serveSource.path:"bun-plugin-stx/serve"}`);const stxModule=await resolveVendoredStxModule(),{site:siteConfig,i18n:i18nConfig}=await loadStxSiteConfig(),userViewsPath="resources/views",defaultsResources=resolveDefaultsResources(),defaultViewsPath=join(defaultsResources,"views"),userLayoutsPath=existsSync("resources/views/layouts")?"resources/views/layouts":"resources/layouts",userComponentsPath=existsSync("resources/views/components")?"resources/views/components":"resources/components",userPartialsPath=resolveUserPartialsPath(process.cwd(),await loadStxPartialsDir()),apiBase=resolveApiBase(config.ports?.api),{mountedDefaultRouteBundles}=await import("@stacksjs/router"),viewPatterns=resolveViewPatterns(userViewsPath,defaultViewsPath,config?.ui?.defaultViews,void 0,void 0,mountedDefaultRouteBundles(feature));for(const name of viewPatterns.missing)log.warn(`ui.defaultViews lists "${name}", which does not exist under ${defaultViewsPath} - ignoring.`);if(viewPatterns.withheld.length>0)log.info(`Default views without a mounted route bundle behind them, not served: ${viewPatterns.withheld.join(", ")}`);const apiProxyRules=resolveApiProxyRules(config.server?.proxy);if(apiProxyRules.paths.length>0||apiProxyRules.prefixes.length>1)log.info(`API proxy: ${describeApiProxyRules(apiProxyRules)}`);const redirectRules=resolveRedirectRules({...await loadRouteRedirects(),...config.server?.redirects});if(redirectRules.size>0)log.info(`Redirects: ${describeRedirectRules(redirectRules)}`);const rewriteRules=resolveRewriteRules(config.server?.rewrites);if(rewriteRules.size>0)log.info(`Rewrites: ${describeRewriteRules(rewriteRules)}`);const{createSiteSeoHandler,describeSeoAtBoot}=await import("@stacksjs/actions/seo"),seoOptions={root:process.cwd(),seo:config.app?.seo,appUrl:config.app?.url},siteSeo=createSiteSeoHandler({...seoOptions,cacheTtlMs:600000});for(const note of await describeSeoAtBoot(seoOptions).catch(()=>[]))log.warn(note);const cacheConfig=config.server?.cache,documentCacheControl=buildDocumentCacheControl(cacheConfig?.documents);if(cacheConfig?.renders)log.info(`Render cache: on, keyed by ${cacheConfig.renderVary??"request"}${cacheConfig.prewarm?", prewarmed":""}`);if(documentCacheControl)log.info(`Document cache: ${documentCacheControl}`);const embeddableRules=resolveEmbeddableRules(config.server?.security?.embeddable);if(embeddableRules.paths.length>0||embeddableRules.prefixes.length>0)log.info(`Frameable by other origins: ${[...embeddableRules.paths,...embeddableRules.prefixes].join(" ")}`);log.info(`Starting production server on port ${port}...`);await stxServe({...serverRequestBodyOptions(config.server?.maxRequestBodySize),patterns:viewPatterns.patterns,exclude:viewPatterns.exclude,port,autoIncrementPort:!1,reusePort:["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase()),componentsDir:userComponentsPath,fallbackComponentsDir:join(defaultsResources,"components"),layoutsDir:userLayoutsPath,...userPartialsPath&&{partialsDir:userPartialsPath},fallbackLayoutsDir:join(defaultsResources,"layouts"),fallbackPartialsDir:defaultViewsPath,quiet:options?.verbose!==!0,...cacheConfig?.renders&&{renderCache:!0,renderCacheVary:cacheConfig.renderVary??"request",...cacheConfig.prewarm&&{prewarmRenderCache:!0}},...stxModule&&{stxModule},...i18nConfig&&{i18n:i18nConfig},...siteConfig?.url&&{site:siteConfig},...config.server?.domains&&{domains:config.server.domains},middleware:{...pageMiddleware,...stxPageAuthMiddleware()},prepareMiddlewareRequest:(request)=>enhanceRequest(request),clientAddress:viewClientAddress,onRequest:async(req,server)=>{beginRequestCapture(req);const snapshot=enterRequestScope(req);registerPeerSource(server);const{maintenanceGate,isApiBoundRequest:isApiBound,proxyToBackend,resolveRedirect,resolveRewrite}=await import("@stacksjs/server"),gated=await maintenanceGate(req);if(gated)return gated;const url=new URL(req.url),redirected=resolveRedirect(url,redirectRules);if(redirected)return redirected;const rewritten=resolveRewrite(url.pathname,rewriteRules);if(rewritten){if(!apiBase){log.error(`No API target configured for ${url.pathname} (rewritten to ${rewritten}); refusing to proxy.`);return new Response("Bad Gateway",{status:502})}try{const target=new URL(`${rewritten}${url.search}`,url.origin);return await proxyToBackend(new Request(target,req),apiBase,void 0,req)}catch(error){log.error(`Rewrite of ${url.pathname} to ${rewritten} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}const seoFile=await siteSeo(req);if(seoFile)return seoFile;if(isApiBound(req,url.pathname,apiProxyRules)){if(!apiBase){log.error(`No API target configured for ${url.pathname}. This app shares its host with other deployments, so there is no safe default port to guess - refusing to proxy. Set PORT_API (or API_URL) for this site, and deploy an \`api\` site on its own port.`);return new Response("Bad Gateway",{status:502})}try{return await proxyToBackend(req,apiBase)}catch(error){log.error(`API proxy to ${apiBase} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}if(existsSync(join(process.cwd(),"resources/views/blog.stx"))){const{renderBlogFeed}=await import("@stacksjs/actions/blog"),feed=await renderBlogFeed(req);if(feed)return feed}if(config.analytics?.capturePageviews)import("@stacksjs/analytics").then(({recordPageview})=>recordPageview(req)).catch(()=>{});if(config.sites?.enabled){const sites=await import("@stacksjs/sites"),resolved=await sites.resolveSiteByHost(sites.requestHost(req.headers,sites.sitesOptions()));sites.setCurrentSite(resolved);snapshot.site=sites.toSiteSnapshot(resolved)}return},onResponse:async(req,response)=>{const securityResponse=applyViewSecurityHeaders(req,response,embeddableRules),secured=applyResponseHeaders(req,securityResponse??response,config.server?.headers)??securityResponse,method=req.method.toUpperCase();if(method!=="GET"&&method!=="HEAD"){finishRequestCapture(req,secured??response);return secured}const baseline=secured??response;let current=baseline;if(current.status===404&&config.sites?.enabled)try{const{cmsNotFoundFallback}=await import("@stacksjs/cms"),cmsResponse=await cmsNotFoundFallback(req);if(cmsResponse)current=cmsResponse}catch(error){log.debug(`CMS fallback skipped: ${error.message}`)}let finished;try{const{seedCsrfCookieIfMissing}=await import(resolveCsrfMiddlewarePath());finished=await seedCsrfCookieIfMissing(req,current)??(current===baseline?secured:current)}catch(error){log.debug(`CSRF cookie seeding skipped: ${error.message}`);finished=current===baseline?secured:current}if(!documentCacheControl){finishRequestCapture(req,finished??response);return finished}const cached=applyDocumentCacheControl(req,finished??response,documentCacheControl);finishRequestCapture(req,cached??finished??response);return cached}});log.success(`Production server listening on http://0.0.0.0:${port}`)}export function buildDocumentCacheControl(documents){if(!documents)return;const maxAge=Number(documents.maxAge??0);if(!Number.isFinite(maxAge)||maxAge<=0)return;const stale=Number(documents.staleWhileRevalidate??0),parts=["public",`max-age=${Math.floor(maxAge)}`];if(Number.isFinite(stale)&&stale>0)parts.push(`stale-while-revalidate=${Math.floor(stale)}`);return parts.join(", ")}export function isAuthenticatedRequest(request){if(request.headers.get("authorization"))return!0;const cookie=request.headers.get("cookie")||"";if(!cookie)return!1;return cookie.split(";").map((part)=>part.trim().split("=")[0]?.toLowerCase()??"").some((name)=>name!==""&&!name.includes("csrf")&&/session|auth|token|remember/.test(name))}const SPA_NAV_REQUEST_HEADER="X-STX-Router",SPA_NAV_FRAGMENT_HEADER="X-STX-Fragment";export function isSpaFragmentExchange(request,response){return request.headers.get(SPA_NAV_REQUEST_HEADER)==="true"||response.headers.get(SPA_NAV_FRAGMENT_HEADER)==="true"}export function applyDocumentCacheControl(request,response,cacheControl){if(!cacheControl)return response;const contentType=response.headers.get("content-type")||"";if(response.status!==200||!contentType.startsWith("text/html"))return response;if(isSpaFragmentExchange(request,response))return response;if(response.headers.getSetCookie().length>0)return response;if(isAuthenticatedRequest(request))return response;const headers=new Headers(response.headers);headers.set("cache-control",cacheControl);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}async function resolveVendoredStxModule(){const source=resolveStxSource({value:process.env.STACKS_STX_SRC});if(source.kind==="missing")await log.exit(`STACKS_STX_SRC points at ${source.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`,ExitCode.FatalError);if(source.kind==="override"){log.warn(`Rendering through ${source.path} instead of the installed @stacksjs/stx.`);return await import(source.path)}try{return await import("@stacksjs/stx")}catch{}return}function fallbackI18nFromSite(site){const locales=site.i18n.locales,defaultLocale=site.i18n.defaultLocale??locales[0];return{locales,defaultLocale,labels:site.i18n.labels??Object.fromEntries(locales.map((c)=>[c,c.toUpperCase()])),translations:{},pickerSelector:site.i18n.pickerSelector??"#lang-picker"}}async function resolveSiteI18n(site){try{const resolved=await resolveVendoredStxModule();if(typeof resolved?.resolveI18n==="function"){const i18n=resolved.resolveI18n(site,process.cwd());if(i18n)return i18n}}catch{}return fallbackI18nFromSite(site)}async function loadStxSiteConfig(){const sitePath=siteConfigPath();if(!existsSync(sitePath))return{};try{const mod=await import(sitePath),site=mod.default??mod.site??mod.config;if(!site)return{};if(!site.i18n)return{site};const i18n=await resolveSiteI18n(site);return{site,i18n}}catch{}return{}}
|
|
1
|
+
import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{enterRequestScope,installRequestScope}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{siteConfigPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{resolveStxSource}from"@stacksjs/actions";import{serverRequestBodyOptions}from"@stacksjs/server/request-body";import{beginRequestCapture,finishRequestCapture}from"@stacksjs/router/request-capture";installRequestScope();export function resolveUserPartialsPath(cwd=process.cwd(),configuredDir){if(configuredDir){const configured=[join(cwd,"resources",configuredDir),join(cwd,configuredDir)].find((candidate)=>existsSync(candidate));if(configured)return configured}const candidates=["resources/partials","resources/views/partials","partials","resources/components"];const existing=candidates.filter((candidate)=>existsSync(join(cwd,candidate)));if(existing.length===0)return;const populated=existing.find((candidate)=>containsTemplates(join(cwd,candidate)));return join(cwd,populated??existing[0])}function containsTemplates(dir){try{return[...new Bun.Glob("**/*.stx").scanSync({cwd:dir,onlyFiles:true})].length>0}catch{return false}}export async function loadStxPartialsDir(cwd=process.cwd()){for(const name of["stx","ui"]){const configPath=join(cwd,`config/${name}.ts`);if(!existsSync(configPath))continue;try{const mod=await import(configPath);const dir=mod.default?.partialsDir;if(typeof dir==="string"&&dir.length>0)return dir}catch{}}return}function resolveCsrfMiddlewarePath(){const rel="app/Middleware/Csrf.ts";const vendored=join(process.cwd(),"storage/framework/defaults",rel);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return`${pkgJson.slice(0,pkgJson.lastIndexOf("/"))}/${rel}`}catch{return vendored}}export async function startProductionServer(options){if(options?.port)process.env.PORT=String(options.port);process.env.APP_ENV=process.env.APP_ENV||"production";const port=Number(process.env.PORT)||3000;const{config,feature,overridesReady,resolveViewPatterns}=await import("@stacksjs/config");await overridesReady;const{ensureDiscoveredPackages}=await import("@stacksjs/actions");await ensureDiscoveredPackages();const{applyResponseHeaders,applyViewSecurityHeaders,describeApiProxyRules,describeRedirectRules,describeRewriteRules,injectGlobalAutoImports,loadRouteRedirects,resolveApiBase,resolveApiProxyRules,resolveEmbeddableRules,resolveRedirectRules,resolveRewriteRules,viewClientAddress}=await import("@stacksjs/server");const{resolveDefaultsResources}=await import("@stacksjs/actions/dev/defaults-resources");const{stxPageAuthMiddleware}=await import("@stacksjs/auth");const{enhanceRequest,loadMiddlewareHandlers,registerPeerSource}=await import("@stacksjs/router");const pageMiddleware=await loadMiddlewareHandlers();try{const{autoImportsAreStale,generateAutoImportFiles}=await import("@stacksjs/server");if(autoImportsAreStale()){log.info("[server] Installed packages moved since the auto-import barrel was written; rebuilding it.");await generateAutoImportFiles({declarations:false})}}catch(error){log.warn(`[server] Could not refresh the auto-import barrel: ${error instanceof Error?error.message:String(error)}`)}await injectGlobalAutoImports();let stxServe;const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing"){await log.exit(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`,ExitCode.FatalError)}if(serveSource.kind==="override"){({serve:stxServe}=await import(serveSource.path));log.warn(`Serving views through ${serveSource.path} instead of the installed bun-plugin-stx.`)}else{({serve:stxServe}=await import("bun-plugin-stx/serve"))}log.debug(`stx serve implementation: ${serveSource.kind==="override"?serveSource.path:"bun-plugin-stx/serve"}`);const stxModule=await resolveVendoredStxModule();const{site:siteConfig,i18n:i18nConfig}=await loadStxSiteConfig();const userViewsPath="resources/views";const defaultsResources=resolveDefaultsResources();const defaultViewsPath=join(defaultsResources,"views");const userLayoutsPath=existsSync("resources/views/layouts")?"resources/views/layouts":"resources/layouts";const userComponentsPath=existsSync("resources/views/components")?"resources/views/components":"resources/components";const userPartialsPath=resolveUserPartialsPath(process.cwd(),await loadStxPartialsDir());const apiBase=resolveApiBase(config.ports?.api);const{mountedDefaultRouteBundles}=await import("@stacksjs/router");const viewPatterns=resolveViewPatterns(userViewsPath,defaultViewsPath,config?.ui?.defaultViews,undefined,undefined,mountedDefaultRouteBundles(feature));for(const name of viewPatterns.missing)log.warn(`ui.defaultViews lists "${name}", which does not exist under ${defaultViewsPath} - ignoring.`);if(viewPatterns.withheld.length>0)log.info(`Default views without a mounted route bundle behind them, not served: ${viewPatterns.withheld.join(", ")}`);const apiProxyRules=resolveApiProxyRules(config.server?.proxy);if(apiProxyRules.paths.length>0||apiProxyRules.prefixes.length>1)log.info(`API proxy: ${describeApiProxyRules(apiProxyRules)}`);const redirectRules=resolveRedirectRules({...await loadRouteRedirects(),...config.server?.redirects});if(redirectRules.size>0)log.info(`Redirects: ${describeRedirectRules(redirectRules)}`);const rewriteRules=resolveRewriteRules(config.server?.rewrites);if(rewriteRules.size>0)log.info(`Rewrites: ${describeRewriteRules(rewriteRules)}`);const{createSiteSeoHandler,describeSeoAtBoot}=await import("@stacksjs/actions/seo");const seoOptions={root:process.cwd(),seo:config.app?.seo,appUrl:config.app?.url};const siteSeo=createSiteSeoHandler({...seoOptions,cacheTtlMs:600000});for(const note of await describeSeoAtBoot(seoOptions).catch(()=>[]))log.warn(note);const cacheConfig=config.server?.cache;const documentCacheControl=buildDocumentCacheControl(cacheConfig?.documents);if(cacheConfig?.renders)log.info(`Render cache: on, keyed by ${cacheConfig.renderVary??"request"}${cacheConfig.prewarm?", prewarmed":""}`);if(documentCacheControl)log.info(`Document cache: ${documentCacheControl}`);const embeddableRules=resolveEmbeddableRules(config.server?.security?.embeddable);if(embeddableRules.paths.length>0||embeddableRules.prefixes.length>0)log.info(`Frameable by other origins: ${[...embeddableRules.paths,...embeddableRules.prefixes].join(" ")}`);log.info(`Starting production server on port ${port}...`);await stxServe({...serverRequestBodyOptions(config.server?.maxRequestBodySize),patterns:viewPatterns.patterns,exclude:viewPatterns.exclude,port,autoIncrementPort:false,reusePort:["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase()),componentsDir:userComponentsPath,fallbackComponentsDir:join(defaultsResources,"components"),layoutsDir:userLayoutsPath,...userPartialsPath&&{partialsDir:userPartialsPath},fallbackLayoutsDir:join(defaultsResources,"layouts"),fallbackPartialsDir:defaultViewsPath,quiet:options?.verbose!==true,...cacheConfig?.renders&&{renderCache:true,renderCacheVary:cacheConfig.renderVary??"request",...cacheConfig.prewarm&&{prewarmRenderCache:true}},...stxModule&&{stxModule},...i18nConfig&&{i18n:i18nConfig},...siteConfig?.url&&{site:siteConfig},...config.server?.domains&&{domains:config.server.domains},middleware:{...pageMiddleware,...stxPageAuthMiddleware()},prepareMiddlewareRequest:(request)=>enhanceRequest(request),clientAddress:viewClientAddress,onRequest:async(req,server)=>{beginRequestCapture(req);const snapshot=enterRequestScope(req);registerPeerSource(server);const{maintenanceGate,isApiBoundRequest:isApiBound,proxyToBackend,resolveRedirect,resolveRewrite}=await import("@stacksjs/server");const gated=await maintenanceGate(req);if(gated)return gated;const url=new URL(req.url);const redirected=resolveRedirect(url,redirectRules);if(redirected)return redirected;const rewritten=resolveRewrite(url.pathname,rewriteRules);if(rewritten){if(!apiBase){log.error(`No API target configured for ${url.pathname} (rewritten to ${rewritten}); refusing to proxy.`);return new Response("Bad Gateway",{status:502})}try{const target=new URL(`${rewritten}${url.search}`,url.origin);return await proxyToBackend(new Request(target,req),apiBase,undefined,req)}catch(error){log.error(`Rewrite of ${url.pathname} to ${rewritten} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}const seoFile=await siteSeo(req);if(seoFile)return seoFile;if(isApiBound(req,url.pathname,apiProxyRules)){if(!apiBase){log.error(`No API target configured for ${url.pathname}. This app shares its host with other deployments, so there is no safe default port to guess - refusing to proxy. Set PORT_API (or API_URL) for this site, and deploy an \`api\` site on its own port.`);return new Response("Bad Gateway",{status:502})}try{return await proxyToBackend(req,apiBase)}catch(error){log.error(`API proxy to ${apiBase} failed: ${error.message}`);return new Response("Bad Gateway",{status:502})}}if(existsSync(join(process.cwd(),"resources/views/blog.stx"))){const{renderBlogFeed}=await import("@stacksjs/actions/blog");const feed=await renderBlogFeed(req);if(feed)return feed}if(config.analytics?.capturePageviews){import("@stacksjs/analytics").then(({recordPageview})=>recordPageview(req)).catch(()=>{})}if(config.sites?.enabled){const sites=await import("@stacksjs/sites");const resolved=await sites.resolveSiteByHost(sites.requestHost(req.headers,sites.sitesOptions()));sites.setCurrentSite(resolved);snapshot.site=sites.toSiteSnapshot(resolved)}return},onResponse:async(req,response)=>{const securityResponse=applyViewSecurityHeaders(req,response,embeddableRules);const secured=applyResponseHeaders(req,securityResponse??response,config.server?.headers)??securityResponse;const method=req.method.toUpperCase();if(method!=="GET"&&method!=="HEAD"){finishRequestCapture(req,secured??response);return secured}const baseline=secured??response;let current=baseline;if(current.status===404&&config.sites?.enabled){try{const{cmsNotFoundFallback}=await import("@stacksjs/cms");const cmsResponse=await cmsNotFoundFallback(req);if(cmsResponse)current=cmsResponse}catch(error){log.debug(`CMS fallback skipped: ${error.message}`)}}let finished;try{const{seedCsrfCookieIfMissing}=await import(resolveCsrfMiddlewarePath());finished=await seedCsrfCookieIfMissing(req,current)??(current===baseline?secured:current)}catch(error){log.debug(`CSRF cookie seeding skipped: ${error.message}`);finished=current===baseline?secured:current}if(!documentCacheControl){finishRequestCapture(req,finished??response);return finished}const cached=applyDocumentCacheControl(req,finished??response,documentCacheControl);finishRequestCapture(req,cached??finished??response);return cached}});log.success(`Production server listening on http://0.0.0.0:${port}`)}export function buildDocumentCacheControl(documents){if(!documents)return;const maxAge=Number(documents.maxAge??0);if(!Number.isFinite(maxAge)||maxAge<=0)return;const stale=Number(documents.staleWhileRevalidate??0);const parts=[`public`,`max-age=${Math.floor(maxAge)}`];if(Number.isFinite(stale)&&stale>0)parts.push(`stale-while-revalidate=${Math.floor(stale)}`);return parts.join(", ")}export function isAuthenticatedRequest(request){if(request.headers.get("authorization"))return true;const cookie=request.headers.get("cookie")||"";if(!cookie)return false;return cookie.split(";").map((part)=>part.trim().split("=")[0]?.toLowerCase()??"").some((name)=>name!==""&&!name.includes("csrf")&&/session|auth|token|remember/.test(name))}const SPA_NAV_REQUEST_HEADER="X-STX-Router";const SPA_NAV_FRAGMENT_HEADER="X-STX-Fragment";export function isSpaFragmentExchange(request,response){return request.headers.get(SPA_NAV_REQUEST_HEADER)==="true"||response.headers.get(SPA_NAV_FRAGMENT_HEADER)==="true"}export function applyDocumentCacheControl(request,response,cacheControl){if(!cacheControl)return response;const contentType=response.headers.get("content-type")||"";if(response.status!==200||!contentType.startsWith("text/html"))return response;if(isSpaFragmentExchange(request,response))return response;if(response.headers.getSetCookie().length>0)return response;if(isAuthenticatedRequest(request))return response;const headers=new Headers(response.headers);headers.set("cache-control",cacheControl);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}async function resolveVendoredStxModule(){const source=resolveStxSource({value:process.env.STACKS_STX_SRC});if(source.kind==="missing"){await log.exit(`STACKS_STX_SRC points at ${source.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`,ExitCode.FatalError)}if(source.kind==="override"){log.warn(`Rendering through ${source.path} instead of the installed @stacksjs/stx.`);return await import(source.path)}try{return await import("@stacksjs/stx")}catch{}return}function fallbackI18nFromSite(site){const locales=site.i18n.locales;const defaultLocale=site.i18n.defaultLocale??locales[0];return{locales,defaultLocale,labels:site.i18n.labels??Object.fromEntries(locales.map((c)=>[c,c.toUpperCase()])),translations:{},pickerSelector:site.i18n.pickerSelector??"#lang-picker"}}async function resolveSiteI18n(site){try{const resolved=await resolveVendoredStxModule();if(typeof resolved?.resolveI18n==="function"){const i18n=resolved.resolveI18n(site,process.cwd());if(i18n)return i18n}}catch{}return fallbackI18nFromSite(site)}async function loadStxSiteConfig(){const sitePath=siteConfigPath();if(!existsSync(sitePath))return{};try{const mod=await import(sitePath);const site=mod.default??mod.site??mod.config;if(!site)return{};if(!site.i18n)return{site};const i18n=await resolveSiteI18n(site);return{site,i18n}}catch{}return{}}
|
package/dist/project-setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const APP_KEY_OPTIONAL_COMMANDS=["env","desktop:apple","build","link:core","unlink:core","lint","docs","release","lint:fix","test","test:types","test:unit","test:feature","typecheck","types:fix","types:generate","clean","fresh","about","ai:context","doctor","list","setup","setup:ssl","setup:oh-my-zsh","deploy","serve","new","create","upgrade","update","migrate","seed","generate","make","key:generate","scaffold:crud"];export function shouldSkipAppKeyCheck(requestedCommand,mode={}){return Boolean(mode.isHelpFlag||mode.isHelpMode||APP_KEY_OPTIONAL_COMMANDS.some((command)=>requestedCommand===command||requestedCommand.startsWith(`${command}:`)))}
|
|
1
|
+
import{FEATURE_NAMES}from"@stacksjs/features";const APP_KEY_OPTIONAL_COMMANDS=["env","desktop:apple","build","link:core","unlink:core","lint","docs","release","lint:fix","test","test:types","test:unit","test:feature","typecheck","types:fix","types:generate","clean","fresh","about","ai:context","doctor","list","setup","setup:ssl","setup:oh-my-zsh","deploy","serve","new","create","upgrade","update","migrate","seed","generate","make","key:generate","scaffold:crud"];export function shouldSkipAppKeyCheck(requestedCommand,mode={}){return Boolean(mode.isHelpFlag||mode.isHelpMode||FEATURE_NAMES.some((feature)=>requestedCommand===`${feature}:install`||requestedCommand===`${feature}:uninstall`)||APP_KEY_OPTIONAL_COMMANDS.some((command)=>requestedCommand===command||requestedCommand.startsWith(`${command}:`)))}
|