@stacksjs/actions 0.75.552 → 0.75.556
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build/desktop-release.js +2 -2
- package/dist/helpers/utils.d.ts +1 -1
- package/dist/upgrade/binary.js +1 -1
- package/dist/upgrade/bun.d.ts +1 -1
- package/dist/upgrade/bun.js +1 -0
- package/dist/upgrade/dependencies.d.ts +1 -1
- package/dist/upgrade/dependencies.js +1 -0
- package/dist/upgrade/framework-preview.d.ts +67 -0
- package/dist/upgrade/framework-preview.js +8 -0
- package/dist/upgrade/framework.js +2 -9
- package/dist/upgrade/index.js +1 -1
- package/dist/upgrade/packages.d.ts +5 -2
- package/dist/upgrade/packages.js +36 -9
- package/dist/upgrade/run.d.ts +4 -0
- package/dist/upgrade/run.js +1 -0
- package/dist/upgrade/shell.js +1 -1
- package/dist/upgrade/tool-preview.d.ts +2 -0
- package/dist/upgrade/tool-preview.js +1 -0
- package/package.json +41 -41
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{copyFileSync,cpSync,existsSync,mkdirSync,mkdtempSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{basename,join,resolve}from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";import{compareVersions,DEFAULT_UPDATE_PREFIX,describeArtifact,developerIdProblem,loadWebviewDesktop,publishDesktopUpdate,releaseArtifactNames,releaseVersionProblem,resolveDmgPackaging,splitDesktopTarget,storageUpdateStore,updateArtifactKey,updateManifestKey,updatePublicKey,validateUpdateManifest}from"@stacksjs/desktop-build";import{projectPath}from"@stacksjs/path";import{imageDmg,notarizeAndStaple,notaryArguments}from"./notarize";process.exitCode=1;const root=projectPath();const pkg=existsSync(join(root,"package.json"))?JSON.parse(readFileSync(join(root,"package.json"),"utf8")):{};const config=await loadWebviewDesktop(root,pkg.version);if(!config)throw new Error("config/desktop.ts has no webview section.");if(!config.updates)throw new Error("config/desktop.ts has no webview.updates: a release needs the feed URL and the public keys the app trusts.");const dryRun=process.env.DESKTOP_RELEASE_DRY_RUN==="1";const channel=process.env.DESKTOP_RELEASE_CHANNEL||config.updates.channel||"stable";const prefix=config.updates.prefix??DEFAULT_UPDATE_PREFIX;const output=resolve(root,config.output);const releaseDir=join(output,"release");const buildFile=join(output,"build.json");if(!existsSync(buildFile))throw new Error("Nothing was built. Run `buddy build:desktop` first, or drop --skip-build.");const build=JSON.parse(readFileSync(buildFile,"utf8"));if(build.version!==config.version)throw new Error(`The build is ${build.version} but the config says ${config.version}. Build again.`);if(!build.sourceRevision||!/^[0-9a-f]{40}$/.test(build.sourceRevision))throw new Error("A release names the commit it was built from, and this build has none. Build from a Git checkout.");const sourceRevision=build.sourceRevision;const dirty=Bun.spawnSync(["git","status","--porcelain"],{cwd:root,stdout:"pipe"}).stdout.toString().trim();const head=Bun.spawnSync(["git","rev-parse","HEAD"],{cwd:root,stdout:"pipe"}).stdout.toString().trim();if(process.env.DESKTOP_RELEASE_ALLOW_DIRTY!=="1"){if(dirty)throw new Error(`The working tree is not clean, and the build came out of it. Commit these first:
|
|
2
|
-
${dirty}`);if(head!==sourceRevision)throw new Error(`The build is from ${sourceRevision.slice(0,12)} but HEAD is ${head.slice(0,12)}. Build again.`)}const privateKey=process.env.DESKTOP_UPDATE_PRIVATE_KEY;if(!privateKey)throw new Error("DESKTOP_UPDATE_PRIVATE_KEY is not set. It is the private half `buddy desktop:update:keypair` printed.");const publicKey=updatePublicKey(privateKey);const keyId=Object.entries(config.updates.publicKeys).find(([,key])=>key===publicKey)?.[0];if(!keyId)throw new Error("DESKTOP_UPDATE_PRIVATE_KEY does not match any key in webview.updates.publicKeys: installed apps would refuse what it signs.");const notes=process.env.DESKTOP_RELEASE_NOTES?readFileSync(resolve(root,process.env.DESKTOP_RELEASE_NOTES),"utf8").trim():undefined;const{signingIdentity,notary}=resolveDmgPackaging({flags:{},env:process.env});const store=dryRun?{read:async()=>null,write:async()=>{},publicUrl:async(key)=>`https://dry-run.invalid/${key}`}:await storageUpdateStore(config.updates.disk);const planned=[];for(const item of build.targets){const{platform,architecture}=splitDesktopTarget(item.target);const directory=join(output,item.directory);const names=releaseArtifactNames(config,item.target);const staged=join(releaseDir,item.target);const location={platform,architecture,channel,prefix};const existing=await store.read(updateManifestKey(location));const problem=releaseVersionProblem(config.version,existing?validateUpdateManifest(JSON.parse(existing)).version:null,compareVersions);if(problem)throw new Error(`${item.target}: ${problem}`);if(platform==="darwin"){const app=join(directory,`${config.appName}.app`);if(process.platform!=="darwin"||!existsSync(app))throw new Error(`${item.target}: the .app is signed and notarized on macOS. Run this release on a Mac.`);if(!dryRun){if(!signingIdentity||!notary)throw new Error(`${item.target}: a release needs a Developer ID identity and notary credentials: --identity and --notary-profile (or DESKTOP_SIGNING_IDENTITY / DESKTOP_NOTARY_PROFILE).`);const signature=Bun.spawnSync(["codesign","-dvv",app],{stderr:"pipe"});const unsigned=developerIdProblem(`${signature.stdout.toString()}${signature.stderr.toString()}`);if(unsigned)throw new Error(`${item.target}: ${app} cannot be notarized: ${unsigned}`)}const dmg=join(staged,names.downloads[0]);planned.push({target:item.target,directory:staged,update:join(staged,names.update),downloads:[dmg],prepare:async()=>{const scratch=mkdtempSync(join(tmpdir(),"stacks-desktop-release-"));try{const auth=!dryRun&¬ary?notaryArguments(notary):undefined;if(auth)await notarizeAndStaple(app,`${config.appName}.app`,auth,scratch);run(["ditto","-c","-k","--keepParent",app,join(staged,names.update)]);const staging=join(scratch,"dmg");mkdirSync(staging,{recursive:true});cpSync(app,join(staging,`${config.appName}.app`),{recursive:true,verbatimSymlinks:true});await imageDmg({staging,volumeName:config.appName,dmgPath:dmg,...dryRun?{}:{signingIdentity}});if(auth){await notarizeAndStaple(dmg,"the DMG",auth,scratch);run(["codesign","--verify","--deep","--strict",app]);run(["spctl","-a","-t","open","--context","context:primary-signature",dmg]);run(["xcrun","stapler","validate",dmg])}}finally{rmSync(scratch,{recursive:true,force:true})}}});continue}const packages=join(directory,"packages");const made=item.artifacts.map((artifact)=>join(directory,artifact.name));const find=(extension)=>made.find((file)=>file.toLowerCase().endsWith(extension)&&existsSync(file));const wanted=platform==="win32"?".msi":".appimage";const installer=find(wanted);if(!installer){throw new Error(`${item.target}: there is no ${platform==="win32"?"MSI":"AppImage"} in ${packages}. Run \`buddy build:desktop --target ${item.target} --package\` on ${platform==="win32"?"Windows":"Linux"}, then release with --skip-build.`)}const extras=platform==="linux"?[".deb",".rpm"].map(find).filter((file)=>Boolean(file)):[];planned.push({target:item.target,directory:staged,update:join(staged,names.update),downloads:extras.map((file,index)=>join(staged,names.downloads[index]??basename(file))),prepare:async()=>{copyFileSync(installer,join(staged,names.update));extras.forEach((file,index)=>copyFileSync(file,join(staged,names.downloads[index]??basename(file))))}})}if(!planned.length)throw new Error("The build has no targets to release.");function run(command){console.log(`> ${command.join(" ")}`);const result=Bun.spawnSync(command,{stdout:"inherit",stderr:"inherit"});if(result.exitCode!==0)throw new Error(`${command[0]} exited with ${result.exitCode}`)}rmSync(releaseDir,{recursive:true,force:true});for(const item of planned){mkdirSync(item.directory,{recursive:true});await log.info(`Preparing ${item.target}`);await item.prepare()}const published=[];for(const item of planned){const{platform,architecture}=splitDesktopTarget(item.target);const location={platform,architecture,channel,prefix};const downloads=[];for(const file of item.downloads){const key=updateArtifactKey(location,config.version,basename(file));await store.write(key,readFileSync(file));const{sha256,size}=await describeArtifact(file);downloads.push({name:basename(file),url:
|
|
1
|
+
import{copyFileSync,cpSync,existsSync,mkdirSync,mkdtempSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{basename,join,resolve}from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";import{artifactUrlProblem,compareVersions,DEFAULT_UPDATE_PREFIX,describeArtifact,developerIdProblem,loadWebviewDesktop,publishDesktopUpdate,publishedArtifactUrl,releaseArtifactNames,releaseVersionProblem,resolveDmgPackaging,splitDesktopTarget,storageUpdateStore,updateArtifactKey,updateManifestKey,updatePublicKey,validateUpdateManifest}from"@stacksjs/desktop-build";import{projectPath}from"@stacksjs/path";import{imageDmg,notarizeAndStaple,notaryArguments}from"./notarize";process.exitCode=1;const root=projectPath();const pkg=existsSync(join(root,"package.json"))?JSON.parse(readFileSync(join(root,"package.json"),"utf8")):{};const config=await loadWebviewDesktop(root,pkg.version);if(!config)throw new Error("config/desktop.ts has no webview section.");if(!config.updates)throw new Error("config/desktop.ts has no webview.updates: a release needs the feed URL and the public keys the app trusts.");const dryRun=process.env.DESKTOP_RELEASE_DRY_RUN==="1";const updates=config.updates;const channel=process.env.DESKTOP_RELEASE_CHANNEL||config.updates.channel||"stable";const prefix=config.updates.prefix??DEFAULT_UPDATE_PREFIX;const output=resolve(root,config.output);const releaseDir=join(output,"release");const buildFile=join(output,"build.json");if(!existsSync(buildFile))throw new Error("Nothing was built. Run `buddy build:desktop` first, or drop --skip-build.");const build=JSON.parse(readFileSync(buildFile,"utf8"));if(build.version!==config.version)throw new Error(`The build is ${build.version} but the config says ${config.version}. Build again.`);if(!build.sourceRevision||!/^[0-9a-f]{40}$/.test(build.sourceRevision))throw new Error("A release names the commit it was built from, and this build has none. Build from a Git checkout.");const sourceRevision=build.sourceRevision;const dirty=Bun.spawnSync(["git","status","--porcelain"],{cwd:root,stdout:"pipe"}).stdout.toString().trim();const head=Bun.spawnSync(["git","rev-parse","HEAD"],{cwd:root,stdout:"pipe"}).stdout.toString().trim();if(process.env.DESKTOP_RELEASE_ALLOW_DIRTY!=="1"){if(dirty)throw new Error(`The working tree is not clean, and the build came out of it. Commit these first:
|
|
2
|
+
${dirty}`);if(head!==sourceRevision)throw new Error(`The build is from ${sourceRevision.slice(0,12)} but HEAD is ${head.slice(0,12)}. Build again.`)}const privateKey=process.env.DESKTOP_UPDATE_PRIVATE_KEY;if(!privateKey)throw new Error("DESKTOP_UPDATE_PRIVATE_KEY is not set. It is the private half `buddy desktop:update:keypair` printed.");const publicKey=updatePublicKey(privateKey);const keyId=Object.entries(config.updates.publicKeys).find(([,key])=>key===publicKey)?.[0];if(!keyId)throw new Error("DESKTOP_UPDATE_PRIVATE_KEY does not match any key in webview.updates.publicKeys: installed apps would refuse what it signs.");const notes=process.env.DESKTOP_RELEASE_NOTES?readFileSync(resolve(root,process.env.DESKTOP_RELEASE_NOTES),"utf8").trim():undefined;const{signingIdentity,notary}=resolveDmgPackaging({flags:{},env:process.env});const store=dryRun?{read:async()=>null,write:async()=>{},publicUrl:async(key)=>`https://dry-run.invalid/${key}`}:await storageUpdateStore(config.updates.disk);const artifactUrl=(location,file)=>publishedArtifactUrl({store,artifactBaseUrl:updates.artifactBaseUrl,feedUrl:updates.feedUrl,...location},config.version,basename(file));const planned=[];for(const item of build.targets){const{platform,architecture}=splitDesktopTarget(item.target);const directory=join(output,item.directory);const names=releaseArtifactNames(config,item.target);const staged=join(releaseDir,item.target);const location={platform,architecture,channel,prefix};const existing=await store.read(updateManifestKey(location));const unreachable=artifactUrlProblem(await artifactUrl(location,names.update));if(unreachable&&process.env.DESKTOP_RELEASE_ALLOW_LOCAL_URL!=="1"){throw new Error(`${item.target}: ${unreachable}. Set webview.updates.${updates.artifactBaseUrl?"artifactBaseUrl":"feedUrl"} to the address the app is served from.`)}const problem=releaseVersionProblem(config.version,existing?validateUpdateManifest(JSON.parse(existing)).version:null,compareVersions);if(problem)throw new Error(`${item.target}: ${problem}`);if(platform==="darwin"){const app=join(directory,`${config.appName}.app`);if(process.platform!=="darwin"||!existsSync(app))throw new Error(`${item.target}: the .app is signed and notarized on macOS. Run this release on a Mac.`);if(!dryRun){if(!signingIdentity||!notary)throw new Error(`${item.target}: a release needs a Developer ID identity and notary credentials: --identity and --notary-profile (or DESKTOP_SIGNING_IDENTITY / DESKTOP_NOTARY_PROFILE).`);const signature=Bun.spawnSync(["codesign","-dvv",app],{stderr:"pipe"});const unsigned=developerIdProblem(`${signature.stdout.toString()}${signature.stderr.toString()}`);if(unsigned)throw new Error(`${item.target}: ${app} cannot be notarized: ${unsigned}`)}const dmg=join(staged,names.downloads[0]);planned.push({target:item.target,directory:staged,update:join(staged,names.update),downloads:[dmg],prepare:async()=>{const scratch=mkdtempSync(join(tmpdir(),"stacks-desktop-release-"));try{const auth=!dryRun&¬ary?notaryArguments(notary):undefined;if(auth)await notarizeAndStaple(app,`${config.appName}.app`,auth,scratch);run(["ditto","-c","-k","--keepParent",app,join(staged,names.update)]);const staging=join(scratch,"dmg");mkdirSync(staging,{recursive:true});cpSync(app,join(staging,`${config.appName}.app`),{recursive:true,verbatimSymlinks:true});await imageDmg({staging,volumeName:config.appName,dmgPath:dmg,...dryRun?{}:{signingIdentity}});if(auth){await notarizeAndStaple(dmg,"the DMG",auth,scratch);run(["codesign","--verify","--deep","--strict",app]);run(["spctl","-a","-t","open","--context","context:primary-signature",dmg]);run(["xcrun","stapler","validate",dmg])}}finally{rmSync(scratch,{recursive:true,force:true})}}});continue}const packages=join(directory,"packages");const made=item.artifacts.map((artifact)=>join(directory,artifact.name));const find=(extension)=>made.find((file)=>file.toLowerCase().endsWith(extension)&&existsSync(file));const wanted=platform==="win32"?".msi":".appimage";const installer=find(wanted);if(!installer){throw new Error(`${item.target}: there is no ${platform==="win32"?"MSI":"AppImage"} in ${packages}. Run \`buddy build:desktop --target ${item.target} --package\` on ${platform==="win32"?"Windows":"Linux"}, then release with --skip-build.`)}const extras=platform==="linux"?[".deb",".rpm"].map(find).filter((file)=>Boolean(file)):[];planned.push({target:item.target,directory:staged,update:join(staged,names.update),downloads:extras.map((file,index)=>join(staged,names.downloads[index]??basename(file))),prepare:async()=>{copyFileSync(installer,join(staged,names.update));extras.forEach((file,index)=>copyFileSync(file,join(staged,names.downloads[index]??basename(file))))}})}if(!planned.length)throw new Error("The build has no targets to release.");function run(command){console.log(`> ${command.join(" ")}`);const result=Bun.spawnSync(command,{stdout:"inherit",stderr:"inherit"});if(result.exitCode!==0)throw new Error(`${command[0]} exited with ${result.exitCode}`)}rmSync(releaseDir,{recursive:true,force:true});for(const item of planned){mkdirSync(item.directory,{recursive:true});await log.info(`Preparing ${item.target}`);await item.prepare()}const published=[];for(const item of planned){const{platform,architecture}=splitDesktopTarget(item.target);const location={platform,architecture,channel,prefix};const downloads=[];for(const file of item.downloads){const key=updateArtifactKey(location,config.version,basename(file));await store.write(key,readFileSync(file));const{sha256,size}=await describeArtifact(file);downloads.push({name:basename(file),url:await artifactUrl(location,file),sha256,bytes:size})}const manifest=await publishDesktopUpdate({store,artifact:item.update,version:config.version,sourceRevision,privateKey,keyId,notes,artifactBaseUrl:updates.artifactBaseUrl,feedUrl:updates.feedUrl,...location});writeFileSync(join(item.directory,"latest.json"),`${JSON.stringify(manifest,null,2)}
|
|
3
3
|
`);published.push({target:item.target,manifest,downloads});await log.success(`${item.target}: ${dryRun?"would publish":"published"} ${basename(item.update)} (${manifest.size} bytes, sha256 ${manifest.sha256})`)}const summary={version:config.version,channel,sourceRevision,publishedAt:new Date().toISOString(),targets:published.map((item)=>({target:item.target,update:{url:item.manifest.url,sha256:item.manifest.sha256,bytes:item.manifest.size},downloads:item.downloads}))};writeFileSync(join(releaseDir,"release.json"),`${JSON.stringify(summary,null,2)}
|
|
4
4
|
`);if(!dryRun)await store.write(`${prefix}/${channel}/release.json`,`${JSON.stringify(summary,null,2)}
|
|
5
5
|
`);await log.success(dryRun?`Dry run: nothing was notarized or uploaded. See ${releaseDir}`:`Released ${config.appName} ${config.version} on ${channel} for ${published.map((item)=>item.target).join(", ")}`);process.exitCode=0;
|
package/dist/helpers/utils.d.ts
CHANGED
|
@@ -28,7 +28,7 @@ export declare function developmentWatchFlag(action: Action): string;
|
|
|
28
28
|
* @returns The result of the command.
|
|
29
29
|
*/
|
|
30
30
|
export declare function runActions(actions: Action[], options?: ActionOptions): Promise<any>;
|
|
31
|
-
export declare function runActionSequence(actions: Action[], options: ActionOptions | undefined, runner?: typeof runAction): Promise<any>;
|
|
31
|
+
export declare function runActionSequence(actions: Action[], options: ActionOptions | undefined, runner?: typeof runAction | ((action: Action, options?: ActionOptions) => Promise<Result<void, CommandError>>)): Promise<any>;
|
|
32
32
|
// looks in most common locations
|
|
33
33
|
export declare function hasAction(action: Action): boolean;
|
|
34
34
|
/**
|
package/dist/upgrade/binary.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{runCommand}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{fs,storage}from"@stacksjs/storage";const source=path.buddyPath("dist/stacks");const destination=path.homeDir(".stacks/bin/stacks");const destinationDir=path.homeDir(".stacks/bin/");log.info("Upgrading `stacks`...");const result=await runCommand("bun compile.ts",{cwd:path.buddyPath()});if(result.isErr){await log.error("There was an error compiling the binary",result.error);process.exit(ExitCode.FatalError)}if(await storage.exists(source)){try{log.info("Updating Binary...");log.info(`Source: ${source}`);log.info(`Destination: ${destination}`);await fs.promises.mkdir(destinationDir,{recursive:true});await fs.promises.copyFile(source,destination);await fs.promises.unlink(source);log.success("Binary Latest Version Is Used")}catch(err){await log.error(err);process.exit(ExitCode.FatalError)}}else{await log.error(`Binary source not found: ${source}`);process.exit(ExitCode.FatalError)}
|
|
1
|
+
import process from"node:process";import{parseOptions,print,runCommand}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{fs,storage}from"@stacksjs/storage";import{upgradeToolPreview}from"./tool-preview";const options=parseOptions();if(options.dryRun){print(upgradeToolPreview(Action.UpgradeBinary));process.exit(ExitCode.Success)}const source=path.buddyPath("dist/stacks");const destination=path.homeDir(".stacks/bin/stacks");const destinationDir=path.homeDir(".stacks/bin/");log.info("Upgrading `stacks`...");const result=await runCommand("bun compile.ts",{cwd:path.buddyPath()});if(result.isErr){await log.error("There was an error compiling the binary",result.error);process.exit(ExitCode.FatalError)}if(await storage.exists(source)){try{log.info("Updating Binary...");log.info(`Source: ${source}`);log.info(`Destination: ${destination}`);await fs.promises.mkdir(destinationDir,{recursive:true});await fs.promises.copyFile(source,destination);await fs.promises.unlink(source);log.success("Binary Latest Version Is Used")}catch(err){await log.error(err);process.exit(ExitCode.FatalError)}}else{await log.error(`Binary source not found: ${source}`);process.exit(ExitCode.FatalError)}
|
package/dist/upgrade/bun.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export {};
|
package/dist/upgrade/bun.js
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import process from"node:process";import{parseOptions,print}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{upgradeToolPreview}from"./tool-preview";if(parseOptions().dryRun){print(upgradeToolPreview(Action.UpgradeBun));process.exit(ExitCode.Success)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import process from"node:process";import{parseOptions,print}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{ExitCode}from"@stacksjs/types";import{upgradeToolPreview}from"./tool-preview";if(parseOptions().dryRun){print(upgradeToolPreview(Action.UpgradeDeps));process.exit(ExitCode.Success)}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { readChannel, readVersion, type SnapshotEntry, type UpgradeContext } from './framework-utils';
|
|
2
|
+
import type { UpgradeOptions } from '@stacksjs/types';
|
|
3
|
+
// This reusable preview never executes project action bodies, installation,
|
|
4
|
+
// compilation, or hooks. Remote inspection retains the native owned temporary
|
|
5
|
+
// template staging below, always removed in finally; user destinations are read-only.
|
|
6
|
+
export declare function resolveFrameworkUpgrade(projectRoot: string, options: UpgradeOptions): Promise<{
|
|
7
|
+
channelFile: __dtsx_return_0.__dtsx_return_0_result_0;
|
|
8
|
+
versionFile: __dtsx_return_0.__dtsx_return_0_result_1;
|
|
9
|
+
currentChannel: __dtsx_return_0.__dtsx_return_0_result_2;
|
|
10
|
+
corePkgPath: __dtsx_return_0.__dtsx_return_0_result_3;
|
|
11
|
+
currentVersion: __dtsx_return_0.__dtsx_return_0_result_4;
|
|
12
|
+
detectedLocal: __dtsx_return_0.__dtsx_return_0_result_5;
|
|
13
|
+
usingLocal: __dtsx_return_0.__dtsx_return_0_result_6;
|
|
14
|
+
ctx: __dtsx_return_0.__dtsx_return_0_result_7
|
|
15
|
+
}>;
|
|
16
|
+
/**
|
|
17
|
+
* `--dry-run` preview. Reports exactly what a real run would do (per-path
|
|
18
|
+
* file diffs, version change, channel/sha writes, post-sync hooks) while
|
|
19
|
+
* performing no writes itself. Runs entirely against the upgrade source:
|
|
20
|
+
* the local checkout for `--from`, or templates downloaded into a temp dir
|
|
21
|
+
* OUTSIDE the project (removed afterwards) for the GitHub path.
|
|
22
|
+
*/
|
|
23
|
+
export declare function previewFrameworkUpgrade(projectRoot: string, options: UpgradeOptions, resolved?: Awaited<ReturnType<typeof resolveFrameworkUpgrade>>): Promise<void>;
|
|
24
|
+
export declare function detectDirtyManagedPaths(root: string): Promise<string[]>;
|
|
25
|
+
/**
|
|
26
|
+
* Resolve the commit sha of the channel's branch HEAD for the up-to-date
|
|
27
|
+
* short-circuit. For a local checkout we `git rev-parse <ref>` in that repo
|
|
28
|
+
* (falling back to HEAD if the named branch doesn't exist locally). For the
|
|
29
|
+
* GitHub path we `git ls-remote` for `refs/heads/<ref>`. Fails OPEN: any
|
|
30
|
+
* failure (no git, offline, unknown ref) returns null so the caller proceeds
|
|
31
|
+
* with the sync rather than blocking on a network blip.
|
|
32
|
+
*/
|
|
33
|
+
export declare function getRemoteSha(context: UpgradeContext, fromLocal: boolean, stacksRoot: string | null): Promise<string | null>;
|
|
34
|
+
export declare function singleFileSnapshot(absPath: string): Promise<Map<string, SnapshotEntry>>;
|
|
35
|
+
export declare function pkgJsonInTree(dir: string): boolean;
|
|
36
|
+
declare namespace __dtsx_return_0 {
|
|
37
|
+
const channelFile: unknown;
|
|
38
|
+
const versionFile: unknown;
|
|
39
|
+
const currentChannel: ReturnType<typeof readChannel>;
|
|
40
|
+
const corePkgPath: unknown;
|
|
41
|
+
const currentVersion: ReturnType<typeof readVersion>;
|
|
42
|
+
const explicitLocal: unknown | null;
|
|
43
|
+
const detectedLocal: unknown;
|
|
44
|
+
const usingLocal: boolean;
|
|
45
|
+
let latestStableRef: string | 'main';
|
|
46
|
+
const ctx: unknown;
|
|
47
|
+
namespace __dtsx_return_0_scope_0 {
|
|
48
|
+
type __dtsx_return_0_result_0 = typeof channelFile
|
|
49
|
+
type __dtsx_return_0_result_1 = typeof versionFile
|
|
50
|
+
type __dtsx_return_0_result_2 = typeof currentChannel
|
|
51
|
+
type __dtsx_return_0_result_3 = typeof corePkgPath
|
|
52
|
+
type __dtsx_return_0_result_4 = typeof currentVersion
|
|
53
|
+
type __dtsx_return_0_result_5 = typeof detectedLocal
|
|
54
|
+
type __dtsx_return_0_result_6 = typeof usingLocal
|
|
55
|
+
type __dtsx_return_0_result_7 = typeof ctx
|
|
56
|
+
}
|
|
57
|
+
type __dtsx_return_0_result_0 = __dtsx_return_0_scope_0.__dtsx_return_0_result_0
|
|
58
|
+
type __dtsx_return_0_result_1 = __dtsx_return_0_scope_0.__dtsx_return_0_result_1
|
|
59
|
+
type __dtsx_return_0_result_2 = __dtsx_return_0_scope_0.__dtsx_return_0_result_2
|
|
60
|
+
type __dtsx_return_0_result_3 = __dtsx_return_0_scope_0.__dtsx_return_0_result_3
|
|
61
|
+
type __dtsx_return_0_result_4 = __dtsx_return_0_scope_0.__dtsx_return_0_result_4
|
|
62
|
+
type __dtsx_return_0_result_5 = __dtsx_return_0_scope_0.__dtsx_return_0_result_5
|
|
63
|
+
type __dtsx_return_0_result_6 = __dtsx_return_0_scope_0.__dtsx_return_0_result_6
|
|
64
|
+
type __dtsx_return_0_result_7 = __dtsx_return_0_scope_0.__dtsx_return_0_result_7
|
|
65
|
+
|
|
66
|
+
}
|
|
67
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{existsSync,mkdtempSync,readFileSync,rmSync}from"node:fs";import{tmpdir}from"node:os";import{join,resolve}from"node:path";import{downloadTemplate}from"@stacksjs/gitit";import{buildTemplateString,detectLocalStacks,diffSnapshotsDetailed,MANAGED_PATHS,readChannel,readSyncedVersion,readVersion,resolveLatestStableTag,resolveUpgradeContext,resolveUpgradeMessage,shouldAutoDetectLocalStacks,shouldShortCircuit,snapshotTree}from"./framework-utils";import{detectDependencyInstaller,shouldRefreshPostSyncDependencies}from"./framework-hooks";import{detectProjectAiProviders}from"./package-project";export async function resolveFrameworkUpgrade(projectRoot,options){const channelFile=join(projectRoot,".stacks-channel");const versionFile=join(projectRoot,".stacks-version");const currentChannel=readChannel(channelFile);const corePkgPath=join(projectRoot,"storage/framework/core/buddy/package.json");const currentVersion=readVersion(corePkgPath);const explicitLocal=options.from?resolve(projectRoot,options.from):null;const detectedLocal=explicitLocal??(shouldAutoDetectLocalStacks(options)?detectLocalStacks(projectRoot):null);const usingLocal=!!detectedLocal;const willResolveStable=!usingLocal&&!options.version&&!options.canary&&(!!options.stable||currentChannel!=="canary");let latestStableRef=currentVersion?`v${currentVersion}`:"main";if(willResolveStable){latestStableRef=await resolveLatestStableTag()??latestStableRef}const ctx=resolveUpgradeContext(options,currentChannel,latestStableRef);console.log(resolveUpgradeMessage(ctx,currentChannel,!!options.stable));console.log(usingLocal?` source: local checkout at ${detectedLocal}`:` source: github:stacksjs/stacks#${ctx.ref}`);return{channelFile,versionFile,currentChannel,corePkgPath,currentVersion,detectedLocal,usingLocal,ctx}}export async function previewFrameworkUpgrade(projectRoot,options,resolved){const{versionFile,currentVersion,detectedLocal,usingLocal,ctx}=resolved??await resolveFrameworkUpgrade(projectRoot,options);console.log(`
|
|
2
|
+
DRY RUN - preview only. No files will be written, nothing will be installed, no migrations will run.
|
|
3
|
+
`);const dirty=await detectDirtyManagedPaths(projectRoot);if(dirty.length>0){console.warn(" Note: these framework-managed paths have uncommitted changes (a real run would abort without --force):");for(const path of dirty)console.warn(` - ${path}`);console.warn("")}let previewSha=null;if(!options.force&&!ctx.targetVersion){previewSha=await getRemoteSha(ctx,usingLocal,detectedLocal);const synced=readSyncedVersion(versionFile);if(shouldShortCircuit({force:!!options.force,targetVersion:ctx.targetVersion,remoteSha:previewSha,synced,channel:ctx.channel})){console.log(`✔ Already on the latest ${ctx.channel} (${previewSha.slice(0,7)}). A real run would change nothing.`);return}}const aggregate={added:0,changed:0,removed:0,unchanged:0};const perPath=[];let sawRemoved=0;let sourceVersion=null;const tmpBase=mkdtempSync(join(tmpdir(),"stacks-upgrade-dry-run-"));try{let repoTmp=null;for(const managed of MANAGED_PATHS){const localTarget=join(projectRoot,managed.localPath);const before=managed.isFile?await singleFileSnapshot(localTarget):await snapshotTree(localTarget,managed.skip);let after;if(usingLocal&&detectedLocal){const src=join(detectedLocal,managed.subPath);if(!existsSync(src)){console.log(` ${managed.label.padEnd(10)} skip: source missing at ${src}`);continue}after=managed.isFile?await singleFileSnapshot(src):await snapshotTree(src,managed.skip)}else{try{if(managed.isFile){if(!repoTmp){repoTmp=join(tmpBase,"repo");await downloadTemplate(`github:stacksjs/stacks#${ctx.ref}`,{dir:repoTmp,force:true,forceClean:true,preferOffline:true,silent:true})}after=await singleFileSnapshot(join(repoTmp,managed.subPath))}else{const dir=join(tmpBase,managed.label);await downloadTemplate(buildTemplateString(ctx.ref,managed.subPath),{dir,force:true,forceClean:true,preferOffline:!options.force,silent:true});after=await snapshotTree(dir,managed.skip)}}catch(err){console.log(` ${managed.label.padEnd(10)} preview unavailable (${err?.message||err}); a real run would sync from github:stacksjs/stacks#${ctx.ref}`);continue}}const summary=diffSnapshotsDetailed(before,after);aggregate.added+=summary.added;aggregate.changed+=summary.changed;aggregate.removed+=summary.removed;aggregate.unchanged+=summary.unchanged;perPath.push({managed,summary});sawRemoved+=summary.removed;if(managed.isFile){const moved=summary.added+summary.changed>0;console.log(` ${managed.label.padEnd(10)} ${moved?"would update":"unchanged"}`)}else if(summary.added+summary.changed+summary.removed===0){console.log(` ${managed.label.padEnd(10)} unchanged (${summary.unchanged} files)`)}else{console.log(` ${managed.label.padEnd(10)} +${summary.added} ~${summary.changed} -${summary.removed} (${summary.unchanged} unchanged)`);const samples=[...summary.addedFiles.map((f)=>`+ ${f}`),...summary.changedFiles.map((f)=>`~ ${f}`)];for(const line of samples.slice(0,8))console.log(` ${line}`);if(samples.length>8)console.log(` ... and ${samples.length-8} more`)}}const sourcePkgPath=usingLocal&&detectedLocal?join(detectedLocal,"storage/framework/core/buddy/package.json"):repoTmp?join(repoTmp,"storage/framework/core/buddy/package.json"):join(tmpBase,"core","buddy","package.json");sourceVersion=readVersion(sourcePkgPath)}finally{rmSync(tmpBase,{recursive:true,force:true})}console.log("");if(currentVersion||sourceVersion){console.log(currentVersion===sourceVersion?` version: unchanged (v${currentVersion??"unknown"})`:` version: v${currentVersion??"unknown"} -> v${sourceVersion??"unknown"}`)}console.log(`
|
|
4
|
+
A real run would:`);console.log(" - sync the managed paths above into place");if(!ctx.targetVersion){console.log(` - write channel "${ctx.channel}" to .stacks-channel`);console.log(previewSha?` - record synced sha ${previewSha.slice(0,7)} in .stacks-version`:" - record the resolved commit sha in .stacks-version (unavailable in this preview)")}const runHooks=!options.noPostinstall&&options.postinstall!==false;if(!runHooks){console.log(" - skip post-sync hooks (--no-postinstall)")}else if(aggregate.added+aggregate.changed+aggregate.removed===0&&!options.force){console.log(" - skip post-sync hooks (nothing changed)")}else{console.log(" - regenerate the auto-import manifest");const corePkgChanged=perPath.some((entry)=>{const{managed,summary}=entry;if(managed.isFile)return false;if(managed.label!=="core"&&managed.label!=="defaults")return false;if(summary.added+summary.changed===0)return false;return pkgJsonInTree(join(projectRoot,managed.localPath))});if(shouldRefreshPostSyncDependencies(corePkgChanged,!!options.force)){const installer=detectDependencyInstaller(existsSync(join(projectRoot,"pantry.lock")));console.log(` - run \`${installer} install --force\` to refresh dependencies`)}if(existsSync(join(projectRoot,"database","types.d.ts")))console.log(" - regenerate database/types.d.ts");if(existsSync(join(projectRoot,"database","migrations")))console.log(" - run pending migrations");console.log(` - refresh AI setup for ${detectProjectAiProviders(projectRoot).join(", ")} (including bundled skills)`)}if(sawRemoved>0)console.log(`
|
|
5
|
+
(-N counts files no longer shipped upstream; the sync leaves them in place.)`);console.log(`
|
|
6
|
+
✔ Dry run complete. No changes were made.`)}export async function detectDirtyManagedPaths(root){const gitDir=join(root,".git");if(!existsSync(gitDir))return[];try{const proc=Bun.spawn({cmd:["git","-C",root,"status","--porcelain","--",...MANAGED_PATHS.map((m)=>m.localPath)],stdout:"pipe",stderr:"pipe"});const output=await new Response(proc.stdout).text();await proc.exited;return output.split(`
|
|
7
|
+
`).filter((line)=>line.length>0).map((line)=>line.slice(3))}catch{return[]}}export async function getRemoteSha(context,fromLocal,stacksRoot){const SHA_RE=/^[0-9a-f]{40}$/i;try{if(fromLocal&&stacksRoot){const head=Bun.spawn({cmd:["git","-C",stacksRoot,"rev-parse","HEAD"],stdout:"pipe",stderr:"pipe"});const h=(await new Response(head.stdout).text()).trim();return await head.exited===0&&SHA_RE.test(h)?h.toLowerCase():null}const proc=Bun.spawn({cmd:["git","ls-remote","https://github.com/stacksjs/stacks.git",`refs/heads/${context.ref}`,`refs/tags/${context.ref}`,`refs/tags/${context.ref}^{}`],stdout:"pipe",stderr:"pipe"});const out=await new Response(proc.stdout).text();if(await proc.exited!==0)return null;const lines=out.split(`
|
|
8
|
+
`).filter(Boolean);const deref=lines.find((l)=>l.includes("^{}"));const chosen=deref??lines[0];const m=chosen?.match(/^([0-9a-f]{40})\s/i);return m?.[1]?m[1].toLowerCase():null}catch{return null}}export async function singleFileSnapshot(absPath){const out=new Map;if(!existsSync(absPath))return out;try{const file=Bun.file(absPath);if(file.size>0){const buf=await file.arrayBuffer();out.set("self",{size:file.size,hash:Bun.hash(buf)})}}catch{}return out}export function pkgJsonInTree(dir){try{if(!existsSync(dir))return false;const top=readFileSync(join(dir,"package.json"),"utf-8");return top.length>0}catch{return existsSync(dir)}}
|
|
@@ -1,13 +1,6 @@
|
|
|
1
|
-
import{chmodSync,copyFileSync,cpSync,existsSync,mkdirSync,
|
|
1
|
+
import{chmodSync,copyFileSync,cpSync,existsSync,mkdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{downloadTemplate}from"@stacksjs/gitit";import{path as p}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{buildTemplateString,diffSnapshots,MANAGED_PATHS,readSyncedVersion,readVersion,resolveSuccessMessage,shouldCheckDirtyManagedPaths,shouldShortCircuit,snapshotTree,writeChannel,writeSyncedVersion}from"./framework-utils";import{detectDependencyInstaller,resolveDependencyRefreshCommand,resolvePantryExecutable,runPostSyncAiRefresh,runPostSyncDatabaseTypesRefresh,runPostSyncDependencyRefresh,runPostSyncMigration,shouldRefreshPostSyncDependencies,shouldRunPostSyncHooks}from"./framework-hooks";import{detectDirtyManagedPaths,getRemoteSha,pkgJsonInTree,previewFrameworkUpgrade,resolveFrameworkUpgrade,singleFileSnapshot}from"./framework-preview";import{describeDanglingRouteActions,findDanglingRouteActions,pruneRetiredScaffoldRoutes}from"./route-actions";const options=parseOptions();const alreadyRestarted=process.argv.includes("--__restarted");const projectRoot=p.projectPath();if(!existsSync(p.projectPath("storage/framework/core"))){const{upgradeStacksPackages}=await import("./packages");await upgradeStacksPackages(projectRoot,{version:options.version,canary:options.canary,stable:options.stable,force:options.force,dryRun:options.dryRun,noPostinstall:options.noPostinstall??options.postinstall===false,allowDowngrade:options.allowDowngrade,restarted:alreadyRestarted,changedBeforeRestart:process.argv.includes("--__upgrade-changed")});process.exit(ExitCode.Success)}const resolved=await resolveFrameworkUpgrade(projectRoot,options);const{channelFile,versionFile,currentChannel,corePkgPath,currentVersion,detectedLocal,usingLocal,ctx}=resolved;if(options.dryRun){await previewFrameworkUpgrade(projectRoot,options,resolved);process.exit(ExitCode.Success)}if(shouldCheckDirtyManagedPaths({force:!!options.force,alreadyRestarted})){const dirty=await detectDirtyManagedPaths(projectRoot);if(dirty.length>0){console.warn(`
|
|
2
2
|
⚠ The following framework-managed paths have uncommitted changes:`);for(const path of dirty)console.warn(` - ${path}`);console.warn(`
|
|
3
3
|
Aborting to avoid clobbering your edits.`);console.warn(` Re-run with --force to overwrite, or commit / stash the changes first.
|
|
4
4
|
`);process.exit(ExitCode.FatalError)}}let resolvedRemoteSha=null;if(!options.force&&!ctx.targetVersion){resolvedRemoteSha=await getRemoteSha(ctx,usingLocal,detectedLocal);const synced=readSyncedVersion(versionFile);if(shouldShortCircuit({force:!!options.force,targetVersion:ctx.targetVersion,remoteSha:resolvedRemoteSha,synced,channel:ctx.channel})){console.log(`✔ Already on the latest ${ctx.channel} (${resolvedRemoteSha.slice(0,7)}).`);process.exit(ExitCode.Success)}}const ownPath=p.frameworkPath("core/actions/src/upgrade/framework.ts");const ownHashBefore=await hashFileOrZero(ownPath);const aggregate={added:0,changed:0,removed:0,unchanged:0};const perPath=[];try{for(const managed of MANAGED_PATHS){const localTarget=join(projectRoot,managed.localPath);const before=managed.isFile?await singleFileSnapshot(localTarget):await snapshotTree(localTarget,managed.skip);if(usingLocal&&detectedLocal){await syncFromLocal(detectedLocal,managed,localTarget)}else{if(managed.isFile)continue;await syncFromGitHub(ctx.ref,managed,localTarget,!!options.force)}const after=managed.isFile?await singleFileSnapshot(localTarget):await snapshotTree(localTarget,managed.skip);const summary=diffSnapshots(before,after);aggregate.added+=summary.added;aggregate.changed+=summary.changed;aggregate.removed+=summary.removed;aggregate.unchanged+=summary.unchanged;perPath.push({managed,summary})}if(!usingLocal){await syncRootFilesFromGitHub(ctx.ref)}}catch(err){console.error("✘ Failed to upgrade Stacks framework:",err?.message||err);process.exit(ExitCode.FatalError)}const newVersion=readVersion(corePkgPath);const ownHashAfter=await hashFileOrZero(ownPath);if(ownHashBefore!==0n&&ownHashAfter!==0n&&ownHashBefore!==ownHashAfter&&!alreadyRestarted){console.log(`Upgrade pulled a newer version of the upgrade action - re-running once to pick up new sync paths and hooks.
|
|
5
5
|
`);const args=process.argv.slice(2).filter((a)=>a!=="--__restarted");const proc=Bun.spawn({cmd:[process.argv[0]||"bun",ownPath,...args,"--__restarted"],cwd:projectRoot,stdout:"inherit",stderr:"inherit"});const code=await proc.exited;process.exit(code??0)}console.log("Sync summary:");for(const{managed,summary}of perPath){if(managed.isFile){const moved=summary.added+summary.changed>0;console.log(` ${managed.label.padEnd(10)} ${moved?"updated":"unchanged"}`)}else{const noop=summary.added+summary.changed+summary.removed===0;if(noop){console.log(` ${managed.label.padEnd(10)} unchanged (${summary.unchanged} files)`)}else{console.log(` ${managed.label.padEnd(10)} +${summary.added} ~${summary.changed} -${summary.removed} (${summary.unchanged} unchanged)`)}}}{const pruned=pruneRetiredScaffoldRoutes(projectRoot);for(const route of pruned)console.log(`Removed ${route.file}:${route.line}, the scaffold route to ${route.action}: removed in ${route.removedIn}, ${route.reason}`);const dangling=findDanglingRouteActions(projectRoot);if(dangling.length>0){console.warn(`${dangling.length} route(s) name an action this version does not ship. Point them at an action that exists, or delete them:`);for(const line of describeDanglingRouteActions(dangling).split(`
|
|
6
|
-
`))console.warn(` ${line}`)}}const runHooks=!options.noPostinstall&&options.postinstall!==false;if(runHooks){try{await runPostSyncHooks({aggregate,perPath,projectRoot,alreadyRestarted:alreadyRestarted||!!options.force})}catch(err){console.error(`Post-sync hooks failed: ${err?.message||err}`);process.exit(ExitCode.FatalError)}}if(!ctx.targetVersion){writeChannel(channelFile,ctx.channel);if(!resolvedRemoteSha)resolvedRemoteSha=await getRemoteSha(ctx,usingLocal,detectedLocal);if(resolvedRemoteSha)writeSyncedVersion(versionFile,ctx.channel,resolvedRemoteSha)}console.log(`✔ ${resolveSuccessMessage(ctx,currentVersion,newVersion,currentChannel,!!options.force)}`);if(ctx.channel==="canary"&&!ctx.targetVersion){console.warn("⚠ Canary builds may contain bugs or breaking changes. Not recommended for production.")}process.exit(ExitCode.Success);async function
|
|
7
|
-
DRY RUN - preview only. No files will be written, nothing will be installed, no migrations will run.
|
|
8
|
-
`);const dirty=await detectDirtyManagedPaths(projectRoot);if(dirty.length>0){console.warn(" Note: these framework-managed paths have uncommitted changes (a real run would abort without --force):");for(const path of dirty)console.warn(` - ${path}`);console.warn("")}let previewSha=null;if(!options.force&&!ctx.targetVersion){previewSha=await getRemoteSha(ctx,usingLocal,detectedLocal);const synced=readSyncedVersion(versionFile);if(shouldShortCircuit({force:!!options.force,targetVersion:ctx.targetVersion,remoteSha:previewSha,synced,channel:ctx.channel})){console.log(`✔ Already on the latest ${ctx.channel} (${previewSha.slice(0,7)}). A real run would change nothing.`);return}}const aggregate={added:0,changed:0,removed:0,unchanged:0};const perPath=[];let sawRemoved=0;let sourceVersion=null;const tmpBase=mkdtempSync(join(tmpdir(),"stacks-upgrade-dry-run-"));try{let repoTmp=null;for(const managed of MANAGED_PATHS){const localTarget=join(projectRoot,managed.localPath);const before=managed.isFile?await singleFileSnapshot(localTarget):await snapshotTree(localTarget,managed.skip);let after;if(usingLocal&&detectedLocal){const src=join(detectedLocal,managed.subPath);if(!existsSync(src)){console.log(` ${managed.label.padEnd(10)} skip: source missing at ${src}`);continue}after=managed.isFile?await singleFileSnapshot(src):await snapshotTree(src,managed.skip)}else{try{if(managed.isFile){if(!repoTmp){repoTmp=join(tmpBase,"repo");await downloadTemplate(`github:stacksjs/stacks#${ctx.ref}`,{dir:repoTmp,force:true,forceClean:true,preferOffline:true,silent:true})}after=await singleFileSnapshot(join(repoTmp,managed.subPath))}else{const dir=join(tmpBase,managed.label);await downloadTemplate(buildTemplateString(ctx.ref,managed.subPath),{dir,force:true,forceClean:true,preferOffline:!options.force,silent:true});after=await snapshotTree(dir,managed.skip)}}catch(err){console.log(` ${managed.label.padEnd(10)} preview unavailable (${err?.message||err}); a real run would sync from github:stacksjs/stacks#${ctx.ref}`);continue}}const summary=diffSnapshotsDetailed(before,after);aggregate.added+=summary.added;aggregate.changed+=summary.changed;aggregate.removed+=summary.removed;aggregate.unchanged+=summary.unchanged;perPath.push({managed,summary});sawRemoved+=summary.removed;if(managed.isFile){const moved=summary.added+summary.changed>0;console.log(` ${managed.label.padEnd(10)} ${moved?"would update":"unchanged"}`)}else if(summary.added+summary.changed+summary.removed===0){console.log(` ${managed.label.padEnd(10)} unchanged (${summary.unchanged} files)`)}else{console.log(` ${managed.label.padEnd(10)} +${summary.added} ~${summary.changed} -${summary.removed} (${summary.unchanged} unchanged)`);const samples=[...summary.addedFiles.map((f)=>`+ ${f}`),...summary.changedFiles.map((f)=>`~ ${f}`)];for(const line of samples.slice(0,8))console.log(` ${line}`);if(samples.length>8)console.log(` ... and ${samples.length-8} more`)}}const sourcePkgPath=usingLocal&&detectedLocal?join(detectedLocal,"storage/framework/core/buddy/package.json"):repoTmp?join(repoTmp,"storage/framework/core/buddy/package.json"):join(tmpBase,"core","buddy","package.json");sourceVersion=readVersion(sourcePkgPath)}finally{rmSync(tmpBase,{recursive:true,force:true})}console.log("");if(currentVersion||sourceVersion){console.log(currentVersion===sourceVersion?` version: unchanged (v${currentVersion??"unknown"})`:` version: v${currentVersion??"unknown"} -> v${sourceVersion??"unknown"}`)}console.log(`
|
|
9
|
-
A real run would:`);console.log(" - sync the managed paths above into place");if(!ctx.targetVersion){console.log(` - write channel "${ctx.channel}" to .stacks-channel`);console.log(previewSha?` - record synced sha ${previewSha.slice(0,7)} in .stacks-version`:" - record the resolved commit sha in .stacks-version (unavailable in this preview)")}const runHooks=!options.noPostinstall&&options.postinstall!==false;if(!runHooks){console.log(" - skip post-sync hooks (--no-postinstall)")}else if(aggregate.added+aggregate.changed+aggregate.removed===0&&!options.force){console.log(" - skip post-sync hooks (nothing changed)")}else{console.log(" - regenerate the auto-import manifest");const corePkgChanged=perPath.some((entry)=>{const{managed,summary}=entry;if(managed.isFile)return false;if(managed.label!=="core"&&managed.label!=="defaults")return false;if(summary.added+summary.changed===0)return false;return pkgJsonInTree(join(projectRoot,managed.localPath))});if(shouldRefreshPostSyncDependencies(corePkgChanged,!!options.force)){const installer=detectDependencyInstaller(existsSync(join(projectRoot,"pantry.lock")));console.log(` - run \`${installer} install --force\` to refresh dependencies`)}if(existsSync(join(projectRoot,"database","types.d.ts")))console.log(" - regenerate database/types.d.ts");if(existsSync(join(projectRoot,"database","migrations")))console.log(" - run pending migrations");console.log(` - refresh AI setup for ${detectProjectAiProviders(projectRoot).join(", ")} (including bundled skills)`)}if(sawRemoved>0)console.log(`
|
|
10
|
-
(-N counts files no longer shipped upstream; the sync leaves them in place.)`);console.log(`
|
|
11
|
-
✔ Dry run complete. No changes were made.`)}async function detectDirtyManagedPaths(root){const gitDir=join(root,".git");if(!existsSync(gitDir))return[];try{const proc=Bun.spawn({cmd:["git","-C",root,"status","--porcelain","--",...MANAGED_PATHS.map((m)=>m.localPath)],stdout:"pipe",stderr:"pipe"});const output=await new Response(proc.stdout).text();await proc.exited;return output.split(`
|
|
12
|
-
`).filter((line)=>line.length>0).map((line)=>line.slice(3))}catch{return[]}}async function getRemoteSha(context,fromLocal,stacksRoot){const SHA_RE=/^[0-9a-f]{40}$/i;try{if(fromLocal&&stacksRoot){const head=Bun.spawn({cmd:["git","-C",stacksRoot,"rev-parse","HEAD"],stdout:"pipe",stderr:"pipe"});const h=(await new Response(head.stdout).text()).trim();return await head.exited===0&&SHA_RE.test(h)?h.toLowerCase():null}const proc=Bun.spawn({cmd:["git","ls-remote","https://github.com/stacksjs/stacks.git",`refs/heads/${context.ref}`,`refs/tags/${context.ref}`,`refs/tags/${context.ref}^{}`],stdout:"pipe",stderr:"pipe"});const out=await new Response(proc.stdout).text();if(await proc.exited!==0)return null;const lines=out.split(`
|
|
13
|
-
`).filter(Boolean);const deref=lines.find((l)=>l.includes("^{}"));const chosen=deref??lines[0];const m=chosen?.match(/^([0-9a-f]{40})\s/i);return m?.[1]?m[1].toLowerCase():null}catch{return null}}async function hashFileOrZero(absPath){try{if(!existsSync(absPath))return 0n;const buf=await Bun.file(absPath).arrayBuffer();return Bun.hash(buf)}catch{return 0n}}async function singleFileSnapshot(absPath){const out=new Map;if(!existsSync(absPath))return out;try{const file=Bun.file(absPath);if(file.size>0){const buf=await file.arrayBuffer();out.set("self",{size:file.size,hash:Bun.hash(buf)})}}catch{}return out}async function syncFromLocal(stacksRoot,managed,localTarget){const src=join(stacksRoot,managed.subPath);if(!existsSync(src)){console.warn(` skip ${managed.label}: source missing at ${src}`);return}if(managed.isFile){mkdirSync(dirname(localTarget),{recursive:true});copyFileSync(src,localTarget);if(managed.executable)chmodSync(localTarget,493);return}mkdirSync(localTarget,{recursive:true});cpSync(src,localTarget,{recursive:true,force:true,filter:(source)=>{if(!managed.skip)return true;const name=source.split("/").pop()||"";return!managed.skip.includes(name)}})}async function syncFromGitHub(ref,managed,localTarget,force){const kept=new Map;for(const name of managed.skip??[]){const file=join(localTarget,name);try{if(existsSync(file)&&statSync(file).isFile())kept.set(file,readFileSync(file))}catch{}}const template=buildTemplateString(ref,managed.subPath);await downloadTemplate(template,{dir:localTarget,force:true,forceClean:false,preferOffline:!force});for(const[file,contents]of kept)writeFileSync(file,contents)}async function syncRootFilesFromGitHub(ref){const tmpDir=p.projectPath(".tmp-upgrade");try{await downloadTemplate(`github:stacksjs/stacks#${ref}`,{dir:tmpDir,force:true,forceClean:true,preferOffline:true,silent:true});for(const managed of MANAGED_PATHS){if(!managed.isFile)continue;const src=join(tmpDir,managed.subPath);const dest=p.projectPath(managed.localPath);try{if(existsSync(src)&&existsSync(dest)){copyFileSync(src,dest);if(managed.executable)chmodSync(dest,493)}}catch{}}}catch{}finally{if(existsSync(tmpDir))rmSync(tmpDir,{recursive:true,force:true})}}async function runPostSyncHooks(args){const{aggregate,perPath,projectRoot,alreadyRestarted}=args;const changeCount=aggregate.added+aggregate.changed+aggregate.removed;if(!shouldRunPostSyncHooks(changeCount,alreadyRestarted)){console.log("Nothing changed - skipping post-sync hooks.");return}console.log("Regenerating auto-import manifest...");try{const{generateAutoImportFiles}=await import("@stacksjs/server");await generateAutoImportFiles()}catch(err){console.warn(` auto-imports failed (non-fatal): ${err?.message||err}`)}const corePkgChanged=shouldRefreshPostSyncDependencies(perPath.some((entry)=>{const{managed,summary}=entry;if(managed.isFile)return false;if(managed.label!=="core"&&managed.label!=="defaults")return false;if(summary.added+summary.changed===0)return false;return pkgJsonInTree(join(projectRoot,managed.localPath))}),alreadyRestarted);if(corePkgChanged){const installer=detectDependencyInstaller(existsSync(join(projectRoot,"pantry.lock")));const cmd=resolveDependencyRefreshCommand({installer,bunExecutable:process.argv[0]||"bun",pantryExecutable:resolvePantryExecutable(pantryExecutableCandidates(projectRoot),existsSync)});console.log(`Running \`${installer} install\` to refresh dependencies...`);try{await runPostSyncDependencyRefresh({cmd,projectRoot,spawn:(spawnOptions)=>Bun.spawn(spawnOptions)})}catch(err){console.warn(` ${installer} install failed (non-fatal): ${err?.message||err}`)}}try{const refreshed=await runPostSyncDatabaseTypesRefresh({cmd:[process.argv[0]||"bun",p.frameworkPath("core/buddy/src/cli.ts"),"generate:db-types"],projectRoot,spawn:(spawnOptions)=>Bun.spawn(spawnOptions),exists:existsSync});if(refreshed)console.log("Regenerated database/types.d.ts")}catch(err){console.warn(` database/types.d.ts was not regenerated (non-fatal): ${err?.message||err}`)}const migrationsDir=join(projectRoot,"database","migrations");if(existsSync(migrationsDir)){console.log("Running pending migrations...");const migrateScript=p.frameworkPath("core/buddy/src/cli.ts");await runPostSyncMigration({bunExecutable:process.argv[0]||"bun",migrateScript,projectRoot,spawn:(spawnOptions)=>Bun.spawn(spawnOptions)})}console.log("Refreshing AI setup and bundled skills...");await runPostSyncAiRefresh({cli:[process.argv[0]||"bun",p.frameworkPath("core/buddy/src/cli.ts")],projectRoot,spawn:(spawnOptions)=>Bun.spawn(spawnOptions)})}function pantryExecutableCandidates(projectRoot){const home=process.env.HOME??"";return[join(projectRoot,"pantry",".bin","pantry"),home?join(home,".local","bin","pantry"):"",home?join(home,".local","share","pantry","global","bin","pantry"):""].filter(Boolean)}function pkgJsonInTree(dir){try{if(!existsSync(dir))return false;const top=readFileSync(join(dir,"package.json"),"utf-8");return top.length>0}catch{return existsSync(dir)}}
|
|
6
|
+
`))console.warn(` ${line}`)}}const runHooks=!options.noPostinstall&&options.postinstall!==false;if(runHooks){try{await runPostSyncHooks({aggregate,perPath,projectRoot,alreadyRestarted:alreadyRestarted||!!options.force})}catch(err){console.error(`Post-sync hooks failed: ${err?.message||err}`);process.exit(ExitCode.FatalError)}}if(!ctx.targetVersion){writeChannel(channelFile,ctx.channel);if(!resolvedRemoteSha)resolvedRemoteSha=await getRemoteSha(ctx,usingLocal,detectedLocal);if(resolvedRemoteSha)writeSyncedVersion(versionFile,ctx.channel,resolvedRemoteSha)}console.log(`✔ ${resolveSuccessMessage(ctx,currentVersion,newVersion,currentChannel,!!options.force)}`);if(ctx.channel==="canary"&&!ctx.targetVersion){console.warn("⚠ Canary builds may contain bugs or breaking changes. Not recommended for production.")}process.exit(ExitCode.Success);async function hashFileOrZero(absPath){try{if(!existsSync(absPath))return 0n;const buf=await Bun.file(absPath).arrayBuffer();return Bun.hash(buf)}catch{return 0n}}async function syncFromLocal(stacksRoot,managed,localTarget){const src=join(stacksRoot,managed.subPath);if(!existsSync(src)){console.warn(` skip ${managed.label}: source missing at ${src}`);return}if(managed.isFile){mkdirSync(dirname(localTarget),{recursive:true});copyFileSync(src,localTarget);if(managed.executable)chmodSync(localTarget,493);return}mkdirSync(localTarget,{recursive:true});cpSync(src,localTarget,{recursive:true,force:true,filter:(source)=>{if(!managed.skip)return true;const name=source.split("/").pop()||"";return!managed.skip.includes(name)}})}async function syncFromGitHub(ref,managed,localTarget,force){const kept=new Map;for(const name of managed.skip??[]){const file=join(localTarget,name);try{if(existsSync(file)&&statSync(file).isFile())kept.set(file,readFileSync(file))}catch{}}const template=buildTemplateString(ref,managed.subPath);await downloadTemplate(template,{dir:localTarget,force:true,forceClean:false,preferOffline:!force});for(const[file,contents]of kept)writeFileSync(file,contents)}async function syncRootFilesFromGitHub(ref){const tmpDir=p.projectPath(".tmp-upgrade");try{await downloadTemplate(`github:stacksjs/stacks#${ref}`,{dir:tmpDir,force:true,forceClean:true,preferOffline:true,silent:true});for(const managed of MANAGED_PATHS){if(!managed.isFile)continue;const src=join(tmpDir,managed.subPath);const dest=p.projectPath(managed.localPath);try{if(existsSync(src)&&existsSync(dest)){copyFileSync(src,dest);if(managed.executable)chmodSync(dest,493)}}catch{}}}catch{}finally{if(existsSync(tmpDir))rmSync(tmpDir,{recursive:true,force:true})}}async function runPostSyncHooks(args){const{aggregate,perPath,projectRoot,alreadyRestarted}=args;const changeCount=aggregate.added+aggregate.changed+aggregate.removed;if(!shouldRunPostSyncHooks(changeCount,alreadyRestarted)){console.log("Nothing changed - skipping post-sync hooks.");return}console.log("Regenerating auto-import manifest...");try{const{generateAutoImportFiles}=await import("@stacksjs/server");await generateAutoImportFiles()}catch(err){console.warn(` auto-imports failed (non-fatal): ${err?.message||err}`)}const corePkgChanged=shouldRefreshPostSyncDependencies(perPath.some((entry)=>{const{managed,summary}=entry;if(managed.isFile)return false;if(managed.label!=="core"&&managed.label!=="defaults")return false;if(summary.added+summary.changed===0)return false;return pkgJsonInTree(join(projectRoot,managed.localPath))}),alreadyRestarted);if(corePkgChanged){const installer=detectDependencyInstaller(existsSync(join(projectRoot,"pantry.lock")));const cmd=resolveDependencyRefreshCommand({installer,bunExecutable:process.argv[0]||"bun",pantryExecutable:resolvePantryExecutable(pantryExecutableCandidates(projectRoot),existsSync)});console.log(`Running \`${installer} install\` to refresh dependencies...`);try{await runPostSyncDependencyRefresh({cmd,projectRoot,spawn:(spawnOptions)=>Bun.spawn(spawnOptions)})}catch(err){console.warn(` ${installer} install failed (non-fatal): ${err?.message||err}`)}}try{const refreshed=await runPostSyncDatabaseTypesRefresh({cmd:[process.argv[0]||"bun",p.frameworkPath("core/buddy/src/cli.ts"),"generate:db-types"],projectRoot,spawn:(spawnOptions)=>Bun.spawn(spawnOptions),exists:existsSync});if(refreshed)console.log("Regenerated database/types.d.ts")}catch(err){console.warn(` database/types.d.ts was not regenerated (non-fatal): ${err?.message||err}`)}const migrationsDir=join(projectRoot,"database","migrations");if(existsSync(migrationsDir)){console.log("Running pending migrations...");const migrateScript=p.frameworkPath("core/buddy/src/cli.ts");await runPostSyncMigration({bunExecutable:process.argv[0]||"bun",migrateScript,projectRoot,spawn:(spawnOptions)=>Bun.spawn(spawnOptions)})}console.log("Refreshing AI setup and bundled skills...");await runPostSyncAiRefresh({cli:[process.argv[0]||"bun",p.frameworkPath("core/buddy/src/cli.ts")],projectRoot,spawn:(spawnOptions)=>Bun.spawn(spawnOptions)})}function pantryExecutableCandidates(projectRoot){const home=process.env.HOME??"";return[join(projectRoot,"pantry",".bin","pantry"),home?join(home,".local","bin","pantry"):"",home?join(home,".local","share","pantry","global","bin","pantry"):""].filter(Boolean)}
|
package/dist/upgrade/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{
|
|
1
|
+
import process from"node:process";import{parseOptions}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";import{runUpgrade}from"./run";const options=parseOptions();const result=await runUpgrade(options);process.exit(result.isErr?ExitCode.FatalError:ExitCode.Success);
|
|
@@ -100,9 +100,10 @@ export declare function applyBumps(pkg: PkgJson, target: string, lockstep: Set<s
|
|
|
100
100
|
/**
|
|
101
101
|
* Upgrade a node_modules app to a published framework version. Called by the
|
|
102
102
|
* framework upgrade script when no vendored `storage/framework/core` exists.
|
|
103
|
-
* Handles resolution, package.json rewrite, and
|
|
103
|
+
* Handles resolution, package.json rewrite, reinstall and target-owned migration.
|
|
104
|
+
* Returns after success so a native action sequence can continue its next stage.
|
|
104
105
|
*/
|
|
105
|
-
export declare function upgradeStacksPackages(projectRoot: string, options: PackageUpgradeOptions): Promise<
|
|
106
|
+
export declare function upgradeStacksPackages(projectRoot: string, options: PackageUpgradeOptions): Promise<void>;
|
|
106
107
|
/*` package rides the framework version, though, and the
|
|
107
108
|
* doc above used to describe a guard the code did not have: without `context`
|
|
108
109
|
* this rewrote `@stacksjs/bun-router: ^0.0.20` to `^0.72.4`, a version that
|
|
@@ -149,6 +150,8 @@ export declare interface PackageUpgradeOptions {
|
|
|
149
150
|
dryRun?: boolean
|
|
150
151
|
noPostinstall?: boolean
|
|
151
152
|
allowDowngrade?: boolean
|
|
153
|
+
restarted?: boolean
|
|
154
|
+
changedBeforeRestart?: boolean
|
|
152
155
|
}
|
|
153
156
|
export declare interface PkgJson {
|
|
154
157
|
dependencies?: Record<string, string>
|
package/dist/upgrade/packages.js
CHANGED
|
@@ -1,33 +1,60 @@
|
|
|
1
|
-
import{existsSync,lstatSync,readdirSync,readFileSync,writeFileSync}from"node:fs";import{join,relative}from"node:path";import process from"node:process";import{runCommand}from"@stacksjs/cli";import{installedDefaultsVersion}from"@stacksjs/path";import{runPostSyncAiRefresh,runPostSyncDatabaseTypesRefresh}from"./framework-hooks";import{measureDefaultsDrift,migratePackageProjectManifest,migratePackageProjectTsconfig,summarizeStructureChanges,syncPackageProjectFiles}from"./package-project";import{describeDanglingRouteActions,findDanglingRouteActions,pruneRetiredScaffoldRoutes}from"./route-actions";export function hasStacksDependency(pkg){return Boolean(pkg.dependencies?.stacks||pkg.devDependencies?.stacks)}export function standalonePackageUpdateCommand(){return"bun update"}export function frameworkPackageUpdateCommand(target,force=false){if(!/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(target))throw new Error("The framework install target must be a published version.");return`bun update stacks@${target}${force?" --force":""}`}export function installedStacksVersion(projectRoot){try{const manifest=JSON.parse(readFileSync(join(projectRoot,"node_modules/stacks/package.json"),"utf-8"));return typeof manifest.version==="string"?manifest.version:null}catch{return null}}export function needsFrameworkInstall(projectRoot,target,runtimePins={}){try{const metaRoot=join(projectRoot,"node_modules/stacks");const installed=JSON.parse(readFileSync(join(metaRoot,"package.json"),"utf8"));if(installed.version!==target)return true;const projectPath=join(projectRoot,"package.json");const project=existsSync(projectPath)?JSON.parse(readFileSync(projectPath,"utf8")):{};const publishedRange=/^[\^~]?\d+\.\d+\.\d+(?:-[\w.-]+)?$/;const customResolution=(name)=>{const rule=project.overrides?.[name]??project.resolutions?.[name];return rule!==undefined&&(typeof rule!=="string"||!publishedRange.test(rule))};const lockPath=join(projectRoot,"bun.lock");if(existsSync(lockPath)){const lock=Bun.JSONC.parse(readFileSync(lockPath,"utf8"));if(lock.packages?.stacks?.[0]!==`stacks@${target}`)return true}for(const[name,version]of Object.entries(installed.dependencies??{})){if(!name.startsWith("@stacksjs/")||version!==target||customResolution(name))continue;const manifest=JSON.parse(readFileSync(Bun.resolveSync(`${name}/package.json`,metaRoot),"utf8"));if(manifest.version!==target)return true}if(Object.keys(runtimePins).length){const declared={...project.dependencies,...project.devDependencies};for(const[name,version]of Object.entries(runtimePins)){const spec=declared[name];if(typeof spec!=="string"||!publishedRange.test(spec)||customResolution(name))continue;const manifest=JSON.parse(readFileSync(Bun.resolveSync(`${name}/package.json`,projectRoot),"utf8"));if(manifest.version!==baseVersion(version))return true}}return false}catch{return true}}async function updateStandalonePackage(projectRoot,options){console.log(`
|
|
2
|
-
Standalone package detected. No Stacks framework source is installed.`);if(options.dryRun){console.log(" --dry-run: would refresh the package dependencies with `bun update`. No files were changed.\n");
|
|
1
|
+
import{existsSync,lstatSync,readdirSync,readFileSync,writeFileSync}from"node:fs";import{join,relative}from"node:path";import process from"node:process";import{buddyOptionArgs,runCommand}from"@stacksjs/cli";import{installedDefaultsVersion}from"@stacksjs/path";import{runPostSyncAiRefresh,runPostSyncDatabaseTypesRefresh}from"./framework-hooks";import{measureDefaultsDrift,migratePackageProjectManifest,migratePackageProjectTsconfig,summarizeStructureChanges,syncPackageProjectFiles}from"./package-project";import{describeDanglingRouteActions,findDanglingRouteActions,pruneRetiredScaffoldRoutes}from"./route-actions";export function hasStacksDependency(pkg){return Boolean(pkg.dependencies?.stacks||pkg.devDependencies?.stacks)}export function standalonePackageUpdateCommand(){return"bun update"}export function frameworkPackageUpdateCommand(target,force=false){if(!/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(target))throw new Error("The framework install target must be a published version.");return`bun update stacks@${target}${force?" --force":""}`}export function installedStacksVersion(projectRoot){try{const manifest=JSON.parse(readFileSync(join(projectRoot,"node_modules/stacks/package.json"),"utf-8"));return typeof manifest.version==="string"?manifest.version:null}catch{return null}}export function needsFrameworkInstall(projectRoot,target,runtimePins={}){try{const metaRoot=join(projectRoot,"node_modules/stacks");const installed=JSON.parse(readFileSync(join(metaRoot,"package.json"),"utf8"));if(installed.version!==target)return true;const projectPath=join(projectRoot,"package.json");const project=existsSync(projectPath)?JSON.parse(readFileSync(projectPath,"utf8")):{};const publishedRange=/^[\^~]?\d+\.\d+\.\d+(?:-[\w.-]+)?$/;const customResolution=(name)=>{const rule=project.overrides?.[name]??project.resolutions?.[name];return rule!==undefined&&(typeof rule!=="string"||!publishedRange.test(rule))};const lockPath=join(projectRoot,"bun.lock");if(existsSync(lockPath)){const lock=Bun.JSONC.parse(readFileSync(lockPath,"utf8"));if(lock.packages?.stacks?.[0]!==`stacks@${target}`)return true}for(const[name,version]of Object.entries(installed.dependencies??{})){if(!name.startsWith("@stacksjs/")||version!==target||customResolution(name))continue;const manifest=JSON.parse(readFileSync(Bun.resolveSync(`${name}/package.json`,metaRoot),"utf8"));if(manifest.version!==target)return true}if(Object.keys(runtimePins).length){const declared={...project.dependencies,...project.devDependencies};for(const[name,version]of Object.entries(runtimePins)){const spec=declared[name];if(typeof spec!=="string"||!publishedRange.test(spec)||customResolution(name))continue;const manifest=JSON.parse(readFileSync(Bun.resolveSync(`${name}/package.json`,projectRoot),"utf8"));if(manifest.version!==baseVersion(version))return true}}return false}catch{return true}}async function updateStandalonePackage(projectRoot,options){console.log(`
|
|
2
|
+
Standalone package detected. No Stacks framework source is installed.`);if(options.dryRun){console.log(" --dry-run: would refresh the package dependencies with `bun update`. No files were changed.\n");return}if(options.noPostinstall){console.log(" --no-postinstall: skipping the dependency refresh. Run `bun update` when ready.\n");return}console.log(` Refreshing declared dependencies...
|
|
3
3
|
`);const result=await runCommand(standalonePackageUpdateCommand(),{cwd:projectRoot});if(result.isErr){console.error("\n✗ The dependency refresh failed. Resolve the reported error and re-run `buddy update`.\n");process.exit(1)}console.log(`
|
|
4
4
|
✔ Standalone package dependencies are up to date.
|
|
5
|
-
`);
|
|
5
|
+
`);return}export function declaredPins(pkg,names){const declared={...pkg.devDependencies,...pkg.dependencies};const pins={};for(const name of names){const spec=declared[name];if(typeof spec==="string"&&/^[\^~]?\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(spec))pins[name]=baseVersion(spec)}return pins}async function resolveTarget(options){const res=await fetch("https://registry.npmjs.org/stacks").catch(()=>null);if(!res||!res.ok)throw new Error("Could not reach the npm registry to resolve the target `stacks` version.");const meta=await res.json();const distTags=meta["dist-tags"]??{};const versions=meta.versions??{};let version;if(options.version){if(!versions[options.version])throw new Error(`stacks@${options.version} was not found on the npm registry.`);version=options.version}else{const tag=options.canary?"canary":"latest";const resolved=distTags[tag];if(!resolved)throw new Error(`The \`${tag}\` dist-tag is not published for \`stacks\`.`);version=resolved}const metaDeps=versions[version]?.dependencies??{};const actions=await fetch(`https://registry.npmjs.org/@stacksjs%2factions/${version}`);if(!actions.ok)throw new Error(`Could not resolve the frontend dependencies shipped by @stacksjs/actions@${version}.`);const manifest=await actions.json();if(manifest.version!==version)throw new Error("The published actions manifest does not match the requested framework release.");return{version,metaDeps,runtimePins:await resolvePublishedRuntimePins(manifest.dependencies??{}),craftFloor:craftFloor(manifest)}}const RUNTIME_PACKAGES=["@stacksjs/stx","@stacksjs/components","bun-plugin-stx","@stacksjs/desktop","@stacksjs/sanitizer","stx-router"];const RUNTIME_COHORT=["@stacksjs/stx","@stacksjs/components","bun-plugin-stx"];export function publishedRuntimePins(dependencies){const exact=/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/;const pins={};for(const name of RUNTIME_PACKAGES){const version=dependencies[name];if(version&&exact.test(version))pins[name]=version}const floors=RUNTIME_COHORT.map((name)=>/^\^(\d+\.\d+\.\d+(?:-[\w.-]+)?)$/.exec(dependencies[name]??"")?.[1]);const floor=floors[0];if(floor&&floors.every((candidate)=>candidate===floor)){for(const name of RUNTIME_PACKAGES){if(dependencies[name]===`^${floor}`)pins[name]=floor}}return pins}export async function resolvePublishedRuntimePins(dependencies,read=fetch){const pins=publishedRuntimePins(dependencies);const version=pins["@stacksjs/stx"];if(!version)return pins;const response=await read(`https://registry.npmjs.org/@stacksjs%2fstx/${version}`);if(!response.ok)throw new Error(`Could not resolve the runtime dependencies shipped by @stacksjs/stx@${version}.`);const manifest=await response.json();if(manifest.name!=="@stacksjs/stx"||manifest.version!==version)throw new Error("The published STX manifest does not match the requested runtime release.");for(const[name,target]of Object.entries(publishedRuntimePins(manifest.dependencies??{}))){if(pins[name]&&pins[name]!==target)throw new Error(`The published framework and STX manifests disagree on ${name}.`);pins[name]=target}return pins}export function keepsNewerRelease(spec,target){const declared=baseVersion(spec);const plain=/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/;return plain.test(declared)&&plain.test(target)&&Bun.semver.order(declared,target)>=0&&Bun.semver.satisfies(declared,`^${target}`)}export function applyRuntimePins(pkg,pins,options={}){const changes=[];for(const field of["dependencies","devDependencies","overrides","resolutions"]){const declarations=pkg[field];if(!declarations||typeof declarations!=="object"||Array.isArray(declarations))continue;for(const[name,target]of Object.entries(pins)){const spec=declarations[name];if(typeof spec!=="string"||!/^[\^~]?\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(spec))continue;if(!options.exact&&keepsNewerRelease(spec,target))continue;const next=`${/^[\^~]/.test(spec)?spec[0]:""}${target}`;if(next===spec)continue;changes.push({name,from:spec,to:next,...field==="overrides"||field==="resolutions"?{field}:{}});declarations[name]=next}}return changes}export function isCraftPackage(name){return name==="craft-native"||/^@craft-native\/[a-z0-9][\w.-]*$/.test(name)}export function craftFloor(manifest){const range=manifest.peerDependencies?.["craft-native"]??manifest.dependencies?.["craft-native"];return range?.match(/^>=\s*(\d+\.\d+\.\d+)$/)?.[1]}export function declaredCraftPackages(pkg){const names=new Set;for(const field of["dependencies","devDependencies","overrides","resolutions"]){const declarations=pkg[field];if(declarations&&typeof declarations==="object"&&!Array.isArray(declarations))Object.keys(declarations).filter(isCraftPackage).forEach((name)=>names.add(name))}return[...names].sort()}export async function resolveCraftPins(pkg,floor,read=fetch){const pins={};if(!floor)return pins;for(const name of declaredCraftPackages(pkg)){const response=await read(`https://registry.npmjs.org/${name.replace("/","%2f")}/${floor}`).catch(()=>null);const manifest=response?.ok?await response.json().catch(()=>null):null;if(manifest?.name===name&&manifest.version===floor)pins[name]=floor;else console.warn(` ${name}@${floor} is not published; leaving ${name} as declared.`)}return pins}export function applyCraftFloor(pkg,pins){const changes=[];for(const field of["dependencies","devDependencies","overrides","resolutions"]){const declarations=pkg[field];if(!declarations||typeof declarations!=="object"||Array.isArray(declarations))continue;for(const[name,floor]of Object.entries(pins)){const spec=declarations[name];const match=typeof spec==="string"?/^(\^|~|>=\s*)?(\d+\.\d+\.\d+(?:-[\w.-]+)?)$/.exec(spec):null;if(!match||Bun.semver.order(match[2],floor)>=0)continue;const next=`${(match[1]??"").replace(/\s+/,"")}${floor}`;changes.push({name,from:spec,to:next,...field==="overrides"||field==="resolutions"?{field}:{}});declarations[name]=next}}return changes}export function lockfileVersion(projectRoot){const path=join(projectRoot,"bun.lock");if(!existsSync(path))return null;const match=/"lockfileVersion"\s*:\s*(\d+)/.exec(readFileSync(path,"utf8"));return match?Number(match[1]):null}export function lockfileOnlyAddCommands(pkg,names){const wanted=new Set(names);const commands=[];for(const[field,flag]of[["dependencies",""],["devDependencies"," --dev"]]){const specs=Object.entries(pkg[field]??{}).filter(([name,spec])=>wanted.has(name)&&/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(spec)&&/^(?:@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/.test(name)).map(([name,spec])=>`${name}@${spec}`);if(specs.length)commands.push(`bun add --exact --lockfile-only${flag} ${specs.join(" ")}`)}return commands}export function baseVersion(range){return range.replace(/^[\^~>=<\s]+/,"").trim()}export function isDowngrade(from,to){const before=baseVersion(from);const after=baseVersion(to);const plain=/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/;return plain.test(before)&&plain.test(after)&&Bun.semver.order(after,before)<0}export function lockstepPackages(metaDeps,target){const lockstep=new Set(["stacks"]);for(const[name,range]of Object.entries(metaDeps)){if(name.startsWith("@stacksjs/")&&baseVersion(range)===target)lockstep.add(name)}return lockstep}export function applyBumps(pkg,target,lockstep){const changes=[];for(const field of["dependencies","devDependencies"]){const deps=pkg[field];if(!deps)continue;for(const[name,spec]of Object.entries(deps)){if(!lockstep.has(name))continue;const prefix=/^[\^~]/.test(spec)?spec[0]:/^\d/.test(spec)?"":"^";const next=`${prefix}${target}`;if(spec!==next){changes.push({name,from:spec,to:next});deps[name]=next}}}for(const field of["overrides","resolutions"]){const rules=pkg[field];if(!rules||typeof rules!=="object"||Array.isArray(rules))continue;for(const[name,spec]of Object.entries(rules)){if(!lockstep.has(name)||typeof spec!=="string"||!/^[\^~]?\d/.test(spec))continue;const next=resolveManifestSpec(name,spec,target);if(!next)continue;changes.push({name,from:spec,to:next,field});rules[name]=next}}return changes}export async function upgradeStacksPackages(projectRoot,options){const pkgPath=join(projectRoot,"package.json");if(!existsSync(pkgPath)){console.error("No package.json found - nothing to upgrade.");process.exit(1)}const raw=readFileSync(pkgPath,"utf-8");const pkg=JSON.parse(raw);const current=pkg.dependencies?.stacks??pkg.devDependencies?.stacks;if(!hasStacksDependency(pkg))return updateStandalonePackage(projectRoot,options);const{version:target,metaDeps,runtimePins,craftFloor:floor}=await resolveTarget(options).catch((err)=>{console.error(`✗ ${err.message}`);process.exit(1)});const craftPins=await resolveCraftPins(pkg,floor);console.log(`
|
|
6
6
|
Upgrading the Stacks framework${options.canary?" (canary)":""} → ${target}`);if(current)console.log(` current \`stacks\` constraint: ${current}
|
|
7
|
-
`);const lockstep=lockstepPackages(metaDeps,target);const changes=[...applyBumps(pkg,target,lockstep),...applyRuntimePins(pkg,runtimePins,{exact:options.allowDowngrade}),...applyCraftFloor(pkg,craftPins)];const installedPins=declaredPins(pkg,[...Object.keys(runtimePins),...Object.keys(craftPins)]);const projectManifestChanges=migratePackageProjectManifest(pkg);const manifestContext={lockstep,metaDeps};const manifestChanges=reconcileVendoredManifests(projectRoot,target,{dryRun:true,context:manifestContext});const backwards=(change)=>isDowngrade(change.from,change.to);const forwards=changes.filter((change)=>!backwards(change));const downgrades=[...changes.filter(backwards).map((change)=>({...change,label:change.field?`${change.name} (${change.field})`:change.name,where:""})),...manifestChanges.filter(backwards).map((change)=>({...change,label:change.name,where:` ${change.file}`}))];if(forwards.length>0){console.log(" The following dependencies will be updated:");const reported=forwards.map((change)=>({...change,label:change.field?`${change.name} (${change.field})`:change.name}));const width=Math.max(...reported.map((c)=>c.label.length));for(const c of reported)console.log(` ${c.label.padEnd(width)} ${c.from} → ${c.to}`);console.log("")}const vendoredForwards=manifestChanges.filter((change)=>!backwards(change));if(vendoredForwards.length>0){console.log(` Vendored manifests under storage/framework (${vendoredForwards.length}):`);const width=Math.max(...vendoredForwards.map((c)=>c.name.length));for(const c of vendoredForwards)console.log(` ${c.name.padEnd(width)} ${c.from} → ${c.to} ${c.file}`);console.log("")}if(downgrades.length>0){const verb=options.allowDowngrade?"will be downgraded":"would be downgraded";console.log(` The following dependencies ${verb}, because stacks@${target} declares older versions than this app does:`);const width=Math.max(...downgrades.map((c)=>c.label.length));for(const c of downgrades)console.log(` ${c.label.padEnd(width)} ${c.from} → ${c.to} (downgrade)${c.where}`);console.log("");if(!options.allowDowngrade){const advice=options.version?[` --version ${target} asks for an older release than this app declares. Re-run with --allow-downgrade to confirm it.
|
|
7
|
+
`);const lockstep=lockstepPackages(metaDeps,target);const changes=[...applyBumps(pkg,target,lockstep),...applyRuntimePins(pkg,runtimePins,{exact:options.allowDowngrade}),...applyCraftFloor(pkg,craftPins)];const installedPins=declaredPins(pkg,[...Object.keys(runtimePins),...Object.keys(craftPins)]);const projectManifestChanges=options.restarted||options.dryRun||options.noPostinstall?migratePackageProjectManifest(pkg):[];const manifestContext={lockstep,metaDeps};const manifestChanges=reconcileVendoredManifests(projectRoot,target,{dryRun:true,context:manifestContext});const backwards=(change)=>isDowngrade(change.from,change.to);const forwards=changes.filter((change)=>!backwards(change));const downgrades=[...changes.filter(backwards).map((change)=>({...change,label:change.field?`${change.name} (${change.field})`:change.name,where:""})),...manifestChanges.filter(backwards).map((change)=>({...change,label:change.name,where:` ${change.file}`}))];if(forwards.length>0){console.log(" The following dependencies will be updated:");const reported=forwards.map((change)=>({...change,label:change.field?`${change.name} (${change.field})`:change.name}));const width=Math.max(...reported.map((c)=>c.label.length));for(const c of reported)console.log(` ${c.label.padEnd(width)} ${c.from} → ${c.to}`);console.log("")}const vendoredForwards=manifestChanges.filter((change)=>!backwards(change));if(vendoredForwards.length>0){console.log(` Vendored manifests under storage/framework (${vendoredForwards.length}):`);const width=Math.max(...vendoredForwards.map((c)=>c.name.length));for(const c of vendoredForwards)console.log(` ${c.name.padEnd(width)} ${c.from} → ${c.to} ${c.file}`);console.log("")}if(downgrades.length>0){const verb=options.allowDowngrade?"will be downgraded":"would be downgraded";console.log(` The following dependencies ${verb}, because stacks@${target} declares older versions than this app does:`);const width=Math.max(...downgrades.map((c)=>c.label.length));for(const c of downgrades)console.log(` ${c.label.padEnd(width)} ${c.from} → ${c.to} (downgrade)${c.where}`);console.log("");if(!options.allowDowngrade){const advice=options.version?[` --version ${target} asks for an older release than this app declares. Re-run with --allow-downgrade to confirm it.
|
|
8
8
|
`]:[` Wait for a framework release that declares these versions or newer, or re-run with --allow-downgrade to accept them.`,` Checking for one: \`npm view stacks versions\`, then \`buddy upgrade --version <version> --dry-run\`.
|
|
9
9
|
`];if(options.dryRun){console.log(` A real run refuses this upgrade unless --allow-downgrade is passed.`);console.log(advice.join(`
|
|
10
10
|
`))}else{console.error(`✗ Refusing to downgrade ${downgrades.length} ${downgrades.length===1?"dependency":"dependencies"}. Nothing was written or installed.`);console.error(advice.join(`
|
|
11
11
|
`));process.exit(1)}}}if(!options.dryRun&&manifestChanges.length>0)reconcileVendoredManifests(projectRoot,target,{context:manifestContext});if(projectManifestChanges.length>0)console.log(` Project manifest migrations: ${projectManifestChanges.length}
|
|
12
12
|
`);if(options.dryRun){const pending=measureDefaultsDrift(projectRoot);if(pending&&pending.length>0){const installed=installedDefaultsVersion(projectRoot);console.log(` Managed project files, against the installed @stacksjs/defaults${installed?` (${installed})`:""}:`);console.log(` ${summarizeStructureChanges(pending)} in storage/framework/defaults and project support files
|
|
13
13
|
`)}reportRouteActions(projectRoot,true);console.log(` --dry-run: no files were written and nothing was installed.
|
|
14
|
-
`);
|
|
14
|
+
`);return}if(changes.length>0||projectManifestChanges.length>0){const trailing=raw.endsWith(`
|
|
15
15
|
`)?`
|
|
16
16
|
`:"";writeFileSync(pkgPath,`${JSON.stringify(pkg,null,2)}${trailing}`);console.log("✔ Updated package.json")}if(options.noPostinstall){console.log(" --no-postinstall: skipping install. Run this to pull the new versions:");console.log(` ${frameworkPackageUpdateCommand(target)}
|
|
17
|
-
`);
|
|
17
|
+
`);return}const dependenciesNeedInstall=needsFrameworkInstall(projectRoot,target,installedPins);if(changes.length>0||manifestChanges.length>0||projectManifestChanges.length>0||dependenciesNeedInstall||options.force&&!options.restarted){console.log(` Installing…
|
|
18
18
|
`);const lockBefore=lockfileVersion(projectRoot);if(lockBefore!==null){for(const command of lockfileOnlyAddCommands(pkg,changes.filter((change)=>!change.field&&!lockstep.has(change.name)).map((change)=>change.name))){const added=await runCommand(command,{cwd:projectRoot});if(added.isErr){console.error(`
|
|
19
19
|
✗ \`${command}\` failed. Your package.json was updated - resolve the error and re-run \`buddy upgrade --version ${target}\`.
|
|
20
20
|
`);process.exit(1)}}}const result=await runCommand(frameworkPackageUpdateCommand(target,options.force),{cwd:projectRoot});const lockAfter=lockfileVersion(projectRoot);if(lockBefore!==null&&lockAfter!==null&&lockAfter!==lockBefore)console.warn(` bun.lock moved from lockfileVersion ${lockBefore} to ${lockAfter}. If CI or the server runs an older Bun, restore it (\`git checkout bun.lock\`) and re-resolve only the changed packages with \`bun add --exact --lockfile-only <package>@<version>\`.`);if(result.isErr){console.error(`
|
|
21
21
|
✗ The install step failed. Your package.json was updated - resolve the error and re-run \`buddy upgrade --version ${target}\`.
|
|
22
22
|
`);process.exit(1)}}const installed=installedStacksVersion(projectRoot);if(installed!==target){console.error(`
|
|
23
23
|
✗ Requested stacks@${target}, but the installed package reports ${installed??"no readable version"}. The installed files are retained for diagnosis; managed defaults were not synchronized.
|
|
24
|
-
`);process.exit(1)}
|
|
24
|
+
`);process.exit(1)}if(!options.restarted){const forwarded={...options};delete forwarded.restarted;delete forwarded.changedBeforeRestart;const changed=changes.length>0||manifestChanges.length>0||projectManifestChanges.length>0||dependenciesNeedInstall;const args=[...buddyOptionArgs({...forwarded,version:target}),"--__restarted",...changed?["--__upgrade-changed"]:[]];const entrypoint=`
|
|
25
|
+
const { readFileSync, realpathSync } = await import('node:fs')
|
|
26
|
+
const { dirname, isAbsolute, join, relative, sep } = await import('node:path')
|
|
27
|
+
const target = ${JSON.stringify(target)}
|
|
28
|
+
try {
|
|
29
|
+
const base = join(process.cwd(), 'node_modules/stacks')
|
|
30
|
+
const manifestPath = Bun.resolveSync('@stacksjs/actions/package.json', base)
|
|
31
|
+
const root = realpathSync(dirname(manifestPath))
|
|
32
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
|
|
33
|
+
if (manifest.name !== '@stacksjs/actions' || manifest.version !== target)
|
|
34
|
+
throw new Error('Requested stacks@' + target + ', but the installed @stacksjs/actions reports ' + String(manifest.version) + ' at ' + manifestPath + '.')
|
|
35
|
+
let entry
|
|
36
|
+
try { entry = realpathSync(Bun.resolveSync('@stacksjs/actions/upgrade/framework', base)) }
|
|
37
|
+
catch { throw new Error('The installed @stacksjs/actions@' + target + ' has no framework upgrade entry.') }
|
|
38
|
+
const path = relative(root, entry)
|
|
39
|
+
if (isAbsolute(path) || path.split(sep)[0] === '..')
|
|
40
|
+
throw new Error('The installed @stacksjs/actions@' + target + ' upgrade entry escapes its package.')
|
|
41
|
+
console.log(' Continuing with the installed upgrade actions at ' + target + '.\\n')
|
|
42
|
+
process.argv = [process.argv[0], entry, ...${JSON.stringify(args)}]
|
|
43
|
+
await import(entry)
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
console.error('\\n✗ ' + (error instanceof Error ? error.message : String(error)) + ' The installed files are retained; target migrations were not completed.\\n')
|
|
47
|
+
process.exit(1)
|
|
48
|
+
}
|
|
49
|
+
`;try{const child=Bun.spawn({cmd:["bun","-e",entrypoint],cwd:projectRoot,stdin:"inherit",stdout:"inherit",stderr:"inherit"});const code=await child.exited;if(code!==0)process.exit(code);return}catch(error){console.error(`
|
|
50
|
+
✗ ${error instanceof Error?error.message:String(error)} The installed files are retained; target migrations were not completed.
|
|
51
|
+
`);process.exit(1)}}const defaultsPackageRoot=join(projectRoot,"node_modules/@stacksjs/defaults");const structureChanges=existsSync(join(defaultsPackageRoot,"package.json"))?syncPackageProjectFiles(projectRoot,defaultsPackageRoot):[];const tsconfigChanges=migratePackageProjectTsconfig(projectRoot);const prunedRoutes=reportRouteActions(projectRoot,false);if(structureChanges.length>0||tsconfigChanges.length>0){const added=structureChanges.filter((change)=>change.action==="add").length;const updated=structureChanges.filter((change)=>change.action==="update").length+tsconfigChanges.length;const removed=structureChanges.filter((change)=>change.action==="remove").length;console.log(` Project structure: +${added} ~${updated} -${removed}`)}if(structureChanges.length>0)await regenerateAutoImports(projectRoot);if(changes.length>0||dependenciesNeedInstall||structureChanges.length>0||options.force||options.changedBeforeRestart)await regenerateDatabaseTypes(projectRoot);try{await runPostSyncAiRefresh({cli:["./buddy"],projectRoot,spawn:(spawnOptions)=>Bun.spawn(spawnOptions)})}catch(err){console.error(`
|
|
25
52
|
✗ ${err.message}
|
|
26
|
-
`);process.exit(1)}const didChange=changes.length>0||manifestChanges.length>0||projectManifestChanges.length>0||dependenciesNeedInstall||structureChanges.length>0||tsconfigChanges.length>0||prunedRoutes>0;if(!didChange&&!options.force)console.log(`
|
|
53
|
+
`);process.exit(1)}const didChange=changes.length>0||options.changedBeforeRestart||manifestChanges.length>0||projectManifestChanges.length>0||dependenciesNeedInstall||structureChanges.length>0||tsconfigChanges.length>0||prunedRoutes>0;if(!didChange&&!options.force)console.log(`
|
|
27
54
|
✔ Already up to date - dependencies and managed project files match the target.
|
|
28
55
|
`);else console.log(`
|
|
29
56
|
✔ Upgraded to stacks@${target}. Review the changelog: https://github.com/stacksjs/stacks/releases/tag/v${target}
|
|
30
|
-
`);
|
|
57
|
+
`);return}function reportRouteActions(projectRoot,dryRun){const pruned=pruneRetiredScaffoldRoutes(projectRoot,{dryRun});for(const route of pruned)console.log(` ${dryRun?"Would remove":"Removed"} ${route.file}:${route.line}, the scaffold route to ${route.action}: removed in ${route.removedIn}, ${route.reason}`);const dangling=findDanglingRouteActions(projectRoot);if(dangling.length>0){console.warn(`
|
|
31
58
|
${dangling.length} route${dangling.length===1?"":"s"} name${dangling.length===1?"s":""} an action this version does not ship. Point ${dangling.length===1?"it":"them"} at an action that exists, or delete ${dangling.length===1?"it":"them"}:`);for(const line of describeDanglingRouteActions(dangling).split(`
|
|
32
59
|
`))console.warn(` ${line}`);console.warn("")}return pruned.length}async function regenerateAutoImports(projectRoot){const proc=Bun.spawn({cmd:[process.execPath,"-e","await (await import('@stacksjs/server')).generateAutoImportFiles()"],cwd:projectRoot,stdout:"ignore",stderr:"pipe"});if(await proc.exited!==0){const stderr=(await new Response(proc.stderr).text()).trim();console.warn(` auto-imports were not regenerated (non-fatal): ${stderr.split(`
|
|
33
60
|
`).pop()||`exit ${proc.exitCode}`}`);return}console.log(" Regenerated auto-imports")}async function regenerateDatabaseTypes(projectRoot){const buddy=join(projectRoot,"buddy");if(!existsSync(buddy))return;try{const refreshed=await runPostSyncDatabaseTypesRefresh({cmd:[buddy,"generate:db-types"],projectRoot,spawn:(spawnOptions)=>Bun.spawn(spawnOptions),exists:existsSync});if(refreshed)console.log(" Regenerated database/types.d.ts")}catch(err){console.warn(` database/types.d.ts was not regenerated (non-fatal): ${err.message} Run \`./buddy generate:db-types\`.`)}}export function resolveManifestSpec(name,spec,target,context,members){if(name!=="stacks"&&!name.startsWith("@stacksjs/"))return null;if(spec.startsWith("workspace:")&&members?.has(name))return null;if(context&&!context.lockstep.has(name)){const declared=context.metaDeps[name];if(!declared)return null;return baseVersion(declared)===baseVersion(spec)?null:declared}if(spec.startsWith("workspace:"))return`^${target}`;if(baseVersion(spec)===target)return null;if(!/^[\^~]?\d/.test(spec))return null;const prefix=/^[\^~]/.test(spec)?spec[0]:"";return`${prefix}${target}`}export function workspaceMembers(projectRoot){const members=new Set;let patterns=[];try{const root=JSON.parse(readFileSync(join(projectRoot,"package.json"),"utf-8"));const declared=Array.isArray(root.workspaces)?root.workspaces:root.workspaces?.packages;patterns=(declared??[]).filter((one)=>typeof one==="string")}catch{return members}const manifestsFor=(pattern)=>{const glob=new Bun.Glob(`${pattern.replace(/\/+$/,"")}/package.json`);return[...glob.scanSync({cwd:projectRoot,onlyFiles:true})].filter((file)=>!file.split("/").includes("node_modules"))};const excluded=new Set(patterns.filter((one)=>one.startsWith("!")).flatMap((one)=>manifestsFor(one.slice(1))));for(const pattern of patterns.filter((one)=>!one.startsWith("!"))){for(const file of manifestsFor(pattern)){if(excluded.has(file))continue;try{const name=JSON.parse(readFileSync(join(projectRoot,file),"utf-8")).name;if(typeof name==="string"&&name)members.add(name)}catch{}}}return members}export function reconcileVendoredManifests(projectRoot,target,options={}){const root=join(projectRoot,"storage/framework");try{if(![join(projectRoot,"storage"),root].every((dir)=>lstatSync(dir).isDirectory()))return[]}catch{return[]}const changes=[];const members=workspaceMembers(projectRoot);const walk=(dir)=>{let entries;try{entries=readdirSync(dir)}catch{return}for(const entry of entries){if(entry==="node_modules"||entry==="dist"||entry===".git")continue;const full=join(dir,entry);let stat;try{stat=lstatSync(full)}catch{continue}if(stat.isSymbolicLink())continue;if(stat.isDirectory()){walk(full);continue}if(entry!=="package.json")continue;let raw;try{raw=readFileSync(full,"utf-8")}catch{continue}let pkg;try{pkg=JSON.parse(raw)}catch{continue}let touched=false;for(const field of["dependencies","devDependencies"]){const deps=pkg[field];if(!deps)continue;for(const[name,spec]of Object.entries(deps)){const next=resolveManifestSpec(name,spec,target,options.context,members);if(!next)continue;changes.push({file:relative(projectRoot,full),name,from:spec,to:next});deps[name]=next;touched=true}}if(touched&&!options.dryRun){const suffix=raw.endsWith(`
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { CommandError, UpgradeOptions } from '@stacksjs/types';
|
|
2
|
+
import type { Result } from '@stacksjs/error-handling';
|
|
3
|
+
/** Shared by the CLI and script dispatcher; the invoking release owns selection. */
|
|
4
|
+
export declare function runUpgrade(options: UpgradeOptions): Promise<Result<void, CommandError>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync}from"node:fs";import{join}from"node:path";import{Action}from"@stacksjs/enums";import{ok}from"@stacksjs/error-handling";import{projectPath}from"@stacksjs/path";import{print}from"@stacksjs/cli";import{runAction,runActionSequence}from"../helpers";import{upgradeStacksPackages}from"./packages";import{previewFrameworkUpgrade}from"./framework-preview";import{upgradeToolPreview}from"./tool-preview";export async function runUpgrade(options){const stages=[[options.framework,Action.UpgradeFramework],[options.dependencies,Action.UpgradeDeps],[options.bun,Action.UpgradeBun],[options.shell,Action.UpgradeShell],[options.binary,Action.UpgradeBinary]];const actions=stages.filter(([selected])=>selected||options.all).map(([,action])=>action);if(!actions.length)return ok(undefined);return runActionSequence(actions,options,async(action,stageOptions)=>{const root=options.cwd?String(options.cwd):projectPath();if(options.dryRun){if(action===Action.UpgradeFramework){if(existsSync(join(root,"storage/framework/core")))await previewFrameworkUpgrade(root,options);else await upgradeStacksPackages(root,options)}else{print(upgradeToolPreview(action))}return ok(undefined)}if(action===Action.UpgradeFramework&&!existsSync(join(root,"storage/framework/core"))){await upgradeStacksPackages(root,options);return ok(undefined)}return(await runAction(action,stageOptions)).map(()=>{})})}
|
package/dist/upgrade/shell.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$}from"bun";import process from"node:process";import{italic}from"@stacksjs/cli";import{log}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{writeFile}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";const homePath=(await $`echo $HOME`.text()).trim();const zshrcPath=p.join(homePath,".zshrc");const pluginPath=p.shellPath("src/buddy.plugin.zsh");const customPath=p.join(homePath,".oh-my-zsh/custom/plugins/buddy/");log.info(`Setting up Oh My Zsh via ${zshrcPath}...`);$.cwd(p.dirname(zshrcPath));let data=await $`cat ${p.basename(zshrcPath)}`.text();const pluginLineRegex=/^(?!#).*plugins=\(([^)]+)\)/m;const match=data.match(pluginLineRegex);if(match){const plugins=match[1]?.split(/\s+/).filter(Boolean);if(!plugins){await log.error("Maybe the plugins line in your .zshrc file could not be found? If this continues being an issue, please reach out to us on Discord.");process.exit(ExitCode.FatalError)}if(!plugins.includes("buddy")){plugins.push("buddy");const formattedPlugins=plugins.map((plugin)=>plugin.trim()).join(`
|
|
1
|
+
import{$}from"bun";import process from"node:process";import{italic,parseOptions,print}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{writeFile}from"@stacksjs/storage";import{ExitCode}from"@stacksjs/types";import{upgradeToolPreview}from"./tool-preview";const options=parseOptions();if(options.dryRun){print(upgradeToolPreview(Action.UpgradeShell));process.exit(ExitCode.Success)}const homePath=(await $`echo $HOME`.text()).trim();const zshrcPath=p.join(homePath,".zshrc");const pluginPath=p.shellPath("src/buddy.plugin.zsh");const customPath=p.join(homePath,".oh-my-zsh/custom/plugins/buddy/");log.info(`Setting up Oh My Zsh via ${zshrcPath}...`);$.cwd(p.dirname(zshrcPath));let data=await $`cat ${p.basename(zshrcPath)}`.text();const pluginLineRegex=/^(?!#).*plugins=\(([^)]+)\)/m;const match=data.match(pluginLineRegex);if(match){const plugins=match[1]?.split(/\s+/).filter(Boolean);if(!plugins){await log.error("Maybe the plugins line in your .zshrc file could not be found? If this continues being an issue, please reach out to us on Discord.");process.exit(ExitCode.FatalError)}if(!plugins.includes("buddy")){plugins.push("buddy");const formattedPlugins=plugins.map((plugin)=>plugin.trim()).join(`
|
|
2
2
|
`);const newPluginLine=`plugins=(
|
|
3
3
|
${formattedPlugins}
|
|
4
4
|
)`;data=data.replace(pluginLineRegex,newPluginLine);await writeFile(zshrcPath,data);log.info(`Copying buddy zsh plugin ${pluginPath} to ${customPath}...`);await $`mkdir -p ${customPath}`;await $`cp -rf ${pluginPath} ${customPath}`;log.success("Copied buddy zsh plugin")}else{log.info("Buddy is already set up");log.info("Ensuring `buddy` is updated...");await $`cp -rf ${pluginPath} ${customPath}`;log.success("Updated buddy zsh plugin to latest version")}}log.success("Oh My Zsh Setup Complete");log.info(italic("To see changes reflect, you may need to open a new terminal window"));if(process.env.TERM_PROGRAM==="vscode")log.info("⌘⇧P terminal.create.new.terminal");
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Action}from"@stacksjs/enums";const previews=new Map([[Action.UpgradeDeps,"DRY RUN: Dependency upgrades are not implemented by this stage. No changes were made."],[Action.UpgradeBun,"DRY RUN: Bun upgrades are not implemented by this stage. No changes were made."],[Action.UpgradeShell,"DRY RUN: would update the Oh My Zsh configuration and copy the Buddy shell plugin. No changes were made."],[Action.UpgradeBinary,"DRY RUN: would compile and install the Stacks binary. No changes were made."]]);export function upgradeToolPreview(action){return previews.get(action)}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/actions",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.556",
|
|
6
6
|
"description": "The Stacks actions.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -66,55 +66,55 @@
|
|
|
66
66
|
"prepublishOnly": "bun run build"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@stacksjs/action-runner": "0.75.
|
|
70
|
-
"@stacksjs/ai": "0.75.
|
|
71
|
-
"@stacksjs/analytics": "0.75.
|
|
72
|
-
"@stacksjs/api": "0.75.
|
|
73
|
-
"@stacksjs/auth": "0.75.
|
|
74
|
-
"@stacksjs/build": "0.75.
|
|
69
|
+
"@stacksjs/action-runner": "0.75.556",
|
|
70
|
+
"@stacksjs/ai": "0.75.556",
|
|
71
|
+
"@stacksjs/analytics": "0.75.556",
|
|
72
|
+
"@stacksjs/api": "0.75.556",
|
|
73
|
+
"@stacksjs/auth": "0.75.556",
|
|
74
|
+
"@stacksjs/build": "0.75.556",
|
|
75
75
|
"@stacksjs/bumpx": "^0.2.26",
|
|
76
76
|
"@stacksjs/bunpress": "^0.2.15",
|
|
77
|
-
"@stacksjs/cli": "0.75.
|
|
78
|
-
"@stacksjs/cloud": "0.75.
|
|
79
|
-
"@stacksjs/cms": "0.75.
|
|
77
|
+
"@stacksjs/cli": "0.75.556",
|
|
78
|
+
"@stacksjs/cloud": "0.75.556",
|
|
79
|
+
"@stacksjs/cms": "0.75.556",
|
|
80
80
|
"@stacksjs/components": "^0.2.859",
|
|
81
|
-
"@stacksjs/config": "0.75.
|
|
82
|
-
"@stacksjs/database": "0.75.
|
|
83
|
-
"@stacksjs/desktop-build": "0.75.
|
|
84
|
-
"@stacksjs/dns": "0.75.
|
|
85
|
-
"@stacksjs/docs": "0.75.
|
|
86
|
-
"@stacksjs/enums": "0.75.
|
|
87
|
-
"@stacksjs/env": "0.75.
|
|
88
|
-
"@stacksjs/error-handling": "0.75.
|
|
89
|
-
"@stacksjs/github": "0.75.
|
|
81
|
+
"@stacksjs/config": "0.75.556",
|
|
82
|
+
"@stacksjs/database": "0.75.556",
|
|
83
|
+
"@stacksjs/desktop-build": "0.75.556",
|
|
84
|
+
"@stacksjs/dns": "0.75.556",
|
|
85
|
+
"@stacksjs/docs": "0.75.556",
|
|
86
|
+
"@stacksjs/enums": "0.75.556",
|
|
87
|
+
"@stacksjs/env": "0.75.556",
|
|
88
|
+
"@stacksjs/error-handling": "0.75.556",
|
|
89
|
+
"@stacksjs/github": "0.75.556",
|
|
90
90
|
"@stacksjs/gitit": "^0.2.5",
|
|
91
|
-
"@stacksjs/i18n": "0.75.
|
|
92
|
-
"@stacksjs/image": "0.75.
|
|
93
|
-
"@stacksjs/logging": "0.75.
|
|
91
|
+
"@stacksjs/i18n": "0.75.556",
|
|
92
|
+
"@stacksjs/image": "0.75.556",
|
|
93
|
+
"@stacksjs/logging": "0.75.556",
|
|
94
94
|
"@stacksjs/logsmith": "^0.2.11",
|
|
95
|
-
"@stacksjs/mobile": "0.75.
|
|
96
|
-
"@stacksjs/orm": "0.75.
|
|
97
|
-
"@stacksjs/path": "0.75.
|
|
98
|
-
"@stacksjs/payments": "0.75.
|
|
99
|
-
"@stacksjs/queue": "0.75.
|
|
100
|
-
"@stacksjs/registry": "0.75.
|
|
101
|
-
"@stacksjs/router": "0.75.
|
|
95
|
+
"@stacksjs/mobile": "0.75.556",
|
|
96
|
+
"@stacksjs/orm": "0.75.556",
|
|
97
|
+
"@stacksjs/path": "0.75.556",
|
|
98
|
+
"@stacksjs/payments": "0.75.556",
|
|
99
|
+
"@stacksjs/queue": "0.75.556",
|
|
100
|
+
"@stacksjs/registry": "0.75.556",
|
|
101
|
+
"@stacksjs/router": "0.75.556",
|
|
102
102
|
"@stacksjs/rpx": "^0.11.54",
|
|
103
|
-
"@stacksjs/scheduler": "0.75.
|
|
104
|
-
"@stacksjs/search-engine": "0.75.
|
|
105
|
-
"@stacksjs/security": "0.75.
|
|
106
|
-
"@stacksjs/server": "0.75.
|
|
107
|
-
"@stacksjs/sites": "0.75.
|
|
108
|
-
"@stacksjs/storage": "0.75.
|
|
109
|
-
"@stacksjs/strings": "0.75.
|
|
103
|
+
"@stacksjs/scheduler": "0.75.556",
|
|
104
|
+
"@stacksjs/search-engine": "0.75.556",
|
|
105
|
+
"@stacksjs/security": "0.75.556",
|
|
106
|
+
"@stacksjs/server": "0.75.556",
|
|
107
|
+
"@stacksjs/sites": "0.75.556",
|
|
108
|
+
"@stacksjs/storage": "0.75.556",
|
|
109
|
+
"@stacksjs/strings": "0.75.556",
|
|
110
110
|
"@stacksjs/stx": "^0.2.859",
|
|
111
111
|
"@stacksjs/tlsx": "^0.13.19",
|
|
112
112
|
"@stacksjs/ts-cloud": "^0.16.125",
|
|
113
113
|
"@stacksjs/ts-md": "^0.1.1",
|
|
114
|
-
"@stacksjs/tunnel": "0.75.
|
|
115
|
-
"@stacksjs/types": "0.75.
|
|
116
|
-
"@stacksjs/utils": "0.75.
|
|
117
|
-
"@stacksjs/whois": "0.75.
|
|
114
|
+
"@stacksjs/tunnel": "0.75.556",
|
|
115
|
+
"@stacksjs/types": "0.75.556",
|
|
116
|
+
"@stacksjs/utils": "0.75.556",
|
|
117
|
+
"@stacksjs/whois": "0.75.556",
|
|
118
118
|
"bun-plugin-stx": "^0.2.859",
|
|
119
119
|
"pickier": "^0.1.92"
|
|
120
120
|
},
|
|
@@ -127,7 +127,7 @@
|
|
|
127
127
|
}
|
|
128
128
|
},
|
|
129
129
|
"devDependencies": {
|
|
130
|
-
"@stacksjs/validation": "0.75.
|
|
130
|
+
"@stacksjs/validation": "0.75.556",
|
|
131
131
|
"better-dx": "^0.2.24"
|
|
132
132
|
}
|
|
133
133
|
}
|