@stacksjs/actions 0.75.515 → 0.75.519

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.
Files changed (151) hide show
  1. package/dist/action.js +1 -1
  2. package/dist/auth/client-options.js +1 -1
  3. package/dist/auth/client.js +1 -1
  4. package/dist/auth/prune.js +1 -1
  5. package/dist/auth/setup.js +2 -2
  6. package/dist/blog-admin.js +3 -3
  7. package/dist/blog.js +23 -23
  8. package/dist/build/android-config.js +1 -1
  9. package/dist/build/android-icons.js +1 -1
  10. package/dist/build/android.js +1 -1
  11. package/dist/build/component-library.js +1 -1
  12. package/dist/build/core.js +1 -1
  13. package/dist/build/craft-entry.js +1 -1
  14. package/dist/build/craft-provenance.js +1 -1
  15. package/dist/build/desktop-macos.js +2 -2
  16. package/dist/build/desktop.js +2 -2
  17. package/dist/build/dmg-macos.js +1 -1
  18. package/dist/build/dmg.js +1 -1
  19. package/dist/build/docs.js +1 -1
  20. package/dist/build/frontend-static.js +5 -5
  21. package/dist/build/ios-config.js +3 -3
  22. package/dist/build/ios-shell.js +3 -3
  23. package/dist/build/ios-toolchain.js +2 -2
  24. package/dist/build/ios.js +2 -2
  25. package/dist/build/macos-native.js +3 -3
  26. package/dist/build/mobile-splash.js +1 -1
  27. package/dist/build/mobile-target.js +1 -1
  28. package/dist/build/native-screens.js +1 -1
  29. package/dist/build/native-sensors.js +1 -1
  30. package/dist/build/notarize.js +2 -2
  31. package/dist/build/run-build-step.js +1 -1
  32. package/dist/build/stacks.js +1 -1
  33. package/dist/build/views.js +1 -1
  34. package/dist/build.js +1 -1
  35. package/dist/bump.js +7 -7
  36. package/dist/calendar-version.js +1 -1
  37. package/dist/changelog.js +1 -1
  38. package/dist/check/ports.js +1 -1
  39. package/dist/commit.js +1 -1
  40. package/dist/database/seed.js +1 -1
  41. package/dist/deploy/create-receipt-rule.js +1 -1
  42. package/dist/deploy/hooks.js +1 -1
  43. package/dist/deploy/index.js +17 -17
  44. package/dist/deploy/stack.js +6 -6
  45. package/dist/dev/api.js +1 -1
  46. package/dist/dev/components.js +1 -1
  47. package/dist/dev/csrf.js +1 -1
  48. package/dist/dev/dashboard-native.js +1 -1
  49. package/dist/dev/dashboard-request-routing.js +1 -1
  50. package/dist/dev/dashboard-supervisor.js +2 -2
  51. package/dist/dev/dashboard-utils.js +1 -1
  52. package/dist/dev/dashboard.js +4 -4
  53. package/dist/dev/defaults-resources.js +1 -1
  54. package/dist/dev/docs.js +1 -1
  55. package/dist/dev/exit-with-parent.js +1 -1
  56. package/dist/dev/migrate-watcher.js +1 -1
  57. package/dist/dev/system-tray.js +2 -2
  58. package/dist/dev/tray-origin.js +1 -1
  59. package/dist/dev/views.js +1 -1
  60. package/dist/discover-packages.js +1 -1
  61. package/dist/domains/add.js +1 -1
  62. package/dist/domains/purchase.js +1 -1
  63. package/dist/domains/remove.js +1 -1
  64. package/dist/examples.js +1 -1
  65. package/dist/find-projects.js +1 -1
  66. package/dist/generate/action-types.js +3 -3
  67. package/dist/generate/erd.js +2 -2
  68. package/dist/generate/ide-helpers.js +1 -1
  69. package/dist/generate/images.js +1 -1
  70. package/dist/generate/index.js +1 -1
  71. package/dist/generate/lib-entries.js +1 -1
  72. package/dist/generate/vschema.js +2 -2
  73. package/dist/github-release.js +5 -5
  74. package/dist/helpers/api-host.js +3 -3
  75. package/dist/helpers/api-shutdown.js +1 -1
  76. package/dist/helpers/component-meta.js +3 -3
  77. package/dist/helpers/utils.js +1 -1
  78. package/dist/helpers/vscode-custom-data.js +1 -1
  79. package/dist/key-generate.js +1 -1
  80. package/dist/library/build.js +2 -2
  81. package/dist/library/entries.js +1 -1
  82. package/dist/library/globals.js +1 -1
  83. package/dist/library/manifest.js +2 -2
  84. package/dist/library/packages.js +1 -1
  85. package/dist/library/publish.js +2 -2
  86. package/dist/library-publish.js +1 -1
  87. package/dist/lint/files.js +1 -1
  88. package/dist/lint/lint.js +1 -1
  89. package/dist/lint/stx-gate.js +3 -3
  90. package/dist/make-command.js +2 -2
  91. package/dist/make-job.js +2 -2
  92. package/dist/make-policy.js +2 -2
  93. package/dist/make-resource.js +1 -1
  94. package/dist/make.js +7 -7
  95. package/dist/migrate/database.js +1 -1
  96. package/dist/migrate/fresh.js +1 -1
  97. package/dist/pantry-lock.js +1 -1
  98. package/dist/pantry-toolchain.js +1 -1
  99. package/dist/project-scripts.js +1 -1
  100. package/dist/publication-preflight.js +1 -1
  101. package/dist/queue/clear.js +1 -1
  102. package/dist/queue/dlq-purge.js +1 -1
  103. package/dist/queue/dlq-retry.js +1 -1
  104. package/dist/queue/dlq.js +2 -2
  105. package/dist/queue/failed.js +2 -2
  106. package/dist/queue/flush.js +1 -1
  107. package/dist/queue/inspect.js +6 -6
  108. package/dist/queue/list.js +2 -2
  109. package/dist/queue/monitor.js +5 -5
  110. package/dist/queue/options.js +1 -1
  111. package/dist/queue/pause.js +1 -1
  112. package/dist/queue/quarantine.js +1 -1
  113. package/dist/queue/resume.js +1 -1
  114. package/dist/queue/retry.js +1 -1
  115. package/dist/queue/schedule-list.js +2 -2
  116. package/dist/queue/status.js +2 -2
  117. package/dist/queue/unquarantine.js +1 -1
  118. package/dist/queue/work.js +1 -1
  119. package/dist/release-evidence.js +1 -1
  120. package/dist/release-notes.js +5 -5
  121. package/dist/release-preflight.js +2 -2
  122. package/dist/release-push-target.js +3 -3
  123. package/dist/release.js +1 -1
  124. package/dist/reviewos-evidence.js +1 -1
  125. package/dist/route/list.js +1 -1
  126. package/dist/saas/setup.js +1 -1
  127. package/dist/scaffold-crud.js +7 -7
  128. package/dist/search/flush.js +1 -1
  129. package/dist/search/import.js +1 -1
  130. package/dist/search/settings-list.js +1 -1
  131. package/dist/seo.js +4 -4
  132. package/dist/serve/api.js +1 -1
  133. package/dist/serve/dashboard-gate.js +1 -1
  134. package/dist/serve/dashboard.js +1 -1
  135. package/dist/setup/ssl.js +2 -2
  136. package/dist/stacks.js +1 -1
  137. package/dist/stx-source.js +1 -1
  138. package/dist/test/feature.js +1 -1
  139. package/dist/test/runner.js +1 -1
  140. package/dist/test/unit.js +1 -1
  141. package/dist/upgrade/binary.js +1 -1
  142. package/dist/upgrade/framework-hooks.d.ts +6 -0
  143. package/dist/upgrade/framework-hooks.js +1 -1
  144. package/dist/upgrade/framework-utils.js +2 -2
  145. package/dist/upgrade/framework.js +10 -10
  146. package/dist/upgrade/package-project.js +2 -2
  147. package/dist/upgrade/packages.js +23 -22
  148. package/dist/upgrade/route-actions.js +3 -3
  149. package/dist/upgrade/shell.js +4 -4
  150. package/dist/upgrade.js +1 -1
  151. package/package.json +40 -40
@@ -1 +1 @@
1
- import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{pauseQueue}from"@stacksjs/queue";const options=queueActionOptions(),queue=options.queue;if(!queue){await log.error("Usage: buddy queue:pause --queue=<name> [--for=300]");process.exit(1)}const pauseSeconds=options.for?Number.parseInt(options.for,10):300;try{await pauseQueue(queue,pauseSeconds);log.success(`Paused queue '${queue}' for ${pauseSeconds}s`);await log.flush();process.exit(0)}catch(error){await log.error("Failed to pause queue",error);process.exit(1)}
1
+ import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{pauseQueue}from"@stacksjs/queue";const options=queueActionOptions();const queue=options.queue;if(!queue){await log.error("Usage: buddy queue:pause --queue=<name> [--for=300]");process.exit(1)}const pauseSeconds=options.for?Number.parseInt(options.for,10):300;try{await pauseQueue(queue,pauseSeconds);log.success(`Paused queue '${queue}' for ${pauseSeconds}s`);await log.flush();process.exit(0)}catch(error){await log.error("Failed to pause queue",error);process.exit(1)}
@@ -1,2 +1,2 @@
1
- import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{listQuarantined,quarantineJob}from"@stacksjs/queue";const options=queueActionOptions();try{if(options.add){const jobName=options.add;await quarantineJob(jobName);log.success(`Quarantined ${jobName}`);await log.flush();process.exit(0)}const rows=await listQuarantined();if(rows.length===0){console.log("\u2713 No jobs currently quarantined");process.exit(0)}console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510");console.log("\u2502 ID \u2502 Job Name \u2502 Payload Hash \u2502 Failures \u2502 Quarantined At \u2502");console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");for(const row of rows){const id=String(row.id).padEnd(3),jn=(row.job_name||"?").substring(0,32).padEnd(32),ph=(row.payload_hash||"?").substring(0,16).padEnd(16),fc=String(row.failure_count??0).padEnd(8),qa=(row.quarantined_at||"N/A").substring(0,24).padEnd(24);console.log(`\u2502 ${id} \u2502 ${jn} \u2502 ${ph} \u2502 ${fc} \u2502 ${qa} \u2502`)}console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518");console.log(`
1
+ import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{listQuarantined,quarantineJob}from"@stacksjs/queue";const options=queueActionOptions();try{if(options.add){const jobName=options.add;await quarantineJob(jobName);log.success(`Quarantined ${jobName}`);await log.flush();process.exit(0)}const rows=await listQuarantined();if(rows.length===0){console.log("✓ No jobs currently quarantined");process.exit(0)}console.log("┌─────┬──────────────────────────────────┬──────────────────┬──────────┬──────────────────────────┐");console.log("│ ID │ Job Name │ Payload Hash │ Failures │ Quarantined At │");console.log("├─────┼──────────────────────────────────┼──────────────────┼──────────┼──────────────────────────┤");for(const row of rows){const id=String(row.id).padEnd(3);const jn=(row.job_name||"?").substring(0,32).padEnd(32);const ph=(row.payload_hash||"?").substring(0,16).padEnd(16);const fc=String(row.failure_count??0).padEnd(8);const qa=(row.quarantined_at||"N/A").substring(0,24).padEnd(24);console.log(`│ ${id} │ ${jn} │ ${ph} │ ${fc} │ ${qa} │`)}console.log("└─────┴──────────────────────────────────┴──────────────────┴──────────┴──────────────────────────┘");console.log(`
2
2
  ${rows.length} quarantined entrie(s). Use \`queue:unquarantine <JobName>\` to lift.`);process.exit(0)}catch(error){await log.error("Failed to handle queue:quarantine",error);process.exit(1)}
@@ -1 +1 @@
1
- import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{resumeQueue}from"@stacksjs/queue";const options=queueActionOptions(),queue=options.queue;if(!queue){await log.error("Usage: buddy queue:resume --queue=<name>");process.exit(1)}try{await resumeQueue(queue);log.success(`Resumed queue '${queue}'`);await log.flush();process.exit(0)}catch(error){await log.error("Failed to resume queue",error);process.exit(1)}
1
+ import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{resumeQueue}from"@stacksjs/queue";const options=queueActionOptions();const queue=options.queue;if(!queue){await log.error("Usage: buddy queue:resume --queue=<name>");process.exit(1)}try{await resumeQueue(queue);log.success(`Resumed queue '${queue}'`);await log.flush();process.exit(0)}catch(error){await log.error("Failed to resume queue",error);process.exit(1)}
@@ -1 +1 @@
1
- import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{executeFailedJobs,retryFailedJob}from"@stacksjs/queue";const options=queueActionOptions(),jobId=options.id,all=options.all==="true";try{if(all){log.info("Retrying all failed jobs...");await executeFailedJobs();log.success("All failed jobs have been queued for retry")}else if(jobId){const id=Number.parseInt(jobId,10);if(Number.isNaN(id)){await log.error("Invalid job ID provided");process.exit(1)}log.info(`Retrying failed job ${id}...`);await retryFailedJob(id);log.success(`Failed job ${id} has been queued for retry`)}else{log.warn("Please provide a job ID or use --all to retry all failed jobs");log.info("Usage: buddy queue:retry <id> or buddy queue:retry --all");await log.flush();process.exit(1)}process.exit(0)}catch(error){await log.error("Failed to retry job(s)",error);process.exit(1)}
1
+ import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{executeFailedJobs,retryFailedJob}from"@stacksjs/queue";const options=queueActionOptions();const jobId=options.id;const all=options.all==="true";try{if(all){log.info("Retrying all failed jobs...");await executeFailedJobs();log.success("All failed jobs have been queued for retry")}else if(jobId){const id=Number.parseInt(jobId,10);if(Number.isNaN(id)){await log.error("Invalid job ID provided");process.exit(1)}log.info(`Retrying failed job ${id}...`);await retryFailedJob(id);log.success(`Failed job ${id} has been queued for retry`)}else{log.warn("Please provide a job ID or use --all to retry all failed jobs");log.info("Usage: buddy queue:retry <id> or buddy queue:retry --all");await log.flush();process.exit(1)}process.exit(0)}catch(error){await log.error("Failed to retry job(s)",error);process.exit(1)}
@@ -1,4 +1,4 @@
1
1
  import process from"node:process";import{log}from"@stacksjs/logging";import{discoverJobs,getScheduledJobs}from"@stacksjs/queue";try{log.info(`Discovering scheduled jobs...
2
- `);await discoverJobs();const scheduledJobs=getScheduledJobs();if(scheduledJobs.length===0){log.info("No scheduled jobs found.");log.info('Tip: Add a "rate" or "schedule" property to your job configuration.');await log.flush();process.exit(0)}console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510");console.log("\u2502 Job Name \u2502 Schedule \u2502 Queue \u2502 Tries \u2502");console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");for(const job of scheduledJobs){const name=job.name.substring(0,48).padEnd(48),schedule=(job.config.rate||job.config.schedule||"N/A").substring(0,21).padEnd(21),queue=(job.config.queue||"default").substring(0,9).padEnd(9),tries=String(job.config.tries||3).padStart(7);console.log(`\u2502 ${name} \u2502 ${schedule} \u2502 ${queue} \u2502${tries} \u2502`)}console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518");console.log(`
2
+ `);await discoverJobs();const scheduledJobs=getScheduledJobs();if(scheduledJobs.length===0){log.info("No scheduled jobs found.");log.info('Tip: Add a "rate" or "schedule" property to your job configuration.');await log.flush();process.exit(0)}console.log("┌──────────────────────────────────────────────────┬───────────────────────┬───────────┬─────────┐");console.log("│ Job Name │ Schedule │ Queue │ Tries │");console.log("├──────────────────────────────────────────────────┼───────────────────────┼───────────┼─────────┤");for(const job of scheduledJobs){const name=job.name.substring(0,48).padEnd(48);const schedule=(job.config.rate||job.config.schedule||"N/A").substring(0,21).padEnd(21);const queue=(job.config.queue||"default").substring(0,9).padEnd(9);const tries=String(job.config.tries||3).padStart(7);console.log(`│ ${name} │ ${schedule} │ ${queue} │${tries} │`)}console.log("└──────────────────────────────────────────────────┴───────────────────────┴───────────┴─────────┘");console.log(`
3
3
  Total: ${scheduledJobs.length} scheduled job(s)`);console.log(`
4
- Schedule Formats:`);console.log(' \u2022 Cron: "* * * * *" (minute hour day month dayOfWeek)');console.log(" \u2022 Presets: @hourly, @daily, @weekly, @monthly");console.log(" \u2022 Every: Every.Minute, Every.Hour, Every.Day");process.exit(0)}catch(error){await log.error("Failed to list scheduled jobs:",error);process.exit(1)}
4
+ Schedule Formats:`);console.log(' • Cron: "* * * * *" (minute hour day month dayOfWeek)');console.log(" • Presets: @hourly, @daily, @weekly, @monthly");console.log(" • Every: Every.Minute, Every.Hour, Every.Day");process.exit(0)}catch(error){await log.error("Failed to list scheduled jobs:",error);process.exit(1)}
@@ -1,4 +1,4 @@
1
- import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{db}from"@stacksjs/database";const options=queueActionOptions(),queueName=options.queue;try{log.info(`Fetching queue status...
2
- `);const allJobs=queueName?await db.selectFrom("jobs").selectAll().where("queue","=",queueName).execute():await db.selectFrom("jobs").selectAll().execute(),failedJobs=queueName?await db.selectFrom("failed_jobs").selectAll().where("queue","=",queueName).execute():await db.selectFrom("failed_jobs").selectAll().execute(),queueStats=new Map;for(const job of allJobs){const queue=job.queue||"default";if(!queueStats.has(queue))queueStats.set(queue,{pending:0,processing:0,delayed:0});const stats=queueStats.get(queue),now=Math.floor(Date.now()/1000);if(job.reserved_at)stats.processing++;else if(job.available_at&&Number(job.available_at)>now)stats.delayed++;else stats.pending++}const failedStats=new Map;for(const job of failedJobs){const queue=job.queue||"default";failedStats.set(queue,(failedStats.get(queue)||0)+1)}console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510");console.log("\u2502 Queue \u2502 Pending \u2502 Processing \u2502 Delayed \u2502 Failed \u2502");console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");const allQueues=new Set([...queueStats.keys(),...failedStats.keys()]);if(allQueues.size===0)console.log("\u2502 No queues found \u2502");else for(const queue of allQueues){const stats=queueStats.get(queue)||{pending:0,processing:0,delayed:0},failed=failedStats.get(queue)||0,queueDisplay=queue.substring(0,48).padEnd(48),pendingDisplay=String(stats.pending).padStart(8),processingDisplay=String(stats.processing).padStart(10),delayedDisplay=String(stats.delayed).padStart(8),failedDisplay=String(failed).padStart(6);console.log(`\u2502 ${queueDisplay} \u2502${pendingDisplay} \u2502${processingDisplay} \u2502${delayedDisplay} \u2502${failedDisplay} \u2502`)}console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518");const totalPending=Array.from(queueStats.values()).reduce((sum,s)=>sum+s.pending,0),totalProcessing=Array.from(queueStats.values()).reduce((sum,s)=>sum+s.processing,0),totalDelayed=Array.from(queueStats.values()).reduce((sum,s)=>sum+s.delayed,0),totalFailed=Array.from(failedStats.values()).reduce((sum,n)=>sum+n,0);console.log(`
1
+ import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{db}from"@stacksjs/database";const options=queueActionOptions();const queueName=options.queue;try{log.info(`Fetching queue status...
2
+ `);const allJobs=queueName?await db.selectFrom("jobs").selectAll().where("queue","=",queueName).execute():await db.selectFrom("jobs").selectAll().execute();const failedJobs=queueName?await db.selectFrom("failed_jobs").selectAll().where("queue","=",queueName).execute():await db.selectFrom("failed_jobs").selectAll().execute();const queueStats=new Map;for(const job of allJobs){const queue=job.queue||"default";if(!queueStats.has(queue)){queueStats.set(queue,{pending:0,processing:0,delayed:0})}const stats=queueStats.get(queue);const now=Math.floor(Date.now()/1000);if(job.reserved_at){stats.processing++}else if(job.available_at&&Number(job.available_at)>now){stats.delayed++}else{stats.pending++}}const failedStats=new Map;for(const job of failedJobs){const queue=job.queue||"default";failedStats.set(queue,(failedStats.get(queue)||0)+1)}console.log("┌──────────────────────────────────────────────────┬──────────┬────────────┬──────────┬────────┐");console.log("│ Queue │ Pending │ Processing │ Delayed │ Failed │");console.log("├──────────────────────────────────────────────────┼──────────┼────────────┼──────────┼────────┤");const allQueues=new Set([...queueStats.keys(),...failedStats.keys()]);if(allQueues.size===0){console.log("│ No queues found │")}else{for(const queue of allQueues){const stats=queueStats.get(queue)||{pending:0,processing:0,delayed:0};const failed=failedStats.get(queue)||0;const queueDisplay=queue.substring(0,48).padEnd(48);const pendingDisplay=String(stats.pending).padStart(8);const processingDisplay=String(stats.processing).padStart(10);const delayedDisplay=String(stats.delayed).padStart(8);const failedDisplay=String(failed).padStart(6);console.log(`│ ${queueDisplay} │${pendingDisplay} │${processingDisplay} │${delayedDisplay} │${failedDisplay} │`)}}console.log("└──────────────────────────────────────────────────┴──────────┴────────────┴──────────┴────────┘");const totalPending=Array.from(queueStats.values()).reduce((sum,s)=>sum+s.pending,0);const totalProcessing=Array.from(queueStats.values()).reduce((sum,s)=>sum+s.processing,0);const totalDelayed=Array.from(queueStats.values()).reduce((sum,s)=>sum+s.delayed,0);const totalFailed=Array.from(failedStats.values()).reduce((sum,n)=>sum+n,0);console.log(`
3
3
  Summary:`);console.log(` Pending: ${totalPending}`);console.log(` Processing: ${totalProcessing}`);console.log(` Delayed: ${totalDelayed}`);console.log(` Failed: ${totalFailed}`);console.log(` Total: ${totalPending+totalProcessing+totalDelayed+totalFailed}`);process.exit(0)}catch(error){const message=error instanceof Error?error.message:String(error);if(/no such table:\s*(?:jobs|failed_jobs)\b/i.test(message)){process.stdout.write(`Queue tables are not set up yet.
4
4
  `);process.stdout.write("Run `buddy queue:table` to create the migrations, then `buddy migrate` to apply them.\n");process.exit(0)}await log.error("Failed to get queue status",error);process.exit(1)}
@@ -1 +1 @@
1
- import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{unquarantineJob}from"@stacksjs/queue";const options=queueActionOptions(),jobName=options.name;if(!jobName){await log.error("Usage: buddy queue:unquarantine --name=<JobName>");process.exit(1)}try{await unquarantineJob(jobName);log.success(`Lifted quarantine for ${jobName}`);await log.flush();process.exit(0)}catch(error){await log.error("Failed to unquarantine",error);process.exit(1)}
1
+ import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{unquarantineJob}from"@stacksjs/queue";const options=queueActionOptions();const jobName=options.name;if(!jobName){await log.error("Usage: buddy queue:unquarantine --name=<JobName>");process.exit(1)}try{await unquarantineJob(jobName);log.success(`Lifted quarantine for ${jobName}`);await log.flush();process.exit(0)}catch(error){await log.error("Failed to unquarantine",error);process.exit(1)}
@@ -1 +1 @@
1
- import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{startProcessor,stopProcessor}from"@stacksjs/queue";import{injectGlobalAutoImports}from"@stacksjs/server";process.on("unhandledRejection",(reason)=>{log.error(`Unhandled Rejection in queue worker: ${reason}`)});process.on("uncaughtException",(error)=>{log.error(`Uncaught Exception in queue worker: ${error.message}`)});const SHUTDOWN_GRACE_MS=Number(process.env.STACKS_QUEUE_SHUTDOWN_GRACE_MS)||1e4;let shuttingDown=!1;async function gracefulShutdown(signal){if(shuttingDown)return;shuttingDown=!0;log.info(`[queue] Worker received ${signal}, draining in-flight jobs (max ${SHUTDOWN_GRACE_MS/1000}s)\u2026`);setTimeout(()=>{console.error("[queue] Drain window exceeded - forcing worker exit.");process.exit(1)},SHUTDOWN_GRACE_MS+2000).unref();try{await stopProcessor({graceMs:SHUTDOWN_GRACE_MS})}catch(error){await log.error("[queue] Error while draining worker on shutdown:",error)}process.exit(0)}process.on("SIGTERM",()=>{gracefulShutdown("SIGTERM")});process.on("SIGINT",()=>{gracefulShutdown("SIGINT")});const options=queueActionOptions(),queue=options.queue,concurrency=Number(options.concurrency)||1;await injectGlobalAutoImports();log.info(`Starting queue worker with ${concurrency} concurrent worker(s)...`);const result=await startProcessor(queue,{concurrency});if(result.isErr){await log.error("Failed to start queue worker:",result.error);process.exit(1)}log.success("Queue worker started successfully!");await new Promise(()=>{});
1
+ import{queueActionOptions}from"./options";import process from"node:process";import{log}from"@stacksjs/logging";import{startProcessor,stopProcessor}from"@stacksjs/queue";import{injectGlobalAutoImports}from"@stacksjs/server";process.on("unhandledRejection",(reason)=>{log.error(`Unhandled Rejection in queue worker: ${reason}`)});process.on("uncaughtException",(error)=>{log.error(`Uncaught Exception in queue worker: ${error.message}`)});const SHUTDOWN_GRACE_MS=Number(process.env.STACKS_QUEUE_SHUTDOWN_GRACE_MS)||1e4;let shuttingDown=false;async function gracefulShutdown(signal){if(shuttingDown)return;shuttingDown=true;log.info(`[queue] Worker received ${signal}, draining in-flight jobs (max ${SHUTDOWN_GRACE_MS/1000}s)…`);setTimeout(()=>{console.error("[queue] Drain window exceeded - forcing worker exit.");process.exit(1)},SHUTDOWN_GRACE_MS+2000).unref();try{await stopProcessor({graceMs:SHUTDOWN_GRACE_MS})}catch(error){await log.error("[queue] Error while draining worker on shutdown:",error)}process.exit(0)}process.on("SIGTERM",()=>{gracefulShutdown("SIGTERM")});process.on("SIGINT",()=>{gracefulShutdown("SIGINT")});const options=queueActionOptions();const queue=options.queue;const concurrency=Number(options.concurrency)||1;await injectGlobalAutoImports();log.info(`Starting queue worker with ${concurrency} concurrent worker(s)...`);const result=await startProcessor(queue,{concurrency});if(result.isErr){await log.error("Failed to start queue worker:",result.error);process.exit(1)}log.success("Queue worker started successfully!");await new Promise(()=>{});
@@ -1 +1 @@
1
- import{createHash}from"node:crypto";import{lstatSync,readFileSync,readdirSync,realpathSync}from"node:fs";import{join,relative,resolve}from"node:path";import{runProjectScripts}from"./project-scripts";function fail(message){throw Error(`Release verification blocked: ${message}`)}function hash(bytes){return createHash("sha256").update(bytes).digest("hex")}function nonemptyStrings(value){return Array.isArray(value)&&value.length>0&&value.every((item)=>typeof item==="string"&&item.length>0)}export function validateReleaseEvidencePlan(value){const plan=value;if(!plan||plan.schemaVersion!==1||!Array.isArray(plan.sources)||!plan.sources.length||!nonemptyStrings(plan.checks)||plan.checks.some((name)=>!/^[a-z0-9][\w:.-]*$/i.test(name))||new Set(plan.checks).size!==plan.checks.length)fail("Expected a version 1 plan with sources and named consumer checks");const packages=new Set;for(const source of plan.sources){if(!source||!/^[\w.-]+\/[\w.-]+$/.test(source.repository)||!/^[a-f0-9]{40}$/.test(source.commit)||typeof source.tag!=="string"||!source.tag||!Array.isArray(source.gates)||!source.gates.length||!Array.isArray(source.packages)||!source.packages.length)fail("Each source needs a repository, full commit, tag, release gates and packages");for(const gate of source.gates)if(!gate||!Number.isSafeInteger(gate.runId)||gate.runId<=0||!/^\.github\/workflows\/[\w.-]+\.ya?ml$/.test(gate.workflow)||!nonemptyStrings(gate.requiredJobs)||new Set(gate.requiredJobs).size!==gate.requiredJobs.length)fail("Each release gate needs an exact run, workflow and required jobs");for(const pkg of source.packages){if(!pkg||!/^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/.test(pkg.name)||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(pkg.version)||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(pkg.integrity)||packages.has(pkg.name))fail("Packages need unique names, exact versions and original SHA-512 archive identities");packages.add(pkg.name)}}}async function boundedBody(response,limit){const declared=response.headers.get("content-length");if(declared&&Number(declared)>limit){await response.body?.cancel();fail("Response exceeds its byte budget")}if(!response.body)fail("Response has no body");const reader=response.body.getReader(),chunks=[];let length=0;try{while(!0){const next=await reader.read();if(next.done)break;length+=next.value.byteLength;if(length>limit)fail("Response exceeds its byte budget");chunks.push(next.value)}return Buffer.concat(chunks,length)}finally{await reader.cancel().catch(()=>{});reader.releaseLock()}}function validateTarBounds(tar){if(!tar.byteLength||tar.byteLength%512)fail("Published archive has invalid tar block bounds");let offset=0,files=0,headers=0;const text=(start,length)=>new TextDecoder().decode(tar.subarray(start,start+length)).replace(/\0.*$/s,"").trim();while(offset+512<=tar.byteLength){const header=tar.subarray(offset,offset+512);if(header.every((byte)=>byte===0)){if(tar.subarray(offset).some((byte)=>byte!==0))fail("Published archive has data after its tar terminator");return files}if(++headers>1e5)fail("Published archive has too many entries");const rawSize=text(offset+124,12);if(!/^[0-7]+$/.test(rawSize))fail("Published archive has an unsupported tar size");const size=Number.parseInt(rawSize,8),end=offset+512+Math.ceil(size/512)*512;if(!Number.isSafeInteger(end)||end>tar.byteLength)fail("Published archive declares bytes outside its tar bounds");const type=header[156]===0?"0":String.fromCharCode(header[156]);if(type==="0")files++;else if(type==="x"||type==="g"){const metadata=tar.subarray(offset+512,offset+512+size),allowed=new Set(["path","mtime","atime","ctime","uid","gid","uname","gname","comment","charset","hdrcharset"]);for(let start=0;start<metadata.length;){const space=metadata.indexOf(32,start);if(space<0)fail("Published archive has malformed PAX records");const rawLength=new TextDecoder().decode(metadata.subarray(start,space)),length=Number(rawLength),end=start+length;if(!/^\d+$/.test(rawLength)||!Number.isSafeInteger(end)||end>metadata.length||end<=space+2||metadata[end-1]!==10)fail("Published archive has malformed PAX bounds");const equals=metadata.indexOf(61,space+1),key=new TextDecoder().decode(metadata.subarray(space+1,equals));if(equals<0||equals>=end-1||!allowed.has(key))fail("Published archive has unsupported PAX allocation or link metadata");start=end}}else if(type!=="5"&&type!=="L")fail("Published archive contains a link or unsupported tar entry");offset=end}fail("Published archive has no tar terminator")}async function archiveFiles(bytes,limit){const stream=new Blob([new Uint8Array(bytes)]).stream().pipeThrough(new DecompressionStream("gzip")),tar=await boundedBody(new Response(stream),limit),count=validateTarBounds(tar),files=await new Bun.Archive(tar).files();if(!count||files.size!==count)fail("Published archive has missing or duplicate file paths");const result=new Map;for(const[name,file]of files){const path=name.slice(8);if(!name.startsWith("package/")||!path||path.includes("\\")||path.includes(":")||path.split("/").some((part)=>!part||part==="."||part==="..")||result.has(path))fail("Published archive contains an unsafe or duplicate package path");result.set(path,{sha256:hash(new Uint8Array(await file.arrayBuffer())),bytes:file.size})}if(!result.has("package.json"))fail("Published archive has no package manifest");return result}function verifyInstalledFiles(directory,expected){const found=new Set,hasBundledDependencies=[...expected.keys()].some((path)=>path.startsWith("node_modules/"));function visit(path,depth){if(depth>128)fail("Installed package directory depth exceeds its budget");for(const entry of readdirSync(join(directory,path),{withFileTypes:!0})){if(!path&&entry.name==="node_modules"&&!hasBundledDependencies)continue;const name=path?`${path}/${entry.name}`:entry.name;if(found.size>=1e5)fail("Installed package has too many files");const fullPath=join(directory,name);if(entry.isDirectory())visit(name,depth+1);else{const identity=expected.get(name),stat=lstatSync(fullPath);if(!identity||!stat.isFile()||stat.size!==identity.bytes||hash(readFileSync(fullPath))!==identity.sha256)fail(`Installed package file ${name} differs from the verified archive`);found.add(name)}}}visit("",0);if(found.size!==expected.size)fail("Installed package is missing files from the verified archive")}function installedState(plan,cwd,archives){const lock=readFileSync(join(cwd,"bun.lock"),"utf8"),parsed=Bun.JSONC.parse(lock),nodeModules=realpathSync(join(cwd,"node_modules")),manifests=[];for(const source of plan.sources)for(const pkg of source.packages){const locked=parsed.packages?.[pkg.name];if(locked?.[0]!==`${pkg.name}@${pkg.version}`||locked.at(-1)!==pkg.integrity)fail(`Consumer lock does not contain ${pkg.name}@${pkg.version} with the original archive identity`);const directory=realpathSync(join(cwd,"node_modules",pkg.name)),path=relative(nodeModules,directory);if(!path||path.startsWith("..")||resolve(nodeModules,path)!==directory)fail(`${pkg.name} resolves outside the installed consumer packages`);const raw=readFileSync(join(directory,"package.json"),"utf8"),manifest=JSON.parse(raw);if(manifest.name!==pkg.name||manifest.version!==pkg.version)fail(`Installed ${pkg.name} does not match tested version ${pkg.version}`);verifyInstalledFiles(directory,archives.get(pkg.name));manifests.push(hash(raw))}return{lock,sha256:hash(lock),manifests:manifests.join(":")}}export async function verifyReleaseEvidence(plan,options){validateReleaseEvidencePlan(plan);const requestTimeoutMs=options.requestTimeoutMs??30000,checkTimeoutMs=options.checkTimeoutMs??300000,maxArchiveBytes=options.maxArchiveBytes??134217728,maxExpandedBytes=options.maxExpandedBytes??134217728;for(const number of[requestTimeoutMs,checkTimeoutMs,maxArchiveBytes,maxExpandedBytes])if(!Number.isSafeInteger(number)||number<=0)fail("Budgets must be positive safe integers");const read=options.fetch??fetch,archives=new Map,receipt={schemaVersion:1,verifiedAt:"",sources:[],consumer:{lockfile:"bun.lock",sha256:"",bunVersion:"",checks:[]}};async function request(url,github,limit=1048576){const timeout=AbortSignal.timeout(requestTimeoutMs),signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;signal.throwIfAborted();const response=await read(url,{method:"GET",redirect:"error",signal,headers:github?{Accept:"application/vnd.github+json",...options.token?{Authorization:`Bearer ${options.token}`}:{}}:{}});if(response.status!==200){await response.body?.cancel();fail(`${github?"Source evidence":"Published package"} request returned HTTP ${response.status}`)}return boundedBody(response,limit)}async function github(path){return JSON.parse(new TextDecoder().decode(await request(`https://api.github.com/repos/${path}`,!0)))}for(const source of plan.sources){let ref=(await github(`${source.repository}/git/ref/tags/${encodeURIComponent(source.tag)}`)).object;for(let depth=0;ref?.type==="tag"&&depth<5;depth++)ref=(await github(`${source.repository}/git/tags/${ref.sha}`)).object;if(ref?.type!=="commit"||ref.sha!==source.commit)fail(`${source.tag} does not identify ${source.commit}`);const manifest=await github(`${source.repository}/contents/package.json?ref=${source.commit}`);if(manifest.encoding!=="base64"||typeof manifest.content!=="string")fail("Source package manifest is unavailable");const releaseScript=JSON.parse(Buffer.from(manifest.content,"base64").toString("utf8")).scripts?.["release:patch"];if(typeof releaseScript!=="string"||!releaseScript.trim())fail(`${source.repository} has no existing release:patch command`);for(const gate of source.gates){const run=await github(`${source.repository}/actions/runs/${gate.runId}`);if(run.id!==gate.runId||run.repository?.full_name!==source.repository||run.path!==gate.workflow||run.head_sha!==source.commit)fail(`Release gate ${gate.runId} does not verify the exact source and workflow`);if(run.status!=="completed"||run.conclusion!=="success")fail(`Release gate ${gate.runId} is not successful`);const jobs=[];for(let page=1;page<=10;page++){const batch=await github(`${source.repository}/actions/runs/${gate.runId}/jobs?per_page=100&page=${page}`);if(!Array.isArray(batch.jobs))fail(`Release gate ${gate.runId} has no readable jobs`);jobs.push(...batch.jobs);if(batch.jobs.length<100)break;if(page===10)fail("Release job inventory exceeds its budget")}for(const name of gate.requiredJobs){const matches=jobs.filter((job)=>job.name===name);if(matches.length!==1||matches[0]?.status!=="completed"||matches[0]?.conclusion!=="success")fail(`Required release job ${name} did not pass exactly once`)}}const verified={...source,releaseCommand:"bun run release:patch",releaseScript,packages:[]};for(const pkg of source.packages){const metadata=JSON.parse(new TextDecoder().decode(await request(`https://registry.npmjs.org/${encodeURIComponent(pkg.name)}/${encodeURIComponent(pkg.version)}`,!1)));if(metadata.name!==pkg.name||metadata.version!==pkg.version||metadata.dist?.integrity!==pkg.integrity)fail(`Published ${pkg.name}@${pkg.version} does not match the original archive identity`);if(metadata.gitHead!==void 0&&metadata.gitHead!==source.commit)fail(`Published ${pkg.name} names a different source commit`);if(!metadata.dist?.tarball)fail(`Published ${pkg.name} has no archive URL`);const tarball=new URL(metadata.dist.tarball);if(tarball.origin!=="https://registry.npmjs.org"||tarball.username||tarball.password)fail("Archive URL is outside the public npm registry");const bytes=await request(tarball.href,!1,maxArchiveBytes);if(`sha512-${createHash("sha512").update(bytes).digest("base64")}`!==pkg.integrity)fail(`Published ${pkg.name}@${pkg.version} archive bytes failed SHA-512 verification`);const files=await archiveFiles(bytes,maxExpandedBytes);archives.set(pkg.name,files);const filesSha256=hash(JSON.stringify([...files].sort(([left],[right])=>left.localeCompare(right))));verified.packages.push({...pkg,tarball:tarball.href,bytes:bytes.byteLength,filesSha256})}receipt.sources.push(verified)}const initial=installedState(plan,options.cwd,archives),checks=await runProjectScripts({cwd:options.cwd,scripts:plan.checks,signal:options.signal,timeoutMs:checkTimeoutMs});receipt.consumer.bunVersion=checks.bunVersion;receipt.consumer.checks=checks.checks;const final=installedState(plan,options.cwd,archives);if(final.sha256!==initial.sha256||final.manifests!==initial.manifests)fail("Consumer checks changed the verified lockfile or package identities");receipt.consumer.sha256=initial.sha256;options.signal?.throwIfAborted();receipt.verifiedAt=new Date().toISOString();return receipt}
1
+ import{createHash}from"node:crypto";import{lstatSync,readFileSync,readdirSync,realpathSync}from"node:fs";import{join,relative,resolve}from"node:path";import{runProjectScripts}from"./project-scripts";function fail(message){throw new Error(`Release verification blocked: ${message}`)}function hash(bytes){return createHash("sha256").update(bytes).digest("hex")}function nonemptyStrings(value){return Array.isArray(value)&&value.length>0&&value.every((item)=>typeof item==="string"&&item.length>0)}export function validateReleaseEvidencePlan(value){const plan=value;if(!plan||plan.schemaVersion!==1||!Array.isArray(plan.sources)||!plan.sources.length||!nonemptyStrings(plan.checks)||plan.checks.some((name)=>!/^[a-z0-9][\w:.-]*$/i.test(name))||new Set(plan.checks).size!==plan.checks.length)fail("Expected a version 1 plan with sources and named consumer checks");const packages=new Set;for(const source of plan.sources){if(!source||!/^[\w.-]+\/[\w.-]+$/.test(source.repository)||!/^[a-f0-9]{40}$/.test(source.commit)||typeof source.tag!=="string"||!source.tag||!Array.isArray(source.gates)||!source.gates.length||!Array.isArray(source.packages)||!source.packages.length)fail("Each source needs a repository, full commit, tag, release gates and packages");for(const gate of source.gates){if(!gate||!Number.isSafeInteger(gate.runId)||gate.runId<=0||!/^\.github\/workflows\/[\w.-]+\.ya?ml$/.test(gate.workflow)||!nonemptyStrings(gate.requiredJobs)||new Set(gate.requiredJobs).size!==gate.requiredJobs.length)fail("Each release gate needs an exact run, workflow and required jobs")}for(const pkg of source.packages){if(!pkg||!/^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/.test(pkg.name)||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(pkg.version)||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(pkg.integrity)||packages.has(pkg.name))fail("Packages need unique names, exact versions and original SHA-512 archive identities");packages.add(pkg.name)}}}async function boundedBody(response,limit){const declared=response.headers.get("content-length");if(declared&&Number(declared)>limit){await response.body?.cancel();fail("Response exceeds its byte budget")}if(!response.body)fail("Response has no body");const reader=response.body.getReader();const chunks=[];let length=0;try{while(true){const next=await reader.read();if(next.done)break;length+=next.value.byteLength;if(length>limit)fail("Response exceeds its byte budget");chunks.push(next.value)}return Buffer.concat(chunks,length)}finally{await reader.cancel().catch(()=>{});reader.releaseLock()}}function validateTarBounds(tar){if(!tar.byteLength||tar.byteLength%512)fail("Published archive has invalid tar block bounds");let offset=0;let files=0;let headers=0;const text=(start,length)=>new TextDecoder().decode(tar.subarray(start,start+length)).replace(/\0.*$/s,"").trim();while(offset+512<=tar.byteLength){const header=tar.subarray(offset,offset+512);if(header.every((byte)=>byte===0)){if(tar.subarray(offset).some((byte)=>byte!==0))fail("Published archive has data after its tar terminator");return files}if(++headers>1e5)fail("Published archive has too many entries");const rawSize=text(offset+124,12);if(!/^[0-7]+$/.test(rawSize))fail("Published archive has an unsupported tar size");const size=Number.parseInt(rawSize,8);const end=offset+512+Math.ceil(size/512)*512;if(!Number.isSafeInteger(end)||end>tar.byteLength)fail("Published archive declares bytes outside its tar bounds");const type=header[156]===0?"0":String.fromCharCode(header[156]);if(type==="0")files++;else if(type==="x"||type==="g"){const metadata=tar.subarray(offset+512,offset+512+size);const allowed=new Set(["path","mtime","atime","ctime","uid","gid","uname","gname","comment","charset","hdrcharset"]);for(let start=0;start<metadata.length;){const space=metadata.indexOf(32,start);if(space<0)fail("Published archive has malformed PAX records");const rawLength=new TextDecoder().decode(metadata.subarray(start,space));const length=Number(rawLength);const end=start+length;if(!/^\d+$/.test(rawLength)||!Number.isSafeInteger(end)||end>metadata.length||end<=space+2||metadata[end-1]!==10)fail("Published archive has malformed PAX bounds");const equals=metadata.indexOf(61,space+1);const key=new TextDecoder().decode(metadata.subarray(space+1,equals));if(equals<0||equals>=end-1||!allowed.has(key))fail("Published archive has unsupported PAX allocation or link metadata");start=end}}else if(type!=="5"&&type!=="L")fail("Published archive contains a link or unsupported tar entry");offset=end}fail("Published archive has no tar terminator")}async function archiveFiles(bytes,limit){const stream=new Blob([new Uint8Array(bytes)]).stream().pipeThrough(new DecompressionStream("gzip"));const tar=await boundedBody(new Response(stream),limit);const count=validateTarBounds(tar);const files=await new Bun.Archive(tar).files();if(!count||files.size!==count)fail("Published archive has missing or duplicate file paths");const result=new Map;for(const[name,file]of files){const path=name.slice("package/".length);if(!name.startsWith("package/")||!path||path.includes("\\")||path.includes(":")||path.split("/").some((part)=>!part||part==="."||part==="..")||result.has(path))fail("Published archive contains an unsafe or duplicate package path");result.set(path,{sha256:hash(new Uint8Array(await file.arrayBuffer())),bytes:file.size})}if(!result.has("package.json"))fail("Published archive has no package manifest");return result}function verifyInstalledFiles(directory,expected){const found=new Set;const hasBundledDependencies=[...expected.keys()].some((path)=>path.startsWith("node_modules/"));function visit(path,depth){if(depth>128)fail("Installed package directory depth exceeds its budget");for(const entry of readdirSync(join(directory,path),{withFileTypes:true})){if(!path&&entry.name==="node_modules"&&!hasBundledDependencies)continue;const name=path?`${path}/${entry.name}`:entry.name;if(found.size>=1e5)fail("Installed package has too many files");const fullPath=join(directory,name);if(entry.isDirectory())visit(name,depth+1);else{const identity=expected.get(name);const stat=lstatSync(fullPath);if(!identity||!stat.isFile()||stat.size!==identity.bytes||hash(readFileSync(fullPath))!==identity.sha256)fail(`Installed package file ${name} differs from the verified archive`);found.add(name)}}}visit("",0);if(found.size!==expected.size)fail("Installed package is missing files from the verified archive")}function installedState(plan,cwd,archives){const lock=readFileSync(join(cwd,"bun.lock"),"utf8");const parsed=Bun.JSONC.parse(lock);const nodeModules=realpathSync(join(cwd,"node_modules"));const manifests=[];for(const source of plan.sources){for(const pkg of source.packages){const locked=parsed.packages?.[pkg.name];if(locked?.[0]!==`${pkg.name}@${pkg.version}`||locked.at(-1)!==pkg.integrity)fail(`Consumer lock does not contain ${pkg.name}@${pkg.version} with the original archive identity`);const directory=realpathSync(join(cwd,"node_modules",pkg.name));const path=relative(nodeModules,directory);if(!path||path.startsWith("..")||resolve(nodeModules,path)!==directory)fail(`${pkg.name} resolves outside the installed consumer packages`);const raw=readFileSync(join(directory,"package.json"),"utf8");const manifest=JSON.parse(raw);if(manifest.name!==pkg.name||manifest.version!==pkg.version)fail(`Installed ${pkg.name} does not match tested version ${pkg.version}`);verifyInstalledFiles(directory,archives.get(pkg.name));manifests.push(hash(raw))}}return{lock,sha256:hash(lock),manifests:manifests.join(":")}}export async function verifyReleaseEvidence(plan,options){validateReleaseEvidencePlan(plan);const requestTimeoutMs=options.requestTimeoutMs??30000;const checkTimeoutMs=options.checkTimeoutMs??300000;const maxArchiveBytes=options.maxArchiveBytes??128*1024*1024;const maxExpandedBytes=options.maxExpandedBytes??128*1024*1024;for(const number of[requestTimeoutMs,checkTimeoutMs,maxArchiveBytes,maxExpandedBytes]){if(!Number.isSafeInteger(number)||number<=0)fail("Budgets must be positive safe integers")}const read=options.fetch??fetch;const archives=new Map;const receipt={schemaVersion:1,verifiedAt:"",sources:[],consumer:{lockfile:"bun.lock",sha256:"",bunVersion:"",checks:[]}};async function request(url,github,limit=1024*1024){const timeout=AbortSignal.timeout(requestTimeoutMs);const signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;signal.throwIfAborted();const response=await read(url,{method:"GET",redirect:"error",signal,headers:github?{Accept:"application/vnd.github+json",...options.token?{Authorization:`Bearer ${options.token}`}:{}}:{}});if(response.status!==200){await response.body?.cancel();fail(`${github?"Source evidence":"Published package"} request returned HTTP ${response.status}`)}return boundedBody(response,limit)}async function github(path){return JSON.parse(new TextDecoder().decode(await request(`https://api.github.com/repos/${path}`,true)))}for(const source of plan.sources){let ref=(await github(`${source.repository}/git/ref/tags/${encodeURIComponent(source.tag)}`)).object;for(let depth=0;ref?.type==="tag"&&depth<5;depth++)ref=(await github(`${source.repository}/git/tags/${ref.sha}`)).object;if(ref?.type!=="commit"||ref.sha!==source.commit)fail(`${source.tag} does not identify ${source.commit}`);const manifest=await github(`${source.repository}/contents/package.json?ref=${source.commit}`);if(manifest.encoding!=="base64"||typeof manifest.content!=="string")fail("Source package manifest is unavailable");const sourcePackage=JSON.parse(Buffer.from(manifest.content,"base64").toString("utf8"));const releaseScript=sourcePackage.scripts?.["release:patch"];if(typeof releaseScript!=="string"||!releaseScript.trim())fail(`${source.repository} has no existing release:patch command`);for(const gate of source.gates){const run=await github(`${source.repository}/actions/runs/${gate.runId}`);if(run.id!==gate.runId||run.repository?.full_name!==source.repository||run.path!==gate.workflow||run.head_sha!==source.commit)fail(`Release gate ${gate.runId} does not verify the exact source and workflow`);if(run.status!=="completed"||run.conclusion!=="success")fail(`Release gate ${gate.runId} is not successful`);const jobs=[];for(let page=1;page<=10;page++){const batch=await github(`${source.repository}/actions/runs/${gate.runId}/jobs?per_page=100&page=${page}`);if(!Array.isArray(batch.jobs))fail(`Release gate ${gate.runId} has no readable jobs`);jobs.push(...batch.jobs);if(batch.jobs.length<100)break;if(page===10)fail("Release job inventory exceeds its budget")}for(const name of gate.requiredJobs){const matches=jobs.filter((job)=>job.name===name);if(matches.length!==1||matches[0]?.status!=="completed"||matches[0]?.conclusion!=="success")fail(`Required release job ${name} did not pass exactly once`)}}const verified={...source,releaseCommand:"bun run release:patch",releaseScript,packages:[]};for(const pkg of source.packages){const metadata=JSON.parse(new TextDecoder().decode(await request(`https://registry.npmjs.org/${encodeURIComponent(pkg.name)}/${encodeURIComponent(pkg.version)}`,false)));if(metadata.name!==pkg.name||metadata.version!==pkg.version||metadata.dist?.integrity!==pkg.integrity)fail(`Published ${pkg.name}@${pkg.version} does not match the original archive identity`);if(metadata.gitHead!==undefined&&metadata.gitHead!==source.commit)fail(`Published ${pkg.name} names a different source commit`);if(!metadata.dist?.tarball)fail(`Published ${pkg.name} has no archive URL`);const tarball=new URL(metadata.dist.tarball);if(tarball.origin!=="https://registry.npmjs.org"||tarball.username||tarball.password)fail("Archive URL is outside the public npm registry");const bytes=await request(tarball.href,false,maxArchiveBytes);if(`sha512-${createHash("sha512").update(bytes).digest("base64")}`!==pkg.integrity)fail(`Published ${pkg.name}@${pkg.version} archive bytes failed SHA-512 verification`);const files=await archiveFiles(bytes,maxExpandedBytes);archives.set(pkg.name,files);const filesSha256=hash(JSON.stringify([...files].sort(([left],[right])=>left.localeCompare(right))));verified.packages.push({...pkg,tarball:tarball.href,bytes:bytes.byteLength,filesSha256})}receipt.sources.push(verified)}const initial=installedState(plan,options.cwd,archives);const checks=await runProjectScripts({cwd:options.cwd,scripts:plan.checks,signal:options.signal,timeoutMs:checkTimeoutMs});receipt.consumer.bunVersion=checks.bunVersion;receipt.consumer.checks=checks.checks;const final=installedState(plan,options.cwd,archives);if(final.sha256!==initial.sha256||final.manifests!==initial.manifests)fail("Consumer checks changed the verified lockfile or package identities");receipt.consumer.sha256=initial.sha256;options.signal?.throwIfAborted();receipt.verifiedAt=new Date().toISOString();return receipt}
@@ -1,9 +1,9 @@
1
- import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative}from"node:path";import{defaultConfig,getCommits,groupCommits}from"@stacksjs/logsmith";export const TESTFLIGHT_NOTES_LIMIT=4000,XCODE_CLOUD_NOTES_LIMIT=1000,PLAY_NOTES_LIMIT=500,DEFAULT_NOTE_TYPES=["feat","fix","perf","revert"],DEFAULT_EXCLUDED_SCOPES=["release","ci","deps","deps-dev","test","tests","docs","lint"];const SECTION_TITLES={feat:"Features",fix:"Fixes",perf:"Performance",refactor:"Changes",revert:"Reverted",style:"Styles",build:"Build",docs:"Documentation"},BANG=/^(\w+)(?:\(([^)]+)\))?!: (.+)$/;function normalized(commit){const bang=commit.type==="misc"?BANG.exec(commit.message):null;return bang?{...commit,type:bang[1],scope:bang[2]||void 0,description:bang[3],breaking:!0}:commit}function line(description,scope){const text=description.replace(/\s*\((?:#\d+(?:,\s*)?)+\)\s*$/,"").replace(/\s+/g," ").trim(),sentence=text.charAt(0).toUpperCase()+text.slice(1),context=scope?.split(",").map((part)=>part.trim()).filter(Boolean).join(", ");return context?`${sentence} (${context})`:sentence}export function testerNotes(commits,options={}){const types=options.types?.length?options.types:DEFAULT_NOTE_TYPES,sections=groupCommits(commits.map(normalized),{...defaultConfig,verbose:!1,includeCommitTypes:types,excludeCommitTypes:[],excludeScopes:options.excludeScopes??DEFAULT_EXCLUDED_SCOPES,includeScopes:[],excludeAuthors:[],includeAuthors:[],excludeMessages:[],groupBreakingChanges:!1,maxCommitsPerSection:0,minCommitsForSection:1,maxDescriptionLength:0}),blocks=[];for(const section of sections){const type=section.commits[0]?.type??"",seen=new Set,lines=section.commits.map((entry)=>line(entry.description,entry.scope)).filter((text)=>text&&!seen.has(text.toLowerCase())&&seen.add(text.toLowerCase())).map((text)=>`- ${text}`);if(!lines.length)continue;const title=SECTION_TITLES[type]??type.charAt(0).toUpperCase()+type.slice(1);blocks.push([options.markdown?`**${title}**`:title,...options.markdown?[""]:[],...lines].join(`
1
+ import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative}from"node:path";import{defaultConfig,getCommits,groupCommits}from"@stacksjs/logsmith";export const TESTFLIGHT_NOTES_LIMIT=4000;export const XCODE_CLOUD_NOTES_LIMIT=1000;export const PLAY_NOTES_LIMIT=500;export const DEFAULT_NOTE_TYPES=["feat","fix","perf","revert"];export const DEFAULT_EXCLUDED_SCOPES=["release","ci","deps","deps-dev","test","tests","docs","lint"];const SECTION_TITLES={feat:"Features",fix:"Fixes",perf:"Performance",refactor:"Changes",revert:"Reverted",style:"Styles",build:"Build",docs:"Documentation"};const BANG=/^(\w+)(?:\(([^)]+)\))?!: (.+)$/;function normalized(commit){const bang=commit.type==="misc"?BANG.exec(commit.message):null;return bang?{...commit,type:bang[1],scope:bang[2]||undefined,description:bang[3],breaking:true}:commit}function line(description,scope){const text=description.replace(/\s*\((?:#\d+(?:,\s*)?)+\)\s*$/,"").replace(/\s+/g," ").trim();const sentence=text.charAt(0).toUpperCase()+text.slice(1);const context=scope?.split(",").map((part)=>part.trim()).filter(Boolean).join(", ");return context?`${sentence} (${context})`:sentence}export function testerNotes(commits,options={}){const types=options.types?.length?options.types:DEFAULT_NOTE_TYPES;const sections=groupCommits(commits.map(normalized),{...defaultConfig,verbose:false,includeCommitTypes:types,excludeCommitTypes:[],excludeScopes:options.excludeScopes??DEFAULT_EXCLUDED_SCOPES,includeScopes:[],excludeAuthors:[],includeAuthors:[],excludeMessages:[],groupBreakingChanges:false,maxCommitsPerSection:0,minCommitsForSection:1,maxDescriptionLength:0});const blocks=[];for(const section of sections){const type=section.commits[0]?.type??"";const seen=new Set;const lines=section.commits.map((entry)=>line(entry.description,entry.scope)).filter((text)=>text&&!seen.has(text.toLowerCase())&&seen.add(text.toLowerCase())).map((text)=>`- ${text}`);if(!lines.length)continue;const title=SECTION_TITLES[type]??type.charAt(0).toUpperCase()+type.slice(1);blocks.push([options.markdown?`**${title}**`:title,...options.markdown?[""]:[],...lines].join(`
2
2
  `))}return blocks.join(`
3
3
 
4
4
  `)}export const NO_VISIBLE_CHANGES="Maintenance build: no visible changes since the previous build.";export function fitNotes(text,limit){const notes=text.trim();if(notes.length<=limit)return notes;const lines=notes.split(`
5
- `),isItem=(value)=>/^\s*(?:[-*\u2022]|\d+\.)\s/.test(value),suffix=(omitted)=>omitted>0?`
6
- \u2026and ${omitted} more`:"\u2026",kept=[];let index=0;for(;index<lines.length;index++){const rest=lines.slice(index+1).filter(isItem).length;if([...kept,lines[index]].join(`
7
- `).length+suffix(rest).length>limit)break;kept.push(lines[index])}const trim=()=>{while(kept.length&&!kept[kept.length-1].trim())kept.pop()};trim();if(kept.length&&!isItem(kept[kept.length-1])&&lines[kept.length]!==void 0&&isItem(lines[kept.length])&&kept.some(isItem)){kept.pop();trim()}const omitted=lines.slice(kept.length).filter(isItem).length;if(!kept.length||omitted===0&&!kept.some(isItem)){const room=limit-1,cut=notes.slice(0,room),word=cut.lastIndexOf(" ");return`${(word>room/2?cut.slice(0,word):cut).trimEnd()}\u2026`}return`${kept.join(`
8
- `)}${suffix(omitted)}`}function git(cwd,args){const result=Bun.spawnSync(["git",...args],{cwd,stdout:"pipe",stderr:"ignore"});return result.exitCode===0?result.stdout.toString().trim():null}export function previousMobileTag(cwd,ref="HEAD"){return git(cwd,["describe","--tags","--match","v*-build.*","--abbrev=0",ref])||void 0}export function commitsBetween(cwd,from,to="HEAD"){return getCommits(from,to,cwd)}function readNotesFile(cwd,path,origin){const absolute=isAbsolute(path)?path:join(cwd,path);if(!existsSync(absolute))throw Error(`${origin} names ${path}, which does not exist`);return readFileSync(absolute,"utf8")}export function resolveNotes(options){const{cwd,flags={},env=process.env,config={}}=options,pick=(text,file,origin,source)=>{if(text?.trim()&&file?.trim())throw Error(`give either ${origin[0]} or ${origin[1]}, not both`);const value=text?.trim()?text:file?.trim()?readNotesFile(cwd,file.trim(),origin[1]):void 0;return value?.trim()?{text:value.trim(),source}:null},notes=typeof flags.notes==="string"?flags.notes:void 0,notesFile=typeof flags.notesFile==="string"?flags.notesFile:void 0;return pick(notes,notesFile,["--notes","--notes-file"],"flag")??pick(env.RELEASE_NOTES,env.RELEASE_NOTES_FILE,["RELEASE_NOTES","RELEASE_NOTES_FILE"],"env")??pick(config.notes,config.notesFile,["release.notes","release.notesFile"],"config")??{text:options.generate().trim()||NO_VISIBLE_CHANGES,source:"generated"}}const APP_STORE_LOCALES={en:"en-US",de:"de-DE",fr:"fr-FR",es:"es-ES",nl:"nl-NL",pt:"pt-BR",zh:"zh-Hans"};export function appStoreLocales(languages){const locales=(languages??[]).map((language)=>language.trim().replace("_","-")).filter(Boolean).map((language)=>language.includes("-")?language:APP_STORE_LOCALES[language.toLowerCase()]??language.toLowerCase());return[...new Set(["en-US",...locales])]}export function writeWhatToTest(root,projectDir,notes,locales){const dir=join(isAbsolute(projectDir)?projectDir:join(root,projectDir),"TestFlight");mkdirSync(dir,{recursive:!0});const text=`${fitNotes(notes,XCODE_CLOUD_NOTES_LIMIT)}
5
+ `);const isItem=(value)=>/^\s*(?:[-*•]|\d+\.)\s/.test(value);const suffix=(omitted)=>omitted>0?`
6
+ …and ${omitted} more`:"…";const kept=[];let index=0;for(;index<lines.length;index++){const rest=lines.slice(index+1).filter(isItem).length;const candidate=[...kept,lines[index]].join(`
7
+ `);if(candidate.length+suffix(rest).length>limit)break;kept.push(lines[index])}const trim=()=>{while(kept.length&&!kept[kept.length-1].trim())kept.pop()};trim();if(kept.length&&!isItem(kept[kept.length-1])&&lines[kept.length]!==undefined&&isItem(lines[kept.length])&&kept.some(isItem)){kept.pop();trim()}const omitted=lines.slice(kept.length).filter(isItem).length;if(!kept.length||omitted===0&&!kept.some(isItem)){const room=limit-1;const cut=notes.slice(0,room);const word=cut.lastIndexOf(" ");return`${(word>room/2?cut.slice(0,word):cut).trimEnd()}…`}return`${kept.join(`
8
+ `)}${suffix(omitted)}`}function git(cwd,args){const result=Bun.spawnSync(["git",...args],{cwd,stdout:"pipe",stderr:"ignore"});return result.exitCode===0?result.stdout.toString().trim():null}export function previousMobileTag(cwd,ref="HEAD"){return git(cwd,["describe","--tags","--match","v*-build.*","--abbrev=0",ref])||undefined}export function commitsBetween(cwd,from,to="HEAD"){return getCommits(from,to,cwd)}function readNotesFile(cwd,path,origin){const absolute=isAbsolute(path)?path:join(cwd,path);if(!existsSync(absolute))throw new Error(`${origin} names ${path}, which does not exist`);return readFileSync(absolute,"utf8")}export function resolveNotes(options){const{cwd,flags={},env=process.env,config={}}=options;const pick=(text,file,origin,source)=>{if(text?.trim()&&file?.trim())throw new Error(`give either ${origin[0]} or ${origin[1]}, not both`);const value=text?.trim()?text:file?.trim()?readNotesFile(cwd,file.trim(),origin[1]):undefined;return value?.trim()?{text:value.trim(),source}:null};const notes=typeof flags.notes==="string"?flags.notes:undefined;const notesFile=typeof flags.notesFile==="string"?flags.notesFile:undefined;return pick(notes,notesFile,["--notes","--notes-file"],"flag")??pick(env.RELEASE_NOTES,env.RELEASE_NOTES_FILE,["RELEASE_NOTES","RELEASE_NOTES_FILE"],"env")??pick(config.notes,config.notesFile,["release.notes","release.notesFile"],"config")??{text:options.generate().trim()||NO_VISIBLE_CHANGES,source:"generated"}}const APP_STORE_LOCALES={en:"en-US",de:"de-DE",fr:"fr-FR",es:"es-ES",nl:"nl-NL",pt:"pt-BR",zh:"zh-Hans"};export function appStoreLocales(languages){const locales=(languages??[]).map((language)=>language.trim().replace("_","-")).filter(Boolean).map((language)=>language.includes("-")?language:APP_STORE_LOCALES[language.toLowerCase()]??language.toLowerCase());return[...new Set(["en-US",...locales])]}export function writeWhatToTest(root,projectDir,notes,locales){const dir=join(isAbsolute(projectDir)?projectDir:join(root,projectDir),"TestFlight");mkdirSync(dir,{recursive:true});const text=`${fitNotes(notes,XCODE_CLOUD_NOTES_LIMIT)}
9
9
  `;return locales.map((locale)=>{const path=join(dir,`WhatToTest.${locale}.txt`);writeFileSync(path,text);return relative(root,path)})}export function committedWhatToTest(cwd,tag,projectDir,locale="en-US"){const path=`${projectDir.replace(/\/$/,"")}/TestFlight/WhatToTest.${locale}.txt`;return git(cwd,["show",`${tag}:${path}`])}
@@ -1,3 +1,3 @@
1
- import{readFileSync}from"node:fs";import{join}from"node:path";export const BYPASS_ENV="RELEASE_GATE_BYPASS";export function pinnedCheckScripts(scripts){return Object.keys(scripts).filter((name)=>name==="declarations:check"||/^docs:(?:[\w:-]+:)?check$/.test(name)).sort()}export function readPinnedChecks(cwd){try{const pkg=JSON.parse(readFileSync(join(cwd,"package.json"),"utf8"));return pinnedCheckScripts(pkg.scripts??{})}catch{return[]}}function isBypassed(env){const value=env[BYPASS_ENV];return value==="1"||value==="true"}export async function runPinnedChecks(options={cwd:process.cwd()}){const env=options.env??process.env;if(isBypassed(env))return{ran:[],failures:[],bypassed:!0};const scripts=options.scripts??readPinnedChecks(options.cwd);if(scripts.length===0)return{ran:[],failures:[],bypassed:!1};const results=await Promise.all(scripts.map(async(script)=>{const proc=Bun.spawn(["bun","run",script],{cwd:options.cwd,stdout:"pipe",stderr:"pipe"}),[stdout,stderr,exitCode]=await Promise.all([new Response(proc.stdout).text(),new Response(proc.stderr).text(),proc.exited]);return{script,exitCode,output:`${stdout}${stderr}`.trim()}}));return{ran:scripts,failures:results.filter((r)=>r.exitCode!==0).map((r)=>({script:r.script,output:r.output})),bypassed:!1}}export function formatPreflightFailure(failures){const diagnosticLines=(output)=>output.split(`
2
- `).map((line)=>line.trim()).filter((line)=>line&&!line.startsWith("[env]")&&!line.startsWith("$ ")&&!line.startsWith("error: script")),lines=[`Release blocked: ${failures.length} pinned check${failures.length===1?"":"s"} failed.`,""];for(const failure of failures){lines.push(` ${failure.script}`);const informative=diagnosticLines(failure.output.replace(/^\[env-plugin\] Errors: \[\r?\n[\s\S]*?^\][ \t]*\r?$/gm,"")),diagnostics=informative.length?informative:diagnosticLines(failure.output);for(const line of diagnostics.slice(0,4))lines.push(` ${line}`);lines.push("")}lines.push("Nothing was bumped, committed, or tagged.");lines.push(`Regenerate the affected artifacts and retry, or set ${BYPASS_ENV}=1 to release anyway.`);return lines.join(`
1
+ import{readFileSync}from"node:fs";import{join}from"node:path";export const BYPASS_ENV="RELEASE_GATE_BYPASS";export function pinnedCheckScripts(scripts){return Object.keys(scripts).filter((name)=>name==="declarations:check"||/^docs:(?:[\w:-]+:)?check$/.test(name)).sort()}export function readPinnedChecks(cwd){try{const pkg=JSON.parse(readFileSync(join(cwd,"package.json"),"utf8"));return pinnedCheckScripts(pkg.scripts??{})}catch{return[]}}function isBypassed(env){const value=env[BYPASS_ENV];return value==="1"||value==="true"}export async function runPinnedChecks(options={cwd:process.cwd()}){const env=options.env??process.env;if(isBypassed(env))return{ran:[],failures:[],bypassed:true};const scripts=options.scripts??readPinnedChecks(options.cwd);if(scripts.length===0)return{ran:[],failures:[],bypassed:false};const results=await Promise.all(scripts.map(async(script)=>{const proc=Bun.spawn(["bun","run",script],{cwd:options.cwd,stdout:"pipe",stderr:"pipe"});const[stdout,stderr,exitCode]=await Promise.all([new Response(proc.stdout).text(),new Response(proc.stderr).text(),proc.exited]);return{script,exitCode,output:`${stdout}${stderr}`.trim()}}));return{ran:scripts,failures:results.filter((r)=>r.exitCode!==0).map((r)=>({script:r.script,output:r.output})),bypassed:false}}export function formatPreflightFailure(failures){const diagnosticLines=(output)=>output.split(`
2
+ `).map((line)=>line.trim()).filter((line)=>line&&!line.startsWith("[env]")&&!line.startsWith("$ ")&&!line.startsWith("error: script"));const lines=[`Release blocked: ${failures.length} pinned check${failures.length===1?"":"s"} failed.`,""];for(const failure of failures){lines.push(` ${failure.script}`);const informative=diagnosticLines(failure.output.replace(/^\[env-plugin\] Errors: \[\r?\n[\s\S]*?^\][ \t]*\r?$/gm,""));const diagnostics=informative.length?informative:diagnosticLines(failure.output);for(const line of diagnostics.slice(0,4))lines.push(` ${line}`);lines.push("")}lines.push("Nothing was bumped, committed, or tagged.");lines.push(`Regenerate the affected artifacts and retry, or set ${BYPASS_ENV}=1 to release anyway.`);return lines.join(`
3
3
  `)}
@@ -1,3 +1,3 @@
1
- import{execFileSync}from"node:child_process";import process from"node:process";export function releasePushTarget(cwd=process.cwd(),requiredBranch){const git=(args,optional=!1)=>{try{return execFileSync("git",args,{cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}catch(error){if(optional&&error instanceof Error&&"status"in error&&error.status===1)return"";throw Error("Cannot resolve the release branch and remote. Release requires a valid Git checkout on a branch.")}},branch=git(["symbolic-ref","--short","HEAD"]),remote=git(["config","--get-all",`branch.${branch}.remote`],!0),ref=git(["config","--get-all",`branch.${branch}.merge`],!0);if(Boolean(remote)!==Boolean(ref))throw Error("The release branch has an incomplete upstream configuration.");const target={remote:remote||"origin",ref:ref||`refs/heads/${branch}`};if(target.remote==="."||!git(["remote"]).split(`
2
- `).includes(target.remote))throw Error("The release destination must name a configured remote.");if(!target.ref.startsWith("refs/heads/")||target.ref.includes(`
3
- `))throw Error("The release upstream must be a single branch.");git(["check-ref-format",target.ref]);if(requiredBranch&&target.ref!==`refs/heads/${requiredBranch}`)throw Error(`Release requires upstream branch refs/heads/${requiredBranch}; configure this branch to track ${target.remote}/${requiredBranch} before releasing.`);return target}
1
+ import{execFileSync}from"node:child_process";import process from"node:process";export function releasePushTarget(cwd=process.cwd(),requiredBranch){const git=(args,optional=false)=>{try{return execFileSync("git",args,{cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}catch(error){if(optional&&error instanceof Error&&"status"in error&&error.status===1)return"";throw new Error("Cannot resolve the release branch and remote. Release requires a valid Git checkout on a branch.")}};const branch=git(["symbolic-ref","--short","HEAD"]);const remote=git(["config","--get-all",`branch.${branch}.remote`],true);const ref=git(["config","--get-all",`branch.${branch}.merge`],true);if(Boolean(remote)!==Boolean(ref))throw new Error("The release branch has an incomplete upstream configuration.");const target={remote:remote||"origin",ref:ref||`refs/heads/${branch}`};if(target.remote==="."||!git(["remote"]).split(`
2
+ `).includes(target.remote))throw new Error("The release destination must name a configured remote.");if(!target.ref.startsWith("refs/heads/")||target.ref.includes(`
3
+ `))throw new Error("The release upstream must be a single branch.");git(["check-ref-format",target.ref]);if(requiredBranch&&target.ref!==`refs/heads/${requiredBranch}`)throw new Error(`Release requires upstream branch refs/heads/${requiredBranch}; configure this branch to track ${target.remote}/${requiredBranch} before releasing.`);return target}
package/dist/release.js CHANGED
@@ -1 +1 @@
1
- import{parseOptions}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{assertPublicationAllowed}from"./publication-preflight";import{runActions}from"./helpers/utils";import{resolvePantryToolchain}from"./pantry-toolchain";import{releasePushTarget}from"./release-push-target";import{BYPASS_ENV,formatPreflightFailure,runPinnedChecks}from"./release-preflight";const raw=parseOptions()??{},passthrough={};for(const[k,v]of Object.entries(raw)){if(k==="--"||k==="_")continue;passthrough[k]=v}const isDryRun=passthrough.dryRun===!0||passthrough.dryRun==="true",actions=isDryRun?[Action.Bump]:[Action.GenerateLibraryEntries,Action.Bump];if(!isDryRun){await assertPublicationAllowed({cwd:projectPath(),channel:"github-release"});if((await Bun.file(projectPath("package.json")).json()).name==="stacks"&&await Bun.file(projectPath("storage/framework/core/package.json")).exists())releasePushTarget(projectPath(),"main")}const preflight=await runPinnedChecks({cwd:projectPath()});if(preflight.bypassed)log.warn(`${BYPASS_ENV} is set, so the pinned checks were skipped for this release.`);else if(preflight.failures.length>0){await log.flush();await log.exit(formatPreflightFailure(preflight.failures),1)}const pantryToolchain=resolvePantryToolchain({cwd:projectPath()});if(!pantryToolchain.ok){await log.flush();await log.exit(pantryToolchain.message,1)}else log.info(`Pantry ${pantryToolchain.version} (${pantryToolchain.bin})${pantryToolchain.declared?` satisfies ts-pantry ${pantryToolchain.declared}`:""}`);const result=await runActions(actions,{cwd:projectPath(),...passthrough});if(result&&result.isErr)await log.exit(`Release failed: ${result.error?.message??String(result.error)}`,1);log.success(isDryRun?`Dry run complete for ${app.name}. Nothing was committed, tagged or pushed.`:`Successfully released ${app.name}`);
1
+ import{parseOptions}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{assertPublicationAllowed}from"./publication-preflight";import{runActions}from"./helpers/utils";import{resolvePantryToolchain}from"./pantry-toolchain";import{releasePushTarget}from"./release-push-target";import{BYPASS_ENV,formatPreflightFailure,runPinnedChecks}from"./release-preflight";const raw=parseOptions()??{};const passthrough={};for(const[k,v]of Object.entries(raw)){if(k==="--"||k==="_")continue;passthrough[k]=v}const isDryRun=passthrough.dryRun===true||passthrough.dryRun==="true";const actions=isDryRun?[Action.Bump]:[Action.GenerateLibraryEntries,Action.Bump];if(!isDryRun){await assertPublicationAllowed({cwd:projectPath(),channel:"github-release"});const rootManifest=await Bun.file(projectPath("package.json")).json();const framework=rootManifest.name==="stacks"&&await Bun.file(projectPath("storage/framework/core/package.json")).exists();if(framework)releasePushTarget(projectPath(),"main")}const preflight=await runPinnedChecks({cwd:projectPath()});if(preflight.bypassed){log.warn(`${BYPASS_ENV} is set, so the pinned checks were skipped for this release.`)}else if(preflight.failures.length>0){await log.flush();await log.exit(formatPreflightFailure(preflight.failures),1)}const pantryToolchain=resolvePantryToolchain({cwd:projectPath()});if(!pantryToolchain.ok){await log.flush();await log.exit(pantryToolchain.message,1)}else{log.info(`Pantry ${pantryToolchain.version} (${pantryToolchain.bin})${pantryToolchain.declared?` satisfies ts-pantry ${pantryToolchain.declared}`:""}`)}const result=await runActions(actions,{cwd:projectPath(),...passthrough});if(result&&result.isErr){await log.exit(`Release failed: ${result.error?.message??String(result.error)}`,1)}log.success(isDryRun?`Dry run complete for ${app.name}. Nothing was committed, tagged or pushed.`:`Successfully released ${app.name}`);
@@ -1 +1 @@
1
- function blocked(reason){throw Error(`ReviewOS evidence blocked: ${reason}`)}function validate(plan){const origin=new URL(plan.origin);if(origin.protocol!=="https:"||origin.username||origin.password||origin.pathname!=="/"||origin.search||origin.hash||!/^[\w.-]+$/.test(plan.owner)||!/^[\w.-]+$/.test(plan.repository)||!/^[a-f0-9]{40}$/.test(plan.commit)||!/^[a-f0-9]{64}$/.test(plan.workflowDigest)||!/^\.reviewos\/workflows\/[\w.-]+\.ya?ml$/.test(plan.workflow)||!plan.job||!plan.labels.length||!plan.steps.length||[...plan.labels,...plan.steps].some((value)=>typeof value!=="string"||!value)||new Set(plan.steps).size!==plan.steps.length)blocked("Expected an HTTPS forge, exact source and workflow identities, job, labels and steps");return origin}export function evaluateReviewOsEvidence(plan,value){const origin=validate(plan),run=value?.workflow_run;if(!run||!Number.isSafeInteger(run.number)||run.number<=0||run.head_sha!==plan.commit||run.trusted!==!0||run.ref!=="refs/heads/main"||!["push","workflow_dispatch"].includes(run.event)||run.workflow?.path!==plan.workflow||run.workflow?.owner_defined!==!1||run.version?.path!==plan.workflow||run.version?.digest!==plan.workflowDigest)blocked("The run does not identify the trusted main source and committed workflow");if(["queued","running","waiting","paused"].includes(run.state))return{state:"pending"};if(run.state!=="succeeded")blocked(`Run ${run.number} concluded ${String(run.state)}`);if(!Array.isArray(run.jobs))blocked("The run has no job evidence");const jobs=run.jobs.filter((job)=>job.job_id===plan.job),job=jobs[0];if(jobs.length!==1||job.state!=="succeeded"||!job.runner||!job.started_at||!job.finished_at||job.resume_from_step!==null||!Array.isArray(job.runs_on)||plan.labels.some((label)=>!job.runs_on.includes(label))||!Array.isArray(job.steps))blocked("The required job did not execute fully on the declared runner");for(const name of plan.steps){const steps=job.steps.filter((step)=>step.name===name),step=steps[0];if(steps.length!==1||step.state!=="succeeded"||step.exit_code!==0||!step.started_at||!step.finished_at||step.reused_from_attempt!=null)blocked(`Required step did not execute successfully: ${name}`)}return{state:"accepted",number:run.number,url:new URL(`/${plan.owner}/${plan.repository}/run/${run.number}`,origin).href}}export async function inspectReviewOsEvidence(plan,options={}){const origin=validate(plan),request=options.fetch??fetch;async function read(path,values){const url=new URL(`/api/repos/${path}`,origin);for(const[name,value]of Object.entries({owner:plan.owner,repo:plan.repository,...values}))url.searchParams.set(name,value);const response=await request(url.href,{redirect:"error",headers:{accept:"application/json"},signal:options.signal?AbortSignal.any([options.signal,AbortSignal.timeout(30000)]):AbortSignal.timeout(30000)});if(!response.ok)blocked(`Metadata API returned HTTP ${response.status}`);if(!response.body)blocked("Metadata API returned no body");const reader=response.body.getReader(),chunks=[];let size=0;try{while(!0){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>1048576)blocked("Metadata exceeds its byte budget");chunks.push(part.value)}return JSON.parse(Buffer.concat(chunks).toString("utf8"))}finally{await reader.cancel().catch(()=>{});reader.releaseLock()}}async function pages(path,field,values){const rows=[],cursors=new Set;let cursor="";for(let page=0;page<10;page++){const data=await read(path,{...values,per_page:"100",...cursor?{cursor}:{}});if(!Array.isArray(data[field]))blocked("Metadata API returned an invalid collection");rows.push(...data[field]);if(data.next===null)return rows;if(typeof data.next!=="string"||!data.next||cursors.has(data.next))blocked("Invalid metadata pagination");cursors.add(data.next);cursor=data.next}return blocked("Metadata exceeds its page budget")}const workflows=(await pages("workflows","workflows",{})).filter((row)=>row.path===plan.workflow);if(!workflows.length)return{state:"pending"};if(workflows.length!==1||!Number.isSafeInteger(workflows[0].id)||workflows[0].id<=0)blocked("Workflow identity is ambiguous");const runs=await pages("workflow-runs","workflow_runs",{workflow:String(workflows[0].id),sha:plan.commit,branch:"main"});if(runs.some((row)=>row.head_sha!==plan.commit||!Number.isSafeInteger(row.number)||row.number<=0))blocked("Run collection has an invalid source identity");const newest=runs.sort((a,b)=>b.number-a.number)[0];if(!newest)return{state:"pending"};const detail=await read("workflow-runs/show",{number:String(newest.number)});if(detail?.workflow_run?.number!==newest.number)blocked("Run detail does not match the selected run");return evaluateReviewOsEvidence(plan,detail)}
1
+ function blocked(reason){throw new Error(`ReviewOS evidence blocked: ${reason}`)}function validate(plan){const origin=new URL(plan.origin);if(origin.protocol!=="https:"||origin.username||origin.password||origin.pathname!=="/"||origin.search||origin.hash||!/^[\w.-]+$/.test(plan.owner)||!/^[\w.-]+$/.test(plan.repository)||!/^[a-f0-9]{40}$/.test(plan.commit)||!/^[a-f0-9]{64}$/.test(plan.workflowDigest)||!/^\.reviewos\/workflows\/[\w.-]+\.ya?ml$/.test(plan.workflow)||!plan.job||!plan.labels.length||!plan.steps.length||[...plan.labels,...plan.steps].some((value)=>typeof value!=="string"||!value)||new Set(plan.steps).size!==plan.steps.length)blocked("Expected an HTTPS forge, exact source and workflow identities, job, labels and steps");return origin}export function evaluateReviewOsEvidence(plan,value){const origin=validate(plan);const run=value?.workflow_run;if(!run||!Number.isSafeInteger(run.number)||run.number<=0||run.head_sha!==plan.commit||run.trusted!==true||run.ref!=="refs/heads/main"||!["push","workflow_dispatch"].includes(run.event)||run.workflow?.path!==plan.workflow||run.workflow?.owner_defined!==false||run.version?.path!==plan.workflow||run.version?.digest!==plan.workflowDigest)blocked("The run does not identify the trusted main source and committed workflow");if(["queued","running","waiting","paused"].includes(run.state))return{state:"pending"};if(run.state!=="succeeded")blocked(`Run ${run.number} concluded ${String(run.state)}`);if(!Array.isArray(run.jobs))blocked("The run has no job evidence");const jobs=run.jobs.filter((job)=>job.job_id===plan.job);const job=jobs[0];if(jobs.length!==1||job.state!=="succeeded"||!job.runner||!job.started_at||!job.finished_at||job.resume_from_step!==null||!Array.isArray(job.runs_on)||plan.labels.some((label)=>!job.runs_on.includes(label))||!Array.isArray(job.steps))blocked("The required job did not execute fully on the declared runner");for(const name of plan.steps){const steps=job.steps.filter((step)=>step.name===name);const step=steps[0];if(steps.length!==1||step.state!=="succeeded"||step.exit_code!==0||!step.started_at||!step.finished_at||step.reused_from_attempt!=null)blocked(`Required step did not execute successfully: ${name}`)}return{state:"accepted",number:run.number,url:new URL(`/${plan.owner}/${plan.repository}/run/${run.number}`,origin).href}}export async function inspectReviewOsEvidence(plan,options={}){const origin=validate(plan);const request=options.fetch??fetch;async function read(path,values){const url=new URL(`/api/repos/${path}`,origin);for(const[name,value]of Object.entries({owner:plan.owner,repo:plan.repository,...values}))url.searchParams.set(name,value);const response=await request(url.href,{redirect:"error",headers:{accept:"application/json"},signal:options.signal?AbortSignal.any([options.signal,AbortSignal.timeout(30000)]):AbortSignal.timeout(30000)});if(!response.ok)blocked(`Metadata API returned HTTP ${response.status}`);if(!response.body)blocked("Metadata API returned no body");const reader=response.body.getReader();const chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>1048576)blocked("Metadata exceeds its byte budget");chunks.push(part.value)}return JSON.parse(Buffer.concat(chunks).toString("utf8"))}finally{await reader.cancel().catch(()=>{});reader.releaseLock()}}async function pages(path,field,values){const rows=[];const cursors=new Set;let cursor="";for(let page=0;page<10;page++){const data=await read(path,{...values,per_page:"100",...cursor?{cursor}:{}});if(!Array.isArray(data[field]))blocked("Metadata API returned an invalid collection");rows.push(...data[field]);if(data.next===null)return rows;if(typeof data.next!=="string"||!data.next||cursors.has(data.next))blocked("Invalid metadata pagination");cursors.add(data.next);cursor=data.next}return blocked("Metadata exceeds its page budget")}const workflows=(await pages("workflows","workflows",{})).filter((row)=>row.path===plan.workflow);if(!workflows.length)return{state:"pending"};if(workflows.length!==1||!Number.isSafeInteger(workflows[0].id)||workflows[0].id<=0)blocked("Workflow identity is ambiguous");const runs=await pages("workflow-runs","workflow_runs",{workflow:String(workflows[0].id),sha:plan.commit,branch:"main"});if(runs.some((row)=>row.head_sha!==plan.commit||!Number.isSafeInteger(row.number)||row.number<=0))blocked("Run collection has an invalid source identity");const newest=runs.sort((a,b)=>b.number-a.number)[0];if(!newest)return{state:"pending"};const detail=await read("workflow-runs/show",{number:String(newest.number)});if(detail?.workflow_run?.number!==newest.number)blocked("Run detail does not match the selected run");return evaluateReviewOsEvidence(plan,detail)}
@@ -1,2 +1,2 @@
1
1
  import process from"node:process";import{italic,log}from"@stacksjs/cli";import{route}from"@stacksjs/router";const METHOD_ORDER=["GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"];function formatHandler(handler){if(typeof handler==="string")return handler;if(typeof handler==="function")return handler.name?`[fn ${handler.name}]`:"[fn]";return"[handler]"}function pad(value,width){if(value.length>=width)return value;return value+" ".repeat(width-value.length)}function write(line){process.stdout.write(`${line}
2
- `)}async function listRoutes(){try{await route.importRoutes()}catch(error){return{isErr:!0,error}}const registered=route.routes??[];if(registered.length===0){write(italic("No routes registered."));return{}}const rows=registered.map((r)=>({method:String(r.method||"GET").toUpperCase(),uri:String(r.path||r.uri||""),handler:formatHandler(r.handler??r.action??""),name:String(r.name||""),middleware:Array.isArray(r.middleware)?r.middleware.join(","):String(r.middleware||"")}));rows.sort((a,b)=>{const ai=METHOD_ORDER.indexOf(a.method),bi=METHOD_ORDER.indexOf(b.method);if(ai!==bi)return(ai===-1?99:ai)-(bi===-1?99:bi);return a.uri.localeCompare(b.uri)});const widths={method:Math.max(6,...rows.map((r)=>r.method.length)),uri:Math.max(3,...rows.map((r)=>r.uri.length)),handler:Math.max(7,...rows.map((r)=>r.handler.length)),name:Math.max(4,...rows.map((r)=>r.name.length))},header=[pad("METHOD",widths.method),pad("URI",widths.uri),pad("HANDLER",widths.handler),pad("NAME",widths.name),"MIDDLEWARE"].join(" ");write("");write(header);write("-".repeat(header.length));for(const r of rows)write([pad(r.method,widths.method),pad(r.uri,widths.uri),pad(r.handler,widths.handler),pad(r.name||"-",widths.name),r.middleware||"-"].join(" "));write("");write(italic(`${rows.length} route${rows.length===1?"":"s"} registered.`));return{}}const result=await listRoutes();if(result?.isErr){console.error(result.error);await log.error("Route lists failed",result.error);process.exit(1)}process.exit(0);
2
+ `)}async function listRoutes(){try{await route.importRoutes()}catch(error){return{isErr:true,error}}const registered=route.routes??[];if(registered.length===0){write(italic("No routes registered."));return{}}const rows=registered.map((r)=>({method:String(r.method||"GET").toUpperCase(),uri:String(r.path||r.uri||""),handler:formatHandler(r.handler??r.action??""),name:String(r.name||""),middleware:Array.isArray(r.middleware)?r.middleware.join(","):String(r.middleware||"")}));rows.sort((a,b)=>{const ai=METHOD_ORDER.indexOf(a.method);const bi=METHOD_ORDER.indexOf(b.method);if(ai!==bi)return(ai===-1?99:ai)-(bi===-1?99:bi);return a.uri.localeCompare(b.uri)});const widths={method:Math.max(6,...rows.map((r)=>r.method.length)),uri:Math.max(3,...rows.map((r)=>r.uri.length)),handler:Math.max(7,...rows.map((r)=>r.handler.length)),name:Math.max(4,...rows.map((r)=>r.name.length))};const header=[pad("METHOD",widths.method),pad("URI",widths.uri),pad("HANDLER",widths.handler),pad("NAME",widths.name),"MIDDLEWARE"].join(" ");write("");write(header);write("-".repeat(header.length));for(const r of rows){write([pad(r.method,widths.method),pad(r.uri,widths.uri),pad(r.handler,widths.handler),pad(r.name||"-",widths.name),r.middleware||"-"].join(" "))}write("");write(italic(`${rows.length} route${rows.length===1?"":"s"} registered.`));return{}}const result=await listRoutes();if(result?.isErr){console.error(result.error);await log.error("Route lists failed",result.error);process.exit(1)}process.exit(0);
@@ -1 +1 @@
1
- import process from"node:process";import{log}from"@stacksjs/logging";import{createStripeProduct,formatSetupReport}from"@stacksjs/payments";const argv=process.argv.slice(2),dryRun=argv.includes("--dry-run")||argv.includes("--dryRun"),result=await createStripeProduct({dryRun});if(result?.isErr){console.error(result.error);await log.error("stripe:setup failed",result.error);process.exit(1)}const report=result.value;log.info(dryRun?"Dry run. Nothing was written to Stripe. This is what would be applied:":"Applied:");for(const line of formatSetupReport(report))log.info(line);const conflicts=report.actions.filter((action)=>action.verb==="conflict");if(conflicts.length){await log.error(`stripe:setup left ${conflicts.length} conflict${conflicts.length===1?"":"s"} for you to resolve.`);process.exit(1)}
1
+ import process from"node:process";import{log}from"@stacksjs/logging";import{createStripeProduct,formatSetupReport}from"@stacksjs/payments";const argv=process.argv.slice(2);const dryRun=argv.includes("--dry-run")||argv.includes("--dryRun");const result=await createStripeProduct({dryRun});if(result?.isErr){console.error(result.error);await log.error("stripe:setup failed",result.error);process.exit(1)}const report=result.value;log.info(dryRun?"Dry run. Nothing was written to Stripe. This is what would be applied:":"Applied:");for(const line of formatSetupReport(report))log.info(line);const conflicts=report.actions.filter((action)=>action.verb==="conflict");if(conflicts.length){await log.error(`stripe:setup left ${conflicts.length} conflict${conflicts.length===1?"":"s"} for you to resolve.`);process.exit(1)}
@@ -1,5 +1,5 @@
1
- import{italic}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{writeTextFile}from"@stacksjs/storage";import{isDryRunActive}from"./make";const TYPE_ALIASES={str:"string",string:"string",varchar:"string",text:"text",longtext:"text",int:"number",integer:"number",number:"number",num:"number",bool:"boolean",boolean:"boolean",date:"date",datetime:"date",json:"json"};export function parseFields(input){if(!input)return[];const parts=input.split(",").map((p)=>p.trim()).filter(Boolean),out=[];for(const part of parts){const[rawName,rawType="string"]=part.split(":"),name=rawName?.trim();if(!name)continue;const type=TYPE_ALIASES[rawType.trim().toLowerCase()]??"string";out.push({name,type})}return out}function pluralize(word){if(!word)return word;const lower=word.toLowerCase();if(lower.endsWith("s")||lower.endsWith("x")||lower.endsWith("z")||lower.endsWith("ch")||lower.endsWith("sh"))return`${word}es`;if(lower.endsWith("y")&&!/[aeiou]y$/.test(lower))return`${word.slice(0,-1)}ies`;return`${word}s`}function pascalCase(name){return name.replace(/(^|[-_\s])(\w)/g,(_,__,c)=>String(c).toUpperCase())}function snakeCase(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()}function attributeBlock(fields){if(fields.length===0)return" title: { type: 'string', fillable: true, validation: { rule: schema.string().required() } },";return fields.map((f)=>{const t=f.type,rule=t==="number"?"schema.number()":t==="boolean"?"schema.boolean()":t==="date"?"schema.date()":t==="json"?"schema.object({})":"schema.string()",dbType=t==="number"?"number":t==="boolean"?"boolean":t==="date"?"date":t==="json"?"json":"string";return` ${f.name}: { type: '${dbType}', fillable: true, validation: { rule: ${rule} } },`}).join(`
2
- `)}function migrationColumns(fields){if(fields.length===0)return" .addColumn('title', 'varchar(255)', col => col.notNull())";return fields.map((f)=>{switch(f.type){case"number":return` .addColumn('${f.name}', 'integer')`;case"boolean":return` .addColumn('${f.name}', 'boolean', col => col.defaultTo(false))`;case"text":return` .addColumn('${f.name}', 'text')`;case"date":return` .addColumn('${f.name}', 'timestamp')`;case"json":return` .addColumn('${f.name}', 'text')`;default:return` .addColumn('${f.name}', 'varchar(255)')`}}).join(`
1
+ import{italic}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{writeTextFile}from"@stacksjs/storage";import{isDryRunActive}from"./make";const TYPE_ALIASES={str:"string",string:"string",varchar:"string",text:"text",longtext:"text",int:"number",integer:"number",number:"number",num:"number",bool:"boolean",boolean:"boolean",date:"date",datetime:"date",json:"json"};export function parseFields(input){if(!input)return[];const parts=input.split(",").map((p)=>p.trim()).filter(Boolean);const out=[];for(const part of parts){const[rawName,rawType="string"]=part.split(":");const name=rawName?.trim();if(!name)continue;const type=TYPE_ALIASES[rawType.trim().toLowerCase()]??"string";out.push({name,type})}return out}function pluralize(word){if(!word)return word;const lower=word.toLowerCase();if(lower.endsWith("s")||lower.endsWith("x")||lower.endsWith("z")||lower.endsWith("ch")||lower.endsWith("sh"))return`${word}es`;if(lower.endsWith("y")&&!/[aeiou]y$/.test(lower))return`${word.slice(0,-1)}ies`;return`${word}s`}function pascalCase(name){return name.replace(/(^|[-_\s])(\w)/g,(_,__,c)=>String(c).toUpperCase())}function snakeCase(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()}function attributeBlock(fields){if(fields.length===0){return` title: { type: 'string', fillable: true, validation: { rule: schema.string().required() } },`}return fields.map((f)=>{const t=f.type;const rule=t==="number"?"schema.number()":t==="boolean"?"schema.boolean()":t==="date"?"schema.date()":t==="json"?"schema.object({})":"schema.string()";const dbType=t==="number"?"number":t==="boolean"?"boolean":t==="date"?"date":t==="json"?"json":"string";return` ${f.name}: { type: '${dbType}', fillable: true, validation: { rule: ${rule} } },`}).join(`
2
+ `)}function migrationColumns(fields){if(fields.length===0)return` .addColumn('title', 'varchar(255)', col => col.notNull())`;return fields.map((f)=>{switch(f.type){case"number":return` .addColumn('${f.name}', 'integer')`;case"boolean":return` .addColumn('${f.name}', 'boolean', col => col.defaultTo(false))`;case"text":return` .addColumn('${f.name}', 'text')`;case"date":return` .addColumn('${f.name}', 'timestamp')`;case"json":return` .addColumn('${f.name}', 'text')`;default:return` .addColumn('${f.name}', 'varchar(255)')`}}).join(`
3
3
  `)}function actionStub(name,kind,fields){const Model=pascalCase(name);switch(kind){case"Index":return`import { Action } from '@stacksjs/actions'
4
4
  import ${Model} from '~/app/Models/${Model}'
5
5
 
@@ -56,23 +56,23 @@ export default new Action({
56
56
  const deleted = await ${Model}.delete(id)
57
57
  return { deleted }
58
58
  },
59
- })`}}function modelStub(name,fields){return`import { defineModel } from '@stacksjs/orm'
59
+ })`}}function modelStub(name,fields){const Model=pascalCase(name);return`import { defineModel } from '@stacksjs/orm'
60
60
  import { schema } from '@stacksjs/validation/runtime'
61
61
 
62
62
  export default defineModel({
63
- name: '${pascalCase(name)}',
63
+ name: '${Model}',
64
64
  table: '${pluralize(snakeCase(name))}',
65
65
  attributes: {
66
66
  ${attributeBlock(fields)}
67
67
  },
68
68
  traits: { useTimestamps: true, useUuid: false },
69
69
  } as const)
70
- `}function migrationStub(name,fields){return`import type { Database } from '@stacksjs/database'
70
+ `}function migrationStub(name,fields){const table=pluralize(snakeCase(name));return`import type { Database } from '@stacksjs/database'
71
71
  import { sql } from '@stacksjs/database'
72
72
 
73
73
  export async function up(db: Database<any>) {
74
74
  await db.schema
75
- .createTable('${pluralize(snakeCase(name))}')
75
+ .createTable('${table}')
76
76
  .addColumn('id', 'serial', col => col.primaryKey())
77
77
  ${migrationColumns(fields)}
78
78
  .addColumn('created_at', 'timestamp', col => col.notNull().defaultTo(sql.raw('CURRENT_TIMESTAMP')))
@@ -83,4 +83,4 @@ ${migrationColumns(fields)}
83
83
  `);log.info(`[dry-run] would write ${path} (${lines.length} lines)`);process.stdout.write(`${lines.slice(0,60).map((l)=>` ${l}`).join(`
84
84
  `)}
85
85
 
86
- `);return}await writeTextFile({path,data:contents})}export async function scaffoldCrud(name,options){const Model=pascalCase(name);if(!Model)throw Error("scaffold:crud requires a non-empty resource name");const fields=parseFields(options.fields);log.info(`Scaffolding CRUD for ${italic(Model)} (${fields.length||"no"} fields)`);await writeFile(p.userModelsPath(`${Model}.ts`),modelStub(Model,fields));const migrationName=`${Date.now().toString()}-create-${pluralize(snakeCase(name))}-table.ts`;await writeFile(p.userMigrationsPath(migrationName),migrationStub(name,fields));for(const kind of["Index","Show","Store","Update","Destroy"])await writeFile(p.userActionsPath(`${Model}${kind}Action.ts`),actionStub(name,kind,fields));log.success(`CRUD scaffold complete: model + migration + 5 actions for ${Model}`);log.info(`Next: run \`buddy generate:types\`, then register \`route.resource('${pluralize(snakeCase(name))}', '${Model}')\` in routes/api.ts`)}
86
+ `);return}await writeTextFile({path,data:contents})}export async function scaffoldCrud(name,options){const Model=pascalCase(name);if(!Model){throw new Error("scaffold:crud requires a non-empty resource name")}const fields=parseFields(options.fields);log.info(`Scaffolding CRUD for ${italic(Model)} (${fields.length||"no"} fields)`);await writeFile(p.userModelsPath(`${Model}.ts`),modelStub(Model,fields));const ts=Date.now().toString();const migrationName=`${ts}-create-${pluralize(snakeCase(name))}-table.ts`;await writeFile(p.userMigrationsPath(migrationName),migrationStub(name,fields));for(const kind of["Index","Show","Store","Update","Destroy"]){await writeFile(p.userActionsPath(`${Model}${kind}Action.ts`),actionStub(name,kind,fields))}log.success(`CRUD scaffold complete: model + migration + 5 actions for ${Model}`);log.info("Next: run `buddy generate:types`, then register "+`\`route.resource('${pluralize(snakeCase(name))}', '${Model}')\` in routes/api.ts`)}
@@ -1 +1 @@
1
- import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{flushModelDocuments}from"@stacksjs/search-engine";import{prepareSearchModels}from"./bootstrap";await prepareSearchModels();const options=parseOptions(),modelOption=options.model,result=await flushModelDocuments(modelOption);if(result?.isErr){console.error(result.error);await log.error("Flushing search engine failed",result.error);await log.flush();process.exit(1)}await log.flush();process.exit(0);
1
+ import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{flushModelDocuments}from"@stacksjs/search-engine";import{prepareSearchModels}from"./bootstrap";await prepareSearchModels();const options=parseOptions();const modelOption=options.model;const result=await flushModelDocuments(modelOption);if(result?.isErr){console.error(result.error);await log.error("Flushing search engine failed",result.error);await log.flush();process.exit(1)}await log.flush();process.exit(0);
@@ -1 +1 @@
1
- import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{importModelDocuments}from"@stacksjs/search-engine";import{prepareSearchModels}from"./bootstrap";await prepareSearchModels();const options=parseOptions(),modelOption=options.model,result=await importModelDocuments(modelOption);if(result?.isErr){console.error(result.error);await log.error("Import to search engine failed",result.error);await log.flush();process.exit(1)}await log.flush();process.exit(0);
1
+ import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{importModelDocuments}from"@stacksjs/search-engine";import{prepareSearchModels}from"./bootstrap";await prepareSearchModels();const options=parseOptions();const modelOption=options.model;const result=await importModelDocuments(modelOption);if(result?.isErr){console.error(result.error);await log.error("Import to search engine failed",result.error);await log.flush();process.exit(1)}await log.flush();process.exit(0);
@@ -1 +1 @@
1
- import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{listIndexSettings}from"@stacksjs/search-engine";import{prepareSearchModels}from"./bootstrap";await prepareSearchModels();const options=parseOptions(),modelOption=options.model,result=await listIndexSettings(modelOption);if(result?.isErr){console.error(result.error);await log.error("Listing index settings failed",result.error);await log.flush();process.exit(1)}await log.flush();process.exit(0);
1
+ import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{listIndexSettings}from"@stacksjs/search-engine";import{prepareSearchModels}from"./bootstrap";await prepareSearchModels();const options=parseOptions();const modelOption=options.model;const result=await listIndexSettings(modelOption);if(result?.isErr){console.error(result.error);await log.error("Listing index settings failed",result.error);await log.flush();process.exit(1)}await log.flush();process.exit(0);
package/dist/seo.js CHANGED
@@ -1,4 +1,4 @@
1
- import{existsSync,readFileSync,statSync}from"node:fs";import{join}from"node:path";import{generateRobotsTxt,generateSitemap,scanForSitemapEntries}from"@stacksjs/stx/seo";import{usableOrigin}from"./site-origin";export const NON_PAGE_DIRS=["components","layouts","partials","emails"],DEFAULT_ROBOTS_DISALLOW=["/api/"];function withoutComments(source){return source.replace(/<!--[\s\S]*?-->/g,"").replace(/\{\{--[\s\S]*?--\}\}/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:\\'"`])\/\/[^\n]*/g,"$1")}export function declaresNoindex(source){const code=withoutComments(source);for(const tag of code.match(/<meta\b[^>]*>/gi)??[])if(/\bname\s*=\s*["']?(?:robots|googlebot)\b/i.test(tag)&&/\bcontent\s*=\s*["'][^"']*\bnoindex\b/i.test(tag))return!0;if(/\brobots\s*:\s*(["'`])[^"'`]*\bnoindex\b/i.test(code))return!0;if(/\b(?:const|let|var)\s+noindex\s*(?::\s*boolean\s*)?=\s*true\b/.test(code))return!0;if(/\bsitemap\s*:\s*false\b/.test(code))return!0;return!1}export function requiresAuth(source){const match=withoutComments(source).match(/\bmiddleware\s*:\s*(\[[^\]]*\]|["'][^"']*["'])/);return!!match&&/["']auth["']/.test(match[1])}export function isErrorViewPath(path){const segments=path.split("/").filter(Boolean),last=segments.at(-1)??"";return segments.includes("errors")||/^(?:\d{3}|error|coming-soon|maintenance)$/.test(last)}export function isNonPagePath(path){const segments=path.split("/").filter(Boolean);return segments.slice(0,-1).some((segment)=>NON_PAGE_DIRS.includes(segment))||segments.some((segment)=>segment.startsWith("_")||segment.startsWith("."))}export function isDynamicPath(path){return/\[[^\]]*\]/.test(path)}export function pathMatchesExclude(path,pattern){if(!pattern)return!1;if(pattern.endsWith("*")){const prefix=pattern.slice(0,-1);return path.startsWith(prefix)||`${path}/`===prefix}if(pattern.endsWith("/")&&pattern!=="/")return path.startsWith(pattern)||`${path}/`===pattern;return path===pattern||pattern!=="/"&&path===pattern.replace(/\/+$/,"")}function longestRobotsMatch(path,rules){let best=-1;for(const rule of rules){if(!rule)continue;const anchored=rule.endsWith("$"),pattern=(anchored?rule.slice(0,-1):rule).split("*").map((part)=>part.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");if(new RegExp(`^${pattern}${anchored?"$":""}`).test(path))best=Math.max(best,rule.length)}return best}export function isDisallowedByRobots(path,group){const disallow=longestRobotsMatch(path,group.disallow??[]);return disallow>=0&&disallow>longestRobotsMatch(path,group.allow??[])}function sitemapOptions(seo){if(seo?.sitemap===!1)return;return seo?.sitemap??{}}function robotsOptions(seo){if(seo?.robots===!1)return;return seo?.robots??{}}export function robotsDefaultGroup(seo){const disallow=[...new Set([...DEFAULT_ROBOTS_DISALLOW,...robotsOptions(seo)?.disallow??[]])];return{userAgent:"*",allow:["/"],disallow}}export function resolveSeoOrigin(options){const configured=usableOrigin(options.seo?.origin)||usableOrigin(options.appUrl);if(configured)return configured;if(!options.request)return"";const url=new URL(options.request.url),host=options.request.headers.get("x-forwarded-host")?.split(",")[0]?.trim()||url.host;return`${options.request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()||url.protocol.replace(":","")}://${host}`}export function buildRobotsTxt(options){const robots=robotsOptions(options.seo),rules=[robotsDefaultGroup(options.seo),...robots?.rules??[]];return`# Generated by Stacks from resources/views and config/app.ts (seo).
2
- ${generateRobotsTxt({rules,...sitemapOptions(options.seo)&&options.origin&&{sitemap:`${options.origin}/sitemap.xml`}})}
3
- `}function toEntry(value){return typeof value==="string"?{loc:value}:value}export function locPath(loc){if(!/^https?:\/\//i.test(loc))return loc.startsWith("/")?loc:`/${loc}`;try{return new URL(loc).pathname}catch{return loc}}export function sitemapLocs(xml){return[...xml.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/gi)].map((match)=>match[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'"))}function viewFileFor(viewsDir,path){const rel=path==="/"?"index":path.replace(/^\//,"");for(const candidate of[`${rel}.stx`,`${rel}/index.stx`]){const file=join(viewsDir,candidate);if(existsSync(file))return file}return}export async function scanViewSitemapEntries(viewsDir,seo){const result={entries:[],skipped:[]};if(!existsSync(viewsDir))return result;const scanned=await scanForSitemapEntries(viewsDir,{baseUrl:"",extensions:[".stx"],ignore:["node_modules"]}),exclude=sitemapOptions(seo)?.exclude??[],robotsGroup=robotsOptions(seo)?robotsDefaultGroup(seo):void 0,seen=new Set;for(const entry of scanned){const path=entry.loc;if(seen.has(path))continue;seen.add(path);const skip=(reason)=>{result.skipped.push({path,reason})};if(isNonPagePath(path)){skip("non-page");continue}if(isDynamicPath(path)){skip("dynamic");continue}if(isErrorViewPath(path)){skip("error-page");continue}if(exclude.some((pattern)=>pathMatchesExclude(path,pattern))){skip("excluded");continue}if(robotsGroup&&isDisallowedByRobots(path,robotsGroup)){skip("disallowed");continue}const file=viewFileFor(viewsDir,path),source=file?readFileSync(file,"utf8"):"";if(declaresNoindex(source)){skip("noindex");continue}if(requiresAuth(source)){skip("auth");continue}result.entries.push({loc:path,...entry.lastmod&&{lastmod:entry.lastmod},priority:path==="/"?1:0.5})}return result}async function blogEntries(root){const contentDir=join(root,"content/blog");if(existsSync(contentDir))try{const{blogSitemapPaths}=await import("./blog"),paths=blogSitemapPaths(contentDir);if(paths.length>0)return paths.map((loc)=>({loc,priority:loc==="/blog"?0.7:0.6}))}catch{}const built=join(root,"dist/blog/sitemap.xml");if(existsSync(built))try{return sitemapLocs(readFileSync(built,"utf8")).map((loc)=>({loc:locPath(loc),priority:0.6}))}catch{}return[]}export async function collectSitemapEntries(inputs){const options=sitemapOptions(inputs.seo);if(!options)return[];const views=await scanViewSitemapEntries(join(inputs.root,"resources/views"),inputs.seo),configured=[...options.include??[]];if(options.entries&&!inputs.skipDynamicEntries)try{configured.push(...await options.entries())}catch(error){console.warn(`[seo] seo.sitemap.entries() failed; serving the sitemap without them: ${error.message}`)}const exclude=options.exclude??[],robotsGroup=robotsOptions(inputs.seo)?robotsDefaultGroup(inputs.seo):void 0,admits=(path)=>!exclude.some((pattern)=>pathMatchesExclude(path,pattern))&&!(robotsGroup&&isDisallowedByRobots(path,robotsGroup)),byPath=new Map;for(const entry of views.entries)byPath.set(entry.loc,entry);for(const entry of await blogEntries(inputs.root)){const path=locPath(entry.loc);if(!byPath.has(path)&&admits(path))byPath.set(path,entry)}for(const raw of configured){const entry=toEntry(raw),path=locPath(entry.loc);if(admits(path))byPath.set(path,{...byPath.get(path),...entry})}const entries=[...byPath.values()].sort((a,b)=>locPath(a.loc).localeCompare(locPath(b.loc)));return withAlternates(entries,options)}function withAlternates(entries,options){const hook=options.alternates;if(!hook)return entries;try{return entries.map((entry)=>{if(entry.alternates)return entry;const alternates=hook(locPath(entry.loc));return alternates?.length?{...entry,alternates}:entry})}catch(error){console.warn(`[seo] seo.sitemap.alternates() failed; serving the sitemap without language alternates: ${error.message}`);return entries}}export async function buildSitemapXml(inputs){const entries=await collectSitemapEntries(inputs);return`${generateSitemap(entries,{baseUrl:inputs.origin,includeLastmod:!1})}
4
- `}export function pathsMissingFromSitemap(handwrittenXml,generated){const listed=new Set(sitemapLocs(handwrittenXml).map((loc)=>locPath(loc).replace(/(.)\/+$/,"$1")));return generated.map((entry)=>locPath(entry.loc)).filter((path)=>!listed.has(path))}export function seoFileFor(req){if(req.method!=="GET"&&req.method!=="HEAD")return;const{pathname}=new URL(req.url);if(pathname==="/sitemap.xml")return"sitemap.xml";if(pathname==="/robots.txt")return"robots.txt";return}export function createSiteSeoHandler(options={}){const root=options.root??process.cwd(),ttl=options.cacheTtlMs??0,cache=new Map;return async(req)=>{const file=seoFileFor(req);if(!file)return null;const seo=options.seo;if(file==="sitemap.xml"&&!sitemapOptions(seo))return null;if(file==="robots.txt"&&!robotsOptions(seo))return null;if((seo?.handwritten??"prefer")==="prefer"&&existsSync(join(root,"public",file)))return null;const origin=resolveSeoOrigin({seo,appUrl:options.appUrl,request:req}),key=`${file} ${origin}`,cached=cache.get(key);let body=cached&&Date.now()-cached.at<ttl?cached.body:void 0;if(body===void 0){body=file==="sitemap.xml"?await buildSitemapXml({root,seo,origin}):buildRobotsTxt({seo,origin});if(ttl>0)cache.set(key,{at:Date.now(),body})}return new Response(req.method==="HEAD"?null:body,{headers:{"Content-Type":file==="sitemap.xml"?"application/xml; charset=utf-8":"text/plain; charset=utf-8","Cache-Control":ttl>0?"public, max-age=3600":"no-cache"}})}}export async function describeSeoAtBoot(options={}){const root=options.root??process.cwd(),seo=options.seo;if((seo?.handwritten??"prefer")!=="prefer")return[];const notes=[],sitemapFile=join(root,"public/sitemap.xml");if(sitemapOptions(seo)&&existsSync(sitemapFile)&&statSync(sitemapFile).isFile()){const generated=await collectSitemapEntries({root,seo,origin:"",skipDynamicEntries:!0}),missing=pathsMissingFromSitemap(readFileSync(sitemapFile,"utf8"),generated);if(missing.length>0)notes.push(`public/sitemap.xml is hand-written and does not list ${missing.length} page${missing.length===1?"":"s"} Stacks would: ${missing.slice(0,8).join(", ")}${missing.length>8?", ...":""}. Delete it to serve the generated /sitemap.xml, or set app.seo.handwritten to 'replace'.`)}const robotsFile=join(root,"public/robots.txt");if(robotsOptions(seo)&&existsSync(robotsFile)&&statSync(robotsFile).isFile()){if(!/^\s*sitemap\s*:/im.test(readFileSync(robotsFile,"utf8")))notes.push("public/robots.txt is hand-written and names no Sitemap. Delete it to serve the generated /robots.txt, which does.")}return notes}
1
+ import{existsSync,readFileSync,statSync}from"node:fs";import{join}from"node:path";import{generateRobotsTxt,generateSitemap,scanForSitemapEntries}from"@stacksjs/stx/seo";import{usableOrigin}from"./site-origin";export const NON_PAGE_DIRS=["components","layouts","partials","emails"];export const DEFAULT_ROBOTS_DISALLOW=["/api/"];function withoutComments(source){return source.replace(/<!--[\s\S]*?-->/g,"").replace(/\{\{--[\s\S]*?--\}\}/g,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:\\'"`])\/\/[^\n]*/g,"$1")}export function declaresNoindex(source){const code=withoutComments(source);for(const tag of code.match(/<meta\b[^>]*>/gi)??[]){if(/\bname\s*=\s*["']?(?:robots|googlebot)\b/i.test(tag)&&/\bcontent\s*=\s*["'][^"']*\bnoindex\b/i.test(tag))return true}if(/\brobots\s*:\s*(["'`])[^"'`]*\bnoindex\b/i.test(code))return true;if(/\b(?:const|let|var)\s+noindex\s*(?::\s*boolean\s*)?=\s*true\b/.test(code))return true;if(/\bsitemap\s*:\s*false\b/.test(code))return true;return false}export function requiresAuth(source){const code=withoutComments(source);const match=code.match(/\bmiddleware\s*:\s*(\[[^\]]*\]|["'][^"']*["'])/);return!!match&&/["']auth["']/.test(match[1])}export function isErrorViewPath(path){const segments=path.split("/").filter(Boolean);const last=segments.at(-1)??"";return segments.includes("errors")||/^(?:\d{3}|error|coming-soon|maintenance)$/.test(last)}export function isNonPagePath(path){const segments=path.split("/").filter(Boolean);return segments.slice(0,-1).some((segment)=>NON_PAGE_DIRS.includes(segment))||segments.some((segment)=>segment.startsWith("_")||segment.startsWith("."))}export function isDynamicPath(path){return/\[[^\]]*\]/.test(path)}export function pathMatchesExclude(path,pattern){if(!pattern)return false;if(pattern.endsWith("*")){const prefix=pattern.slice(0,-1);return path.startsWith(prefix)||`${path}/`===prefix}if(pattern.endsWith("/")&&pattern!=="/")return path.startsWith(pattern)||`${path}/`===pattern;return path===pattern||pattern!=="/"&&path===pattern.replace(/\/+$/,"")}function longestRobotsMatch(path,rules){let best=-1;for(const rule of rules){if(!rule)continue;const anchored=rule.endsWith("$");const body=anchored?rule.slice(0,-1):rule;const pattern=body.split("*").map((part)=>part.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");if(new RegExp(`^${pattern}${anchored?"$":""}`).test(path))best=Math.max(best,rule.length)}return best}export function isDisallowedByRobots(path,group){const disallow=longestRobotsMatch(path,group.disallow??[]);return disallow>=0&&disallow>longestRobotsMatch(path,group.allow??[])}function sitemapOptions(seo){if(seo?.sitemap===false)return;return seo?.sitemap??{}}function robotsOptions(seo){if(seo?.robots===false)return;return seo?.robots??{}}export function robotsDefaultGroup(seo){const disallow=[...new Set([...DEFAULT_ROBOTS_DISALLOW,...robotsOptions(seo)?.disallow??[]])];return{userAgent:"*",allow:["/"],disallow}}export function resolveSeoOrigin(options){const configured=usableOrigin(options.seo?.origin)||usableOrigin(options.appUrl);if(configured)return configured;if(!options.request)return"";const url=new URL(options.request.url);const host=options.request.headers.get("x-forwarded-host")?.split(",")[0]?.trim()||url.host;const proto=options.request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()||url.protocol.replace(":","");return`${proto}://${host}`}export function buildRobotsTxt(options){const robots=robotsOptions(options.seo);const rules=[robotsDefaultGroup(options.seo),...robots?.rules??[]];const body=generateRobotsTxt({rules,...sitemapOptions(options.seo)&&options.origin&&{sitemap:`${options.origin}/sitemap.xml`}});return`# Generated by Stacks from resources/views and config/app.ts (seo).
2
+ ${body}
3
+ `}function toEntry(value){return typeof value==="string"?{loc:value}:value}export function locPath(loc){if(!/^https?:\/\//i.test(loc))return loc.startsWith("/")?loc:`/${loc}`;try{return new URL(loc).pathname}catch{return loc}}export function sitemapLocs(xml){return[...xml.matchAll(/<loc>\s*([^<]+?)\s*<\/loc>/gi)].map((match)=>match[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'"))}function viewFileFor(viewsDir,path){const rel=path==="/"?"index":path.replace(/^\//,"");for(const candidate of[`${rel}.stx`,`${rel}/index.stx`]){const file=join(viewsDir,candidate);if(existsSync(file))return file}return}export async function scanViewSitemapEntries(viewsDir,seo){const result={entries:[],skipped:[]};if(!existsSync(viewsDir))return result;const scanned=await scanForSitemapEntries(viewsDir,{baseUrl:"",extensions:[".stx"],ignore:["node_modules"]});const exclude=sitemapOptions(seo)?.exclude??[];const robotsGroup=robotsOptions(seo)?robotsDefaultGroup(seo):undefined;const seen=new Set;for(const entry of scanned){const path=entry.loc;if(seen.has(path))continue;seen.add(path);const skip=(reason)=>{result.skipped.push({path,reason})};if(isNonPagePath(path)){skip("non-page");continue}if(isDynamicPath(path)){skip("dynamic");continue}if(isErrorViewPath(path)){skip("error-page");continue}if(exclude.some((pattern)=>pathMatchesExclude(path,pattern))){skip("excluded");continue}if(robotsGroup&&isDisallowedByRobots(path,robotsGroup)){skip("disallowed");continue}const file=viewFileFor(viewsDir,path);const source=file?readFileSync(file,"utf8"):"";if(declaresNoindex(source)){skip("noindex");continue}if(requiresAuth(source)){skip("auth");continue}result.entries.push({loc:path,...entry.lastmod&&{lastmod:entry.lastmod},priority:path==="/"?1:0.5})}return result}async function blogEntries(root){const contentDir=join(root,"content/blog");if(existsSync(contentDir)){try{const{blogSitemapPaths}=await import("./blog");const paths=blogSitemapPaths(contentDir);if(paths.length>0)return paths.map((loc)=>({loc,priority:loc==="/blog"?0.7:0.6}))}catch{}}const built=join(root,"dist/blog/sitemap.xml");if(existsSync(built)){try{return sitemapLocs(readFileSync(built,"utf8")).map((loc)=>({loc:locPath(loc),priority:0.6}))}catch{}}return[]}export async function collectSitemapEntries(inputs){const options=sitemapOptions(inputs.seo);if(!options)return[];const views=await scanViewSitemapEntries(join(inputs.root,"resources/views"),inputs.seo);const configured=[...options.include??[]];if(options.entries&&!inputs.skipDynamicEntries){try{configured.push(...await options.entries())}catch(error){console.warn(`[seo] seo.sitemap.entries() failed; serving the sitemap without them: ${error.message}`)}}const exclude=options.exclude??[];const robotsGroup=robotsOptions(inputs.seo)?robotsDefaultGroup(inputs.seo):undefined;const admits=(path)=>!exclude.some((pattern)=>pathMatchesExclude(path,pattern))&&!(robotsGroup&&isDisallowedByRobots(path,robotsGroup));const byPath=new Map;for(const entry of views.entries)byPath.set(entry.loc,entry);for(const entry of await blogEntries(inputs.root)){const path=locPath(entry.loc);if(!byPath.has(path)&&admits(path))byPath.set(path,entry)}for(const raw of configured){const entry=toEntry(raw);const path=locPath(entry.loc);if(admits(path))byPath.set(path,{...byPath.get(path),...entry})}const entries=[...byPath.values()].sort((a,b)=>locPath(a.loc).localeCompare(locPath(b.loc)));return withAlternates(entries,options)}function withAlternates(entries,options){const hook=options.alternates;if(!hook)return entries;try{return entries.map((entry)=>{if(entry.alternates)return entry;const alternates=hook(locPath(entry.loc));return alternates?.length?{...entry,alternates}:entry})}catch(error){console.warn(`[seo] seo.sitemap.alternates() failed; serving the sitemap without language alternates: ${error.message}`);return entries}}export async function buildSitemapXml(inputs){const entries=await collectSitemapEntries(inputs);return`${generateSitemap(entries,{baseUrl:inputs.origin,includeLastmod:false})}
4
+ `}export function pathsMissingFromSitemap(handwrittenXml,generated){const listed=new Set(sitemapLocs(handwrittenXml).map((loc)=>locPath(loc).replace(/(.)\/+$/,"$1")));return generated.map((entry)=>locPath(entry.loc)).filter((path)=>!listed.has(path))}export function seoFileFor(req){if(req.method!=="GET"&&req.method!=="HEAD")return;const{pathname}=new URL(req.url);if(pathname==="/sitemap.xml")return"sitemap.xml";if(pathname==="/robots.txt")return"robots.txt";return}export function createSiteSeoHandler(options={}){const root=options.root??process.cwd();const ttl=options.cacheTtlMs??0;const cache=new Map;return async(req)=>{const file=seoFileFor(req);if(!file)return null;const seo=options.seo;if(file==="sitemap.xml"&&!sitemapOptions(seo))return null;if(file==="robots.txt"&&!robotsOptions(seo))return null;if((seo?.handwritten??"prefer")==="prefer"&&existsSync(join(root,"public",file)))return null;const origin=resolveSeoOrigin({seo,appUrl:options.appUrl,request:req});const key=`${file} ${origin}`;const cached=cache.get(key);let body=cached&&Date.now()-cached.at<ttl?cached.body:undefined;if(body===undefined){body=file==="sitemap.xml"?await buildSitemapXml({root,seo,origin}):buildRobotsTxt({seo,origin});if(ttl>0)cache.set(key,{at:Date.now(),body})}return new Response(req.method==="HEAD"?null:body,{headers:{"Content-Type":file==="sitemap.xml"?"application/xml; charset=utf-8":"text/plain; charset=utf-8","Cache-Control":ttl>0?"public, max-age=3600":"no-cache"}})}}export async function describeSeoAtBoot(options={}){const root=options.root??process.cwd();const seo=options.seo;if((seo?.handwritten??"prefer")!=="prefer")return[];const notes=[];const sitemapFile=join(root,"public/sitemap.xml");if(sitemapOptions(seo)&&existsSync(sitemapFile)&&statSync(sitemapFile).isFile()){const generated=await collectSitemapEntries({root,seo,origin:"",skipDynamicEntries:true});const missing=pathsMissingFromSitemap(readFileSync(sitemapFile,"utf8"),generated);if(missing.length>0){notes.push(`public/sitemap.xml is hand-written and does not list ${missing.length} page${missing.length===1?"":"s"} Stacks would: ${missing.slice(0,8).join(", ")}${missing.length>8?", ...":""}. Delete it to serve the generated /sitemap.xml, or set app.seo.handwritten to 'replace'.`)}}const robotsFile=join(root,"public/robots.txt");if(robotsOptions(seo)&&existsSync(robotsFile)&&statSync(robotsFile).isFile()){if(!/^\s*sitemap\s*:/im.test(readFileSync(robotsFile,"utf8")))notes.push("public/robots.txt is hand-written and names no Sitemap. Delete it to serve the generated /robots.txt, which does.")}return notes}
package/dist/serve/api.js CHANGED
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{config,overridesReady}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{appPath,frameworkPath}from"@stacksjs/path";import{disableViewRouting,route}from"@stacksjs/router";import{serverRequestBodyOptions}from"@stacksjs/server/request-body";import{ensureDiscoveredPackages}from"../discover-packages";import{resolveApiHost}from"../helpers/api-host";import{shutDownApiServer}from"../helpers/api-shutdown";function resolveDefaultsFile(rel){if(rel.startsWith("app/")){const published=appPath(rel.slice(4));if(existsSync(published))return published}const vendored=frameworkPath(`defaults/${rel}`);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return join(dirname(pkgJson),rel)}catch{return vendored}}await overridesReady;const port=Number(process.env.PORT)||config.ports?.api||3008,hostname=resolveApiHost();log.info("[Stacks API] Starting server...");log.info(`[Stacks API] Environment: ${process.env.APP_ENV||"development"}`);const corsMod=await import(resolveDefaultsFile("app/Middleware/Cors.ts")),corsMiddleware=corsMod.default;route.use(corsMiddleware.toRouterHandler());await ensureDiscoveredPackages();const{reportStripeAvailability}=await import("@stacksjs/payments");reportStripeAvailability();const{autoImportsAreStale,generateAutoImportFiles,injectGlobalAutoImports,warnShadowedSecurityDefaults}=await import("@stacksjs/server");try{if(autoImportsAreStale()){log.info("[Stacks API] Installed packages moved since the auto-import barrel was written; rebuilding it.");await generateAutoImportFiles({declarations:!1})}}catch(error){log.warn(`[Stacks API] Could not refresh the auto-import barrel: ${error instanceof Error?error.message:String(error)}`)}await injectGlobalAutoImports();warnShadowedSecurityDefaults();await route.importRoutes();try{const{describeUnforwardableRoutes,resolveApiProxyRules,unforwardableRoutes}=await import("@stacksjs/server"),{listRedirectRoutes,listRootMountedAppRoutes}=await import("@stacksjs/router"),redirected=new Set(listRedirectRoutes().map((entry)=>entry.path)),unreachable=unforwardableRoutes(listRootMountedAppRoutes().filter((entry)=>(entry.method==="GET"||entry.method==="HEAD")&&!redirected.has(entry.path)),resolveApiProxyRules(config.server?.proxy));if(unreachable.length>0)log.warn(describeUnforwardableRoutes(unreachable))}catch(error){log.debug(`[Stacks API] Route reachability check skipped: ${error instanceof Error?error.message:String(error)}`)}disableViewRouting(route.bunRouter);const isDeployed=["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase()),server=await route.serve({...serverRequestBodyOptions(config.server?.maxRequestBodySize),port,hostname,reusePort:isDeployed});process.on("SIGTERM",()=>{shutDownApiServer(server,{graceMs:Number(process.env.SHUTDOWN_GRACE_MS)||15000,exit:(code)=>process.exit(code)})});log.info(`[Stacks API] Server running at http://${hostname}:${port}`);
1
+ import{existsSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{config,overridesReady}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{appPath,frameworkPath}from"@stacksjs/path";import{disableViewRouting,route}from"@stacksjs/router";import{serverRequestBodyOptions}from"@stacksjs/server/request-body";import{ensureDiscoveredPackages}from"../discover-packages";import{resolveApiHost}from"../helpers/api-host";import{shutDownApiServer}from"../helpers/api-shutdown";function resolveDefaultsFile(rel){if(rel.startsWith("app/")){const published=appPath(rel.slice("app/".length));if(existsSync(published))return published}const vendored=frameworkPath(`defaults/${rel}`);if(existsSync(vendored))return vendored;try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());return join(dirname(pkgJson),rel)}catch{return vendored}}await overridesReady;const port=Number(process.env.PORT)||config.ports?.api||3008;const hostname=resolveApiHost();log.info(`[Stacks API] Starting server...`);log.info(`[Stacks API] Environment: ${process.env.APP_ENV||"development"}`);const corsMod=await import(resolveDefaultsFile("app/Middleware/Cors.ts"));const corsMiddleware=corsMod.default;route.use(corsMiddleware.toRouterHandler());await ensureDiscoveredPackages();const{reportStripeAvailability}=await import("@stacksjs/payments");reportStripeAvailability();const{autoImportsAreStale,generateAutoImportFiles,injectGlobalAutoImports,warnShadowedSecurityDefaults}=await import("@stacksjs/server");try{if(autoImportsAreStale()){log.info("[Stacks API] Installed packages moved since the auto-import barrel was written; rebuilding it.");await generateAutoImportFiles({declarations:false})}}catch(error){log.warn(`[Stacks API] Could not refresh the auto-import barrel: ${error instanceof Error?error.message:String(error)}`)}await injectGlobalAutoImports();warnShadowedSecurityDefaults();await route.importRoutes();try{const{describeUnforwardableRoutes,resolveApiProxyRules,unforwardableRoutes}=await import("@stacksjs/server");const{listRedirectRoutes,listRootMountedAppRoutes}=await import("@stacksjs/router");const redirected=new Set(listRedirectRoutes().map((entry)=>entry.path));const unreachable=unforwardableRoutes(listRootMountedAppRoutes().filter((entry)=>(entry.method==="GET"||entry.method==="HEAD")&&!redirected.has(entry.path)),resolveApiProxyRules(config.server?.proxy));if(unreachable.length>0)log.warn(describeUnforwardableRoutes(unreachable))}catch(error){log.debug(`[Stacks API] Route reachability check skipped: ${error instanceof Error?error.message:String(error)}`)}disableViewRouting(route.bunRouter);const isDeployed=["production","staging","development"].includes((process.env.APP_ENV||"").toLowerCase());const server=await route.serve({...serverRequestBodyOptions(config.server?.maxRequestBodySize),port,hostname,reusePort:isDeployed});process.on("SIGTERM",()=>{shutDownApiServer(server,{graceMs:Number(process.env.SHUTDOWN_GRACE_MS)||15000,exit:(code)=>process.exit(code)})});log.info(`[Stacks API] Server running at http://${hostname}:${port}`);
@@ -1 +1 @@
1
- const DEFAULT_PUBLIC_PATHS=["/login","/health"];export function isAssetPath(pathname){if(pathname.startsWith("/_stx/")||pathname.startsWith("/@"))return!0;return pathname.slice(pathname.lastIndexOf("/")+1).includes(".")}export function isDelegatedRequest(method,pathname){if(pathname==="/api"||pathname.startsWith("/api/"))return!0;return method!=="GET"&&method!=="HEAD"}export async function decideDashboardAccess(request,validate,options={}){const publicPaths=options.publicPaths??DEFAULT_PUBLIC_PATHS;if(isDelegatedRequest(request.method,request.pathname))return{allow:!0,reason:"delegated"};if(isAssetPath(request.pathname))return{allow:!0,reason:"asset"};const pathname=request.pathname.length>1?request.pathname.replace(/\/+$/,""):request.pathname;if(publicPaths.includes(pathname))return{allow:!0,reason:"public-page"};if(!request.token)return{allow:!1,reason:"no-session"};try{if(await validate(request.token))return{allow:!0,reason:"authenticated"}}catch{}return{allow:!1,reason:"invalid-session"}}
1
+ const DEFAULT_PUBLIC_PATHS=["/login","/health"];export function isAssetPath(pathname){if(pathname.startsWith("/_stx/")||pathname.startsWith("/@"))return true;const last=pathname.slice(pathname.lastIndexOf("/")+1);return last.includes(".")}export function isDelegatedRequest(method,pathname){if(pathname==="/api"||pathname.startsWith("/api/"))return true;return method!=="GET"&&method!=="HEAD"}export async function decideDashboardAccess(request,validate,options={}){const publicPaths=options.publicPaths??DEFAULT_PUBLIC_PATHS;if(isDelegatedRequest(request.method,request.pathname))return{allow:true,reason:"delegated"};if(isAssetPath(request.pathname))return{allow:true,reason:"asset"};const pathname=request.pathname.length>1?request.pathname.replace(/\/+$/,""):request.pathname;if(publicPaths.includes(pathname))return{allow:true,reason:"public-page"};if(!request.token)return{allow:false,reason:"no-session"};try{const user=await validate(request.token);if(user)return{allow:true,reason:"authenticated"}}catch{}return{allow:false,reason:"invalid-session"}}
@@ -1 +1 @@
1
- import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{projectPath,publicPath}from"@stacksjs/path";import{resolveComponentsLibraryRoot,resolveDefaultsRoot}from"../dev/defaults-resources";import{decideDashboardAccess}from"./dashboard-gate";process.env.APP_ENV||="production";process.env.NODE_ENV||="production";const port=Number(process.env.PORT_DASHBOARD||process.env.PORT)||3002,defaultsRoot=resolveDefaultsRoot(),frameworkDashboard=join(defaultsRoot,"views/dashboard"),appDashboard=projectPath("resources/views/dashboard"),{authCookieName}=await import("@stacksjs/auth"),authCookie=authCookieName();function readCookie(header,name){if(!header)return;for(const part of header.split(";")){const raw=part.trim(),eq=raw.indexOf("=");if(eq<1)continue;if(raw.slice(0,eq)===name)return decodeURIComponent(raw.slice(eq+1))}return}const{isApiBoundRequest,proxyToBackend,resolveApiBase,resolveApiProxyRules,viewClientAddress}=await import("@stacksjs/server"),apiBase=resolveApiBase(config.ports?.api),apiProxyRules=resolveApiProxyRules(config.server?.proxy),{Auth}=await import("@stacksjs/auth"),{registerPeerSource}=await import("@stacksjs/router"),{serve}=await import("bun-plugin-stx/serve");await serve({patterns:[appDashboard,frameworkDashboard].filter((dir)=>existsSync(dir)),port,layoutsDir:join(appDashboard,"layouts"),fallbackLayoutsDir:join(frameworkDashboard,"layouts"),partialsDir:frameworkDashboard,componentsDir:projectPath("resources/components/Dashboard"),additionalComponentsDirs:[join(defaultsRoot,"resources/components/Dashboard")],fallbackComponentsDir:resolveComponentsLibraryRoot(),publicDir:publicPath(),quiet:!0,clientAddress:viewClientAddress,onRequest:async(req,server)=>{registerPeerSource(server);const url=new URL(req.url);if((await decideDashboardAccess({method:req.method,pathname:url.pathname,token:readCookie(req.headers.get("cookie"),authCookie)},(token)=>Auth.getUserFromToken(token))).allow){if(isApiBoundRequest(req,url.pathname,apiProxyRules)){if(!apiBase){log.error(`No API target configured for ${url.pathname}. This dashboard 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.`);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})}}return null}const next=encodeURIComponent(url.pathname+url.search);return new Response(null,{status:302,headers:{location:`/login?next=${next}`,"cache-control":"no-store, private"}})}});console.log(`Dashboard server listening on port ${port}`);
1
+ import{existsSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{projectPath,publicPath}from"@stacksjs/path";import{resolveComponentsLibraryRoot,resolveDefaultsRoot}from"../dev/defaults-resources";import{decideDashboardAccess}from"./dashboard-gate";process.env.APP_ENV||="production";process.env.NODE_ENV||="production";const port=Number(process.env.PORT_DASHBOARD||process.env.PORT)||3002;const defaultsRoot=resolveDefaultsRoot();const frameworkDashboard=join(defaultsRoot,"views/dashboard");const appDashboard=projectPath("resources/views/dashboard");const{authCookieName}=await import("@stacksjs/auth");const authCookie=authCookieName();function readCookie(header,name){if(!header)return;for(const part of header.split(";")){const raw=part.trim();const eq=raw.indexOf("=");if(eq<1)continue;if(raw.slice(0,eq)===name)return decodeURIComponent(raw.slice(eq+1))}return}const{isApiBoundRequest,proxyToBackend,resolveApiBase,resolveApiProxyRules,viewClientAddress}=await import("@stacksjs/server");const apiBase=resolveApiBase(config.ports?.api);const apiProxyRules=resolveApiProxyRules(config.server?.proxy);const{Auth}=await import("@stacksjs/auth");const{registerPeerSource}=await import("@stacksjs/router");const{serve}=await import("bun-plugin-stx/serve");await serve({patterns:[appDashboard,frameworkDashboard].filter((dir)=>existsSync(dir)),port,layoutsDir:join(appDashboard,"layouts"),fallbackLayoutsDir:join(frameworkDashboard,"layouts"),partialsDir:frameworkDashboard,componentsDir:projectPath("resources/components/Dashboard"),additionalComponentsDirs:[join(defaultsRoot,"resources/components/Dashboard")],fallbackComponentsDir:resolveComponentsLibraryRoot(),publicDir:publicPath(),quiet:true,clientAddress:viewClientAddress,onRequest:async(req,server)=>{registerPeerSource(server);const url=new URL(req.url);const decision=await decideDashboardAccess({method:req.method,pathname:url.pathname,token:readCookie(req.headers.get("cookie"),authCookie)},(token)=>Auth.getUserFromToken(token));if(decision.allow){if(isApiBoundRequest(req,url.pathname,apiProxyRules)){if(!apiBase){log.error(`No API target configured for ${url.pathname}. This dashboard 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.`);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})}}return null}const next=encodeURIComponent(url.pathname+url.search);return new Response(null,{status:302,headers:{location:`/login?next=${next}`,"cache-control":"no-store, private"}})}});console.log(`Dashboard server listening on port ${port}`);
package/dist/setup/ssl.js CHANGED
@@ -1,5 +1,5 @@
1
- import{execSync,spawn}from"node:child_process";import fs from"node:fs";import os from"node:os";import path from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";const HOSTS_FILE=process.platform==="win32"?path.join(process.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",SSL_DIR=path.join(os.homedir(),".stacks","ssl");function isInteractiveTerminal(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function getSudoPassword(){return process.env.SUDO_PASSWORD}function canRunSudo(){return isInteractiveTerminal()||!!getSudoPassword()}export function isDomainInHosts(domain){try{const hostsContent=fs.readFileSync(HOSTS_FILE,"utf-8");return hostsContent.includes(`127.0.0.1 ${domain}`)||hostsContent.includes(`::1 ${domain}`)}catch{if(process.platform!=="win32"){const sudoPassword=getSudoPassword();if(sudoPassword)try{const result=execSync(`echo '${sudoPassword}' | sudo -S cat "${HOSTS_FILE}" 2>/dev/null`,{encoding:"utf-8"});return result.includes(`127.0.0.1 ${domain}`)||result.includes(`::1 ${domain}`)}catch{return!1}}return!1}}export async function addDomainToHosts(domain,verbose){if(isDomainInHosts(domain)){if(verbose)log.info(`${domain} already in hosts file`);return!0}const hostsEntry=`
1
+ import{execSync,spawn}from"node:child_process";import fs from"node:fs";import os from"node:os";import path from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";const HOSTS_FILE=process.platform==="win32"?path.join(process.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts";const SSL_DIR=path.join(os.homedir(),".stacks","ssl");function isInteractiveTerminal(){return process.stdin.isTTY===true&&process.stdout.isTTY===true}function getSudoPassword(){return process.env.SUDO_PASSWORD}function canRunSudo(){return isInteractiveTerminal()||!!getSudoPassword()}export function isDomainInHosts(domain){try{const hostsContent=fs.readFileSync(HOSTS_FILE,"utf-8");return hostsContent.includes(`127.0.0.1 ${domain}`)||hostsContent.includes(`::1 ${domain}`)}catch{if(process.platform!=="win32"){const sudoPassword=getSudoPassword();if(sudoPassword){try{const result=execSync(`echo '${sudoPassword}' | sudo -S cat "${HOSTS_FILE}" 2>/dev/null`,{encoding:"utf-8"});return result.includes(`127.0.0.1 ${domain}`)||result.includes(`::1 ${domain}`)}catch{return false}}}return false}}export async function addDomainToHosts(domain,verbose){if(isDomainInHosts(domain)){if(verbose)log.info(`${domain} already in hosts file`);return true}const hostsEntry=`
2
2
  # Added by Stacks
3
3
  127.0.0.1 ${domain}
4
4
  ::1 ${domain}
5
- `;if(process.platform==="win32"){log.warn("Please add this to your hosts file manually:");log.warn(`127.0.0.1 ${domain}`);log.warn(`::1 ${domain}`);log.warn(`File location: ${HOSTS_FILE}`);return!1}if(!canRunSudo()){if(verbose){log.warn(`Cannot add ${domain} to hosts file (non-interactive mode and no SUDO_PASSWORD set)`);log.info("Run `buddy setup:ssl` in a terminal or set SUDO_PASSWORD environment variable")}return!1}const sudoPassword=getSudoPassword();return new Promise((resolve)=>{let child;if(sudoPassword)child=spawn("sh",["-c",`echo '${sudoPassword}' | sudo -S sh -c "echo '${hostsEntry}' >> '${HOSTS_FILE}'"`],{stdio:["pipe","inherit","inherit"]});else child=spawn("sudo",["sh","-c",`echo '${hostsEntry}' >> "${HOSTS_FILE}"`],{stdio:"inherit"});child.on("close",(code)=>{if(code===0){if(verbose)log.success(`Added ${domain} to hosts file`);resolve(!0)}else{if(verbose){log.error(`Failed to add ${domain} to hosts file`);log.warn(`Manually add: 127.0.0.1 ${domain}`)}resolve(!1)}});child.on("error",()=>{log.error("Failed to run sudo command");resolve(!1)})})}export function sslCertificatesExist(domain){const certPath=path.join(SSL_DIR,`${domain}.crt`),keyPath=path.join(SSL_DIR,`${domain}.key`),caPath=path.join(SSL_DIR,`${domain}.ca.crt`);return fs.existsSync(certPath)&&fs.existsSync(keyPath)&&fs.existsSync(caPath)}export function isCertificateTrusted(domain){if(process.platform!=="darwin")return!0;const certPath=path.join(SSL_DIR,`${domain}.crt`);if(!fs.existsSync(certPath))return!1;try{const fingerprint=execSync(`openssl x509 -noout -fingerprint -sha256 -in "${certPath}"`,{encoding:"utf-8"}),eqIdx=fingerprint.indexOf("="),fingerprintValue=eqIdx>=0?fingerprint.slice(eqIdx+1).trim():"";if(!fingerprintValue)return!1;return execSync("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true",{encoding:"utf-8"}).includes(fingerprintValue)}catch{return!1}}export async function trustCertificate(domain,verbose){const caCertPath=path.join(SSL_DIR,`${domain}.ca.crt`),certPath=path.join(SSL_DIR,`${domain}.crt`);if(!fs.existsSync(caCertPath)){log.error(`CA certificate not found: ${caCertPath}`);return!1}if(isCertificateTrusted(domain)){if(verbose)log.info("Certificate is already trusted, skipping trust step");return!0}if(!canRunSudo()){if(verbose){log.warn("Cannot trust certificate (non-interactive mode and no SUDO_PASSWORD set)");log.info("Run `buddy setup:ssl` in a terminal or set SUDO_PASSWORD environment variable")}return!1}const sudoPassword=getSudoPassword();if(process.platform==="darwin")return new Promise((resolve)=>{const combinedCommand=`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain '${caCertPath}' && security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain '${certPath}'`;let child;if(sudoPassword)child=spawn("sh",["-c",`echo '${sudoPassword}' | sudo -S sh -c "${combinedCommand}"`],{stdio:["pipe","inherit","inherit"]});else child=spawn("sudo",["sh","-c",combinedCommand],{stdio:"inherit"});child.on("close",(code)=>{if(code===0){try{execSync(`security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db "${certPath}" 2>/dev/null || true`)}catch{}resolve(!0)}else{if(verbose){log.warn("Could not trust certificate automatically");log.info(` sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${caCertPath}"`)}resolve(!1)}});child.on("error",()=>{log.error("Failed to run sudo command");resolve(!1)})});else if(process.platform==="linux")return new Promise((resolve)=>{const linuxCommands=`mkdir -p /usr/local/share/ca-certificates/stacks && cp '${caCertPath}' /usr/local/share/ca-certificates/stacks/ && update-ca-certificates`;let child;if(sudoPassword)child=spawn("sh",["-c",`echo '${sudoPassword}' | sudo -S sh -c "${linuxCommands}"`],{stdio:["pipe","inherit","inherit"]});else child=spawn("sudo",["sh","-c",linuxCommands],{stdio:"inherit"});child.on("close",(code)=>{if(code===0){log.success("Certificate trusted");resolve(!0)}else{log.warn("Could not trust certificate automatically");resolve(!1)}});child.on("error",()=>resolve(!1))});else if(process.platform==="win32"){log.warn("Please manually trust the certificate in Windows:");log.warn(` 1. Double-click: ${caCertPath}`);log.warn(' 2. Click "Install Certificate"');log.warn(' 3. Select "Local Machine" and place in "Trusted Root Certification Authorities"');return!1}return!1}export async function generateCertificates(domain,verbose){try{const tlsxModule=await import("@stacksjs/tlsx"),{generateCertificate,createRootCA}=tlsxModule;if(!fs.existsSync(SSL_DIR))fs.mkdirSync(SSL_DIR,{recursive:!0});const config={domain,hostCertCN:domain,basePath:SSL_DIR,caCertPath:path.join(SSL_DIR,`${domain}.ca.crt`),certPath:path.join(SSL_DIR,`${domain}.crt`),keyPath:path.join(SSL_DIR,`${domain}.key`),altNameIPs:["127.0.0.1","::1"],altNameURIs:["localhost",domain],organizationName:"Stacks Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:domain,validityDays:825,verbose:verbose||!1,subjectAltNames:[{type:2,value:domain},{type:2,value:`*.${domain.split(".").slice(1).join(".")}`},{type:2,value:"localhost"},{type:2,value:"*.localhost"}]};if(verbose)log.info("Generating Root CA certificate...");const caCert=await createRootCA(config);if(verbose)log.info(`Generating host certificate for ${domain}...`);const hostCert=await generateCertificate({...config,rootCA:{certificate:caCert.certificate,privateKey:caCert.privateKey}});fs.writeFileSync(config.caCertPath,caCert.certificate);fs.writeFileSync(config.certPath,hostCert.certificate);fs.writeFileSync(config.keyPath,hostCert.privateKey);if(verbose)log.success(`SSL certificates generated for ${domain}`);return!0}catch(error){log.error(`Failed to generate certificates: ${error}`);return!1}}export async function setupSSL(options={}){const domain=options.domain||process.env.APP_URL?.replace(/^https?:\/\//,"")||"stacks.localhost";if(domain==="localhost"||domain.startsWith("localhost:")){log.info("Skipping SSL setup for localhost");return!0}let success=!0;if(!options.skipHosts){if(!await addDomainToHosts(domain,options.verbose)&&options.verbose)log.warn("Hosts file not updated - you may need to add the entry manually")}if(!sslCertificatesExist(domain)){if(options.verbose)log.info("Generating SSL certificates...");if(!await generateCertificates(domain,options.verbose)){log.error("Failed to generate SSL certificates");return!1}}if(!options.skipTrust&&!isCertificateTrusted(domain)){if(!await trustCertificate(domain,options.verbose)){log.warn("Certificate not trusted - you may see browser warnings");success=!1}}return success}export function isSSLSetupComplete(domain){return isDomainInHosts(domain)&&sslCertificatesExist(domain)}
5
+ `;if(process.platform==="win32"){log.warn("Please add this to your hosts file manually:");log.warn(`127.0.0.1 ${domain}`);log.warn(`::1 ${domain}`);log.warn(`File location: ${HOSTS_FILE}`);return false}if(!canRunSudo()){if(verbose){log.warn(`Cannot add ${domain} to hosts file (non-interactive mode and no SUDO_PASSWORD set)`);log.info("Run `buddy setup:ssl` in a terminal or set SUDO_PASSWORD environment variable")}return false}const sudoPassword=getSudoPassword();return new Promise((resolve)=>{let child;if(sudoPassword){child=spawn("sh",["-c",`echo '${sudoPassword}' | sudo -S sh -c "echo '${hostsEntry}' >> '${HOSTS_FILE}'"`],{stdio:["pipe","inherit","inherit"]})}else{child=spawn("sudo",["sh","-c",`echo '${hostsEntry}' >> "${HOSTS_FILE}"`],{stdio:"inherit"})}child.on("close",(code)=>{if(code===0){if(verbose)log.success(`Added ${domain} to hosts file`);resolve(true)}else{if(verbose){log.error(`Failed to add ${domain} to hosts file`);log.warn(`Manually add: 127.0.0.1 ${domain}`)}resolve(false)}});child.on("error",()=>{log.error("Failed to run sudo command");resolve(false)})})}export function sslCertificatesExist(domain){const certPath=path.join(SSL_DIR,`${domain}.crt`);const keyPath=path.join(SSL_DIR,`${domain}.key`);const caPath=path.join(SSL_DIR,`${domain}.ca.crt`);return fs.existsSync(certPath)&&fs.existsSync(keyPath)&&fs.existsSync(caPath)}export function isCertificateTrusted(domain){if(process.platform!=="darwin")return true;const certPath=path.join(SSL_DIR,`${domain}.crt`);if(!fs.existsSync(certPath))return false;try{const fingerprint=execSync(`openssl x509 -noout -fingerprint -sha256 -in "${certPath}"`,{encoding:"utf-8"});const eqIdx=fingerprint.indexOf("=");const fingerprintValue=eqIdx>=0?fingerprint.slice(eqIdx+1).trim():"";if(!fingerprintValue)return false;const keychainOutput=execSync("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true",{encoding:"utf-8"});return keychainOutput.includes(fingerprintValue)}catch{return false}}export async function trustCertificate(domain,verbose){const caCertPath=path.join(SSL_DIR,`${domain}.ca.crt`);const certPath=path.join(SSL_DIR,`${domain}.crt`);if(!fs.existsSync(caCertPath)){log.error(`CA certificate not found: ${caCertPath}`);return false}if(isCertificateTrusted(domain)){if(verbose)log.info("Certificate is already trusted, skipping trust step");return true}if(!canRunSudo()){if(verbose){log.warn("Cannot trust certificate (non-interactive mode and no SUDO_PASSWORD set)");log.info("Run `buddy setup:ssl` in a terminal or set SUDO_PASSWORD environment variable")}return false}const sudoPassword=getSudoPassword();if(process.platform==="darwin"){return new Promise((resolve)=>{const combinedCommand=`security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain '${caCertPath}' && security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain '${certPath}'`;let child;if(sudoPassword){child=spawn("sh",["-c",`echo '${sudoPassword}' | sudo -S sh -c "${combinedCommand}"`],{stdio:["pipe","inherit","inherit"]})}else{child=spawn("sudo",["sh","-c",combinedCommand],{stdio:"inherit"})}child.on("close",(code)=>{if(code===0){try{execSync(`security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain-db "${certPath}" 2>/dev/null || true`)}catch{}resolve(true)}else{if(verbose){log.warn("Could not trust certificate automatically");log.info(` sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain "${caCertPath}"`)}resolve(false)}});child.on("error",()=>{log.error("Failed to run sudo command");resolve(false)})})}else if(process.platform==="linux"){return new Promise((resolve)=>{const linuxCommands=`mkdir -p /usr/local/share/ca-certificates/stacks && cp '${caCertPath}' /usr/local/share/ca-certificates/stacks/ && update-ca-certificates`;let child;if(sudoPassword){child=spawn("sh",["-c",`echo '${sudoPassword}' | sudo -S sh -c "${linuxCommands}"`],{stdio:["pipe","inherit","inherit"]})}else{child=spawn("sudo",["sh","-c",linuxCommands],{stdio:"inherit"})}child.on("close",(code)=>{if(code===0){log.success("Certificate trusted");resolve(true)}else{log.warn("Could not trust certificate automatically");resolve(false)}});child.on("error",()=>resolve(false))})}else if(process.platform==="win32"){log.warn("Please manually trust the certificate in Windows:");log.warn(` 1. Double-click: ${caCertPath}`);log.warn(' 2. Click "Install Certificate"');log.warn(' 3. Select "Local Machine" and place in "Trusted Root Certification Authorities"');return false}return false}export async function generateCertificates(domain,verbose){try{const tlsxModule=await import("@stacksjs/tlsx");const{generateCertificate,createRootCA}=tlsxModule;if(!fs.existsSync(SSL_DIR)){fs.mkdirSync(SSL_DIR,{recursive:true})}const config={domain,hostCertCN:domain,basePath:SSL_DIR,caCertPath:path.join(SSL_DIR,`${domain}.ca.crt`),certPath:path.join(SSL_DIR,`${domain}.crt`),keyPath:path.join(SSL_DIR,`${domain}.key`),altNameIPs:["127.0.0.1","::1"],altNameURIs:["localhost",domain],organizationName:"Stacks Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:domain,validityDays:825,verbose:verbose||false,subjectAltNames:[{type:2,value:domain},{type:2,value:`*.${domain.split(".").slice(1).join(".")}`},{type:2,value:"localhost"},{type:2,value:"*.localhost"}]};if(verbose)log.info("Generating Root CA certificate...");const caCert=await createRootCA(config);if(verbose)log.info(`Generating host certificate for ${domain}...`);const hostCert=await generateCertificate({...config,rootCA:{certificate:caCert.certificate,privateKey:caCert.privateKey}});fs.writeFileSync(config.caCertPath,caCert.certificate);fs.writeFileSync(config.certPath,hostCert.certificate);fs.writeFileSync(config.keyPath,hostCert.privateKey);if(verbose)log.success(`SSL certificates generated for ${domain}`);return true}catch(error){log.error(`Failed to generate certificates: ${error}`);return false}}export async function setupSSL(options={}){const domain=options.domain||process.env.APP_URL?.replace(/^https?:\/\//,"")||"stacks.localhost";if(domain==="localhost"||domain.startsWith("localhost:")){log.info("Skipping SSL setup for localhost");return true}let success=true;if(!options.skipHosts){const hostsResult=await addDomainToHosts(domain,options.verbose);if(!hostsResult&&options.verbose){log.warn("Hosts file not updated - you may need to add the entry manually")}}if(!sslCertificatesExist(domain)){if(options.verbose)log.info("Generating SSL certificates...");const certResult=await generateCertificates(domain,options.verbose);if(!certResult){log.error("Failed to generate SSL certificates");return false}}if(!options.skipTrust&&!isCertificateTrusted(domain)){const trustResult=await trustCertificate(domain,options.verbose);if(!trustResult){log.warn("Certificate not trusted - you may see browser warnings");success=false}}return success}export function isSSLSetupComplete(domain){return isDomainInHosts(domain)&&sslCertificatesExist(domain)}