diff --git a/electron/handlers/devServers.ts b/electron/handlers/devServers.ts index d4271ddd2..3ddbb48b5 100644 --- a/electron/handlers/devServers.ts +++ b/electron/handlers/devServers.ts @@ -15,7 +15,8 @@ import { RUNTIME_PATHS } from '../lib/runtimePaths'; import { commandNeedsShell, sameFilesystemPath } from '../lib/platform'; import { createKeyedQueue } from '../lib/serialQueue'; import type { DevServer } from '../lib/mainTypes'; -import { SHORT_COMMAND, errorMessage, isWin, parseOptionalString, parseRecord, readJson, toPosix } from '../lib/mainHelpers'; +import { SHORT_COMMAND, errorMessage, parseOptionalString, parseRecord, readJson, toPosix } from '../lib/mainHelpers'; +import { localAstroBin } from '../project/projectFiles'; import { findFreePort, nodeCliCommand, resolveNodeBin, run, spawnAstroServer, stopProcessTree } from '../lib/nodeTools'; import { previewSupportFiles, renderComponentPreviewPage } from '../previewServer/componentPreview'; import { probeUrl } from '../preview/devProbe'; @@ -645,21 +646,20 @@ export class DevServers { ); } - const binName = isWin ? 'astro.cmd' : 'astro'; - const localBin = path.join(projectPath, 'node_modules', '.bin', binName); - if (!fs.existsSync(localBin)) { + if (!fs.existsSync(localAstroBin(projectPath))) { // Dependencies missing or incomplete — install with the right PM first. await installDependencies(this.host, projectPath); assertActive(); this.host.send('progress', PROGRESS_CLEARED); - if (!fs.existsSync(localBin)) { + if (!fs.existsSync(localAstroBin(projectPath))) { throw new Error( 'astro is not installed in this project (no node_modules/.bin/astro after install). ' + 'Is astro listed in package.json dependencies?', ); } } - return localBin; + // Looked up again: the install is what may have made it, and under Bun it is `astro.exe`, not `astro.cmd`. + return localAstroBin(projectPath); } private async failureDetail(projectPath: string, localBin: string, startedAtMs: number): Promise { diff --git a/electron/handlers/emdashInstall.ts b/electron/handlers/emdashInstall.ts index b8ec125e8..d1dffc057 100644 --- a/electron/handlers/emdashInstall.ts +++ b/electron/handlers/emdashInstall.ts @@ -37,7 +37,7 @@ import { type EmDashPreviewState, } from '../../shared/properties/emdashInstall'; import { PNPM_TOLERATE_IGNORED_BUILDS, detectPackageManager } from '../project/packageManager'; -import type { PackageManager } from '../../shared/properties/packageManager'; +import { packageManagerProgram, type PackageManager } from '../../shared/properties/packageManager'; import { RUN_CANCELLED, runCreateCommand } from '../project/starter'; import { ensureToolPath, git } from '../lib/nodeTools'; import { commit } from '../git/gitSnapshot'; @@ -296,7 +296,7 @@ async function install( const options = { signal: context.controller.signal, timeoutMs: EMDASH_INSTALL_LIMITS.runMsMax }; try { context.onLog(`> ${plan.command}\n\n`); - await context.deps.runCommand(windows ? `${plan.manager}.cmd` : plan.manager, addArguments(plan.manager), root, context.onLog, options); + await context.deps.runCommand(packageManagerProgram(plan.manager, { windows }), addArguments(plan.manager), root, context.onLog, options); writeLiveConfigIfAbsent(root); appendIgnoreLines(root); config = registerInAstroConfig(root, context.deps.verifyConfig); diff --git a/electron/handlers/previewHandlers.ts b/electron/handlers/previewHandlers.ts index 6cea95761..e2741425b 100644 --- a/electron/handlers/previewHandlers.ts +++ b/electron/handlers/previewHandlers.ts @@ -2,12 +2,11 @@ // its render check, and stopping it. import { MAIN_LIMITS } from '../lib/mainLimits'; -import * as path from 'path'; import * as fs from 'fs'; import * as previewWorktree from '../preview/previewWorktree'; import { checkPreviewRender } from '../preview/previewCheck'; -import { isWin } from '../lib/mainHelpers'; import { findFreePort, git, spawnAstroServer } from '../lib/nodeTools'; +import { localAstroBin } from '../project/projectFiles'; import { serverAlive } from '../preview/devServerChecks'; import { previewServers, stopPreview } from '../preview/previewServers'; import type { MainHost } from './mainHost'; @@ -30,8 +29,7 @@ function registerPreviewAtCommitHandler({ ipcMain }: Pick): return { url: running.url, ref, reused: true as const }; } - const bin = isWin ? 'astro.cmd' : 'astro'; - const localBin = path.join(projectPath, 'node_modules', '.bin', bin); + const localBin = localAstroBin(projectPath); if (!fs.existsSync(localBin)) { throw new Error('This project’s packages aren’t installed, so an older version can’t be shown. ' + 'Install them and try again.'); } diff --git a/electron/handlers/projectHandlers.ts b/electron/handlers/projectHandlers.ts index 8936820fa..5996120bb 100644 --- a/electron/handlers/projectHandlers.ts +++ b/electron/handlers/projectHandlers.ts @@ -13,7 +13,7 @@ import { isWin } from '../lib/mainHelpers'; import { ensureToolPath, run } from '../lib/nodeTools'; import { isAstroProject } from '../project/projectFiles'; import { detectPackageManager, installArguments } from '../project/packageManager'; -import { packageManagerLabel, type PackageManager } from '../../shared/properties/packageManager'; +import { packageManagerLabel, packageManagerProgram, type PackageManager } from '../../shared/properties/packageManager'; import type { MainHost } from './mainHost'; import { translateMain } from '../lib/mainLocale'; import { folderOpenChoice, siteFolderChoice } from '../project/folderOpen'; @@ -115,6 +115,7 @@ function registerProjectCreateStarterHandlers({ ipcMain, send }: Pick send('create:log', text), }); const label = STARTERS[starter]?.label ?? starter; @@ -195,10 +196,10 @@ function normalizedRequest, directory: string, pm: PackageManager = detectPackageManager(directory)) { - ensureToolPath(); // npm/pnpm/yarn are Node shims — same PATH problem as astro + ensureToolPath(); // npm/pnpm/yarn are Node shims, and bun lives in ~/.bun/bin — same PATH problem as astro send('progress', { message: `Installing dependencies (${pm} install)…` }); try { - await run(isWin ? `${pm}.cmd` : pm, [...installArguments(pm)], directory, { + await run(packageManagerProgram(pm, { windows: isWin }), [...installArguments(pm)], directory, { timeout: 10 * 60 * 1000, shell: isWin, }); @@ -214,7 +215,7 @@ export async function installDependencies({ send }: Pick, dire // any folder exists. On Windows a missing command fails without ENOENT, so any failure counts. async function requirePackageManager(manager: PackageManager): Promise { try { - await run(isWin ? `${manager}.cmd` : manager, ['--version'], os.homedir()); + await run(packageManagerProgram(manager, { windows: isWin }), ['--version'], os.homedir()); } catch { throw new Error(`${packageManagerLabel(manager)} is not installed. Install it or choose npm.`); } diff --git a/electron/handlers/thumbnails.ts b/electron/handlers/thumbnails.ts index e70612527..24f5c4043 100644 --- a/electron/handlers/thumbnails.ts +++ b/electron/handlers/thumbnails.ts @@ -6,14 +6,12 @@ // makes "the site as it is now" true for a project that was last edited // somewhere else entirely. One instance per main process, made by main.ts. -import * as path from 'path'; import type { ChildProcess } from 'child_process'; import * as thumbs from '../project/thumbs'; import { sameFilesystemPath } from '../lib/platform'; import { createSerialQueue } from '../lib/serialQueue'; -import { isWin } from '../lib/mainHelpers'; import { findFreePort, spawnAstroServer, stopProcessTree } from '../lib/nodeTools'; -import { hasDependencies } from '../project/projectFiles'; +import { hasDependencies, localAstroBin } from '../project/projectFiles'; import { serverAlive } from '../preview/devServerChecks'; import type { DevServers } from './devServers'; import type { MainHost } from './mainHost'; @@ -128,8 +126,7 @@ export function registerThumbnailHandlers({ // A dev server of the project's own, for one capture: the canvas's server is // left alone, and the temporary one is stopped however the capture ends. async function withTemporaryServer(projectPath: string, signal: AbortSignal, capture: (url: string) => ReturnType) { - const binName = isWin ? 'astro.cmd' : 'astro'; - const localBin = path.join(projectPath, 'node_modules', '.bin', binName); + const localBin = localAstroBin(projectPath); const port = await findFreePort(4400 + Math.floor(Math.random() * 200)); if (signal.aborted) { return { ok: false as const, error: 'skipped' }; diff --git a/electron/project/projectFiles.ts b/electron/project/projectFiles.ts index ba09bed88..a5010f610 100644 --- a/electron/project/projectFiles.ts +++ b/electron/project/projectFiles.ts @@ -126,13 +126,24 @@ export function isAstroProject(directory: string): boolean { return false; } +// The project's own `astro` command in node_modules/.bin. On Windows npm, pnpm and Yarn leave `astro.cmd`, while Bun +// leaves `astro.exe` (and no .cmd), so whichever is there is the one; when neither is, the path npm would have made. +export function localAstroBin(projectPath: string): string { + const folder = path.join(projectPath, 'node_modules', '.bin'); + if (!isWin) { + return path.join(folder, 'astro'); + } + const executable = path.join(folder, 'astro.exe'); + const shim = path.join(folder, 'astro.cmd'); + return fs.existsSync(shim) || !fs.existsSync(executable) ? shim : executable; +} + // Astro has to be installed for a page to be rendered at all; without it the // card can only offer to open the project. A workspace hoists node_modules to its root, so each parent counts. export function hasDependencies(projectPath: string): boolean { - const binName = isWin ? 'astro.cmd' : 'astro'; return ancestorsOf(projectPath).some( (directory) => - fs.existsSync(path.join(directory, 'node_modules', '.bin', binName)) || + fs.existsSync(localAstroBin(directory)) || fs.existsSync(path.join(directory, 'node_modules', 'astro', 'package.json')) || // Yarn Plug'n'Play keeps packages in a cache and no node_modules at all. fs.existsSync(path.join(directory, '.pnp.cjs')), diff --git a/electron/project/starter.ts b/electron/project/starter.ts index cce828f02..2a10ff5c5 100644 --- a/electron/project/starter.ts +++ b/electron/project/starter.ts @@ -1,10 +1,12 @@ import fs from 'fs'; +import os from 'os'; import path from 'path'; import { spawn } from 'child_process'; import { toRecord } from '../../shared/core/record'; import { commandNeedsShell } from '../lib/platform'; import { stopProcessTree } from '../lib/nodeTools'; +import { packageManagerProgram, type PackageManager } from '../../shared/properties/packageManager'; // Starting a site from a starter. // @@ -51,6 +53,40 @@ export const RUN_CANCELLED = 'The command was cancelled.'; interface RunOptions { readonly signal?: AbortSignal; readonly timeoutMs?: number; + /** Extra variables for this child only, laid over the app's own. */ + readonly environment?: Readonly>; +} + +// The Lumos scaffolder (create-lumos 0.3.9) links its skill folders with symlinks and, where Windows refuses them +// (no Developer Mode, no admin), falls back to `copyFile` on the folder, which always fails with EPERM. This preload +// makes that one fallback copy the folder instead. It touches nothing else: files go to the original `copyFile`. +const COPY_DIRECTORIES_SHIM = `const fsp = require('node:fs/promises'); +const { statSync } = require('node:fs'); +const original = fsp.copyFile; +fsp.copyFile = async function copyFile(source, target, mode) { + let directory = false; + try { + directory = statSync(source).isDirectory(); + } catch { + directory = false; + } + if (directory) { + return fsp.cp(source, target, { recursive: true }); + } + return original.call(this, source, target, mode); +}; +require('node:module').syncBuiltinESMExports(); +`; + +// NODE_OPTIONS for a scaffolder run: the shim written to the temp folder, joined to whatever the person already set. +function scaffolderEnvironment(): Readonly> { + const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'stacki-scaffold-')); + const file = path.join(folder, 'copyDirectories.cjs'); + fs.writeFileSync(file, COPY_DIRECTORIES_SHIM, 'utf8'); + // Forward slashes: a backslash escapes inside the quotes NODE_OPTIONS reads. + const preload = `--require "${file.replace(/\\/g, '/')}"`; + const existing = process.env['NODE_OPTIONS']; + return { NODE_OPTIONS: existing === undefined || existing.length === 0 ? preload : `${existing} ${preload}` }; } const run = (cmd: string, args: readonly string[], cwd: string, onLog?: OnLog, options: RunOptions = {}): Promise => @@ -69,6 +105,7 @@ const run = (cmd: string, args: readonly string[], cwd: string, onLog?: OnLog, o FORCE_COLOR: '0', NO_COLOR: '1', CI: '1', // npm asks before downloading a scaffolder; nobody is here to answer + ...options.environment, }, }); } catch (error: unknown) { @@ -134,16 +171,34 @@ interface CreateStarterOptions { readonly name?: string; /** The npm command to run, so a test can hand it one that needs no network. */ readonly npm?: string; + /** The manager the person chose. Bun runs the scaffolder itself (`bun create`); the others run it through npm, which every Node install has. */ + readonly manager?: PackageManager; readonly onLog?: OnLog; } +// Bun has its own `create`, which downloads and runs the scaffolder. It takes no `--yes` and no `--` separator: +// what follows the folder name goes to the scaffolder as it is. +function scaffolderCommand( + manager: PackageManager | undefined, + create: string, + folder: string, +): { readonly label: string; readonly program: string; readonly args: readonly string[] } { + if (manager === 'bun') { + return { label: 'bun', program: packageManagerProgram('bun', { windows: isWin }), args: ['create', create, folder, '--no-install'] }; + } + return { label: 'npm', program: packageManagerProgram('npm', { windows: isWin }), args: ['create', create, folder, '--yes', '--', '--no-install'] }; +} + /** * Runs a starter's scaffolder in `parentPath` to make `parentPath/name`. * Installing what it needs and its first commit (`startSiteHistory`) are the * caller's — this is the part that has to be right before anything is * installed into it. */ -async function createStarter({ starter = 'lumos', parentPath, name, npm, onLog }: CreateStarterOptions = {}): Promise<{ ok: boolean; projectPath: string }> { +async function createStarter({ starter = 'lumos', parentPath, name, npm, manager, onLog }: CreateStarterOptions = {}): Promise<{ + ok: boolean; + projectPath: string; +}> { const template = STARTERS[starter]; if (!template) { throw new Error(`${starter} is not a starter this app knows.`); @@ -153,9 +208,9 @@ async function createStarter({ starter = 'lumos', parentPath, name, npm, onLog } // `--no-install`: the app installs afterwards, where a failure is an error // the wizard can show rather than a line in a log that scrolled past. - const args = ['create', template.create, folder, '--yes', '--', '--no-install']; - onLog?.(`> npm create ${template.create} ${folder}\n\n`); - await run(npm || (isWin ? 'npm.cmd' : 'npm'), args, path.dirname(directory), onLog); + const command = scaffolderCommand(manager, template.create, folder); + onLog?.(`> ${command.label} create ${template.create} ${folder}\n\n`); + await run(npm || command.program, command.args, path.dirname(directory), onLog, { environment: scaffolderEnvironment() }); if (!fs.existsSync(path.join(directory, 'package.json'))) { throw new Error('The starter finished but there is no package.json in it.'); @@ -231,4 +286,4 @@ function newSiteDirectory(parentPath: string | undefined, name: string | undefin return directory; } -export { createStarter, newSiteDirectory, run as runCreateCommand, startSiteHistory, STARTERS }; +export { createStarter, newSiteDirectory, run as runCreateCommand, scaffolderEnvironment, startSiteHistory, STARTERS }; diff --git a/shared/properties/i18n/messages/ar/workspace.ts b/shared/properties/i18n/messages/ar/workspace.ts index ea9c4398f..8c99ea89c 100644 --- a/shared/properties/i18n/messages/ar/workspace.ts +++ b/shared/properties/i18n/messages/ar/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'إغلاق (تُحفظ التعديلات مباشرة)', 'workspace.code.title': 'الكود', + 'workspace.notifications.copied': 'تم النسخ', + 'workspace.notifications.copy': 'نسخ', 'workspace.notifications.dismiss': 'تجاهل الإشعار', 'workspace.notifications.label': 'الإشعارات', 'workspace.notifications.loadMore': 'تحميل المزيد ({count})', diff --git a/shared/properties/i18n/messages/de/workspace.ts b/shared/properties/i18n/messages/de/workspace.ts index 304ff5d26..304136bba 100644 --- a/shared/properties/i18n/messages/de/workspace.ts +++ b/shared/properties/i18n/messages/de/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'Schließen (Änderungen werden sofort gespeichert)', 'workspace.code.title': 'Code', // same + 'workspace.notifications.copied': 'Kopiert', + 'workspace.notifications.copy': 'Kopieren', 'workspace.notifications.dismiss': 'Benachrichtigung schließen', 'workspace.notifications.label': 'Benachrichtigungen', 'workspace.notifications.loadMore': 'Mehr laden ({count})', diff --git a/shared/properties/i18n/messages/en/workspace.ts b/shared/properties/i18n/messages/en/workspace.ts index 0dfd6ac45..30301ba98 100644 --- a/shared/properties/i18n/messages/en/workspace.ts +++ b/shared/properties/i18n/messages/en/workspace.ts @@ -5,6 +5,8 @@ import type { CatalogOf } from '../../../../core/i18n/catalog'; export const messages = { 'workspace.code.close': 'Close (edits are saved live)', 'workspace.code.title': 'Code', + 'workspace.notifications.copied': 'Copied', + 'workspace.notifications.copy': 'Copy', 'workspace.notifications.dismiss': 'Dismiss notification', 'workspace.notifications.label': 'Notifications', 'workspace.notifications.loadMore': 'Load more ({count})', diff --git a/shared/properties/i18n/messages/es/workspace.ts b/shared/properties/i18n/messages/es/workspace.ts index 912caba51..97e29d35f 100644 --- a/shared/properties/i18n/messages/es/workspace.ts +++ b/shared/properties/i18n/messages/es/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'Cerrar (los cambios se guardan al instante)', 'workspace.code.title': 'Código', + 'workspace.notifications.copied': 'Copiado', + 'workspace.notifications.copy': 'Copiar', 'workspace.notifications.dismiss': 'Descartar notificación', 'workspace.notifications.label': 'Notificaciones', 'workspace.notifications.loadMore': 'Cargar más ({count})', diff --git a/shared/properties/i18n/messages/fr/workspace.ts b/shared/properties/i18n/messages/fr/workspace.ts index babfef55a..1bdb6c635 100644 --- a/shared/properties/i18n/messages/fr/workspace.ts +++ b/shared/properties/i18n/messages/fr/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'Fermer (les modifications sont enregistrées en direct)', 'workspace.code.title': 'Code', // same + 'workspace.notifications.copied': 'Copié', + 'workspace.notifications.copy': 'Copier', 'workspace.notifications.dismiss': 'Ignorer la notification', 'workspace.notifications.label': 'Notifications', // same 'workspace.notifications.loadMore': 'Charger plus ({count})', diff --git a/shared/properties/i18n/messages/he/workspace.ts b/shared/properties/i18n/messages/he/workspace.ts index bf1196338..50496e241 100644 --- a/shared/properties/i18n/messages/he/workspace.ts +++ b/shared/properties/i18n/messages/he/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'סגירה (העריכות נשמרות מיד)', 'workspace.code.title': 'קוד', + 'workspace.notifications.copied': 'הועתק', + 'workspace.notifications.copy': 'העתקה', 'workspace.notifications.dismiss': 'סגירת ההתראה', 'workspace.notifications.label': 'התראות', 'workspace.notifications.loadMore': 'טעינת עוד ({count})', diff --git a/shared/properties/i18n/messages/hi/workspace.ts b/shared/properties/i18n/messages/hi/workspace.ts index de09bc457..4493ac265 100644 --- a/shared/properties/i18n/messages/hi/workspace.ts +++ b/shared/properties/i18n/messages/hi/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'बंद करें (बदलाव तुरंत सहेजे जाते हैं)', 'workspace.code.title': 'कोड', + 'workspace.notifications.copied': 'कॉपी हो गया', + 'workspace.notifications.copy': 'कॉपी करें', 'workspace.notifications.dismiss': 'सूचना हटाएँ', 'workspace.notifications.label': 'सूचनाएँ', 'workspace.notifications.loadMore': 'और लोड करें ({count})', diff --git a/shared/properties/i18n/messages/id/workspace.ts b/shared/properties/i18n/messages/id/workspace.ts index e1d9d267d..c5797389e 100644 --- a/shared/properties/i18n/messages/id/workspace.ts +++ b/shared/properties/i18n/messages/id/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'Tutup (suntingan disimpan langsung)', 'workspace.code.title': 'Kode', + 'workspace.notifications.copied': 'Disalin', + 'workspace.notifications.copy': 'Salin', 'workspace.notifications.dismiss': 'Tutup notifikasi', 'workspace.notifications.label': 'Notifikasi', 'workspace.notifications.loadMore': 'Muat lebih banyak ({count})', diff --git a/shared/properties/i18n/messages/it/workspace.ts b/shared/properties/i18n/messages/it/workspace.ts index 36c34943e..30d73635f 100644 --- a/shared/properties/i18n/messages/it/workspace.ts +++ b/shared/properties/i18n/messages/it/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'Chiudi (le modifiche vengono salvate in tempo reale)', 'workspace.code.title': 'Codice', + 'workspace.notifications.copied': 'Copiato', + 'workspace.notifications.copy': 'Copia', 'workspace.notifications.dismiss': 'Ignora notifica', 'workspace.notifications.label': 'Notifiche', 'workspace.notifications.loadMore': 'Carica altre ({count})', diff --git a/shared/properties/i18n/messages/ja/workspace.ts b/shared/properties/i18n/messages/ja/workspace.ts index 62d5c54bc..41bdd8f16 100644 --- a/shared/properties/i18n/messages/ja/workspace.ts +++ b/shared/properties/i18n/messages/ja/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': '閉じる(編集内容は自動で保存されます)', 'workspace.code.title': 'コード', + 'workspace.notifications.copied': 'コピーしました', + 'workspace.notifications.copy': 'コピー', 'workspace.notifications.dismiss': '通知を閉じる', 'workspace.notifications.label': '通知', 'workspace.notifications.loadMore': 'さらに読み込む({count})', diff --git a/shared/properties/i18n/messages/ko/workspace.ts b/shared/properties/i18n/messages/ko/workspace.ts index 9eba58b7a..7c8ae0f6a 100644 --- a/shared/properties/i18n/messages/ko/workspace.ts +++ b/shared/properties/i18n/messages/ko/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': '닫기(편집 내용은 자동으로 저장됨)', 'workspace.code.title': '코드', + 'workspace.notifications.copied': '복사됨', + 'workspace.notifications.copy': '복사', 'workspace.notifications.dismiss': '알림 닫기', 'workspace.notifications.label': '알림', 'workspace.notifications.loadMore': '더 불러오기({count})', diff --git a/shared/properties/i18n/messages/nl/workspace.ts b/shared/properties/i18n/messages/nl/workspace.ts index 202be168e..2fe0d8dd4 100644 --- a/shared/properties/i18n/messages/nl/workspace.ts +++ b/shared/properties/i18n/messages/nl/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'Sluiten (wijzigingen worden direct opgeslagen)', 'workspace.code.title': 'Code', // same + 'workspace.notifications.copied': 'Gekopieerd', + 'workspace.notifications.copy': 'Kopiëren', 'workspace.notifications.dismiss': 'Melding sluiten', 'workspace.notifications.label': 'Meldingen', 'workspace.notifications.loadMore': 'Meer laden ({count})', diff --git a/shared/properties/i18n/messages/pl/workspace.ts b/shared/properties/i18n/messages/pl/workspace.ts index 1c82e2a96..9e54df491 100644 --- a/shared/properties/i18n/messages/pl/workspace.ts +++ b/shared/properties/i18n/messages/pl/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'Zamknij (zmiany są zapisywane na bieżąco)', 'workspace.code.title': 'Kod', + 'workspace.notifications.copied': 'Skopiowano', + 'workspace.notifications.copy': 'Kopiuj', 'workspace.notifications.dismiss': 'Zamknij powiadomienie', 'workspace.notifications.label': 'Powiadomienia', 'workspace.notifications.loadMore': 'Wczytaj więcej ({count})', diff --git a/shared/properties/i18n/messages/ptBR/workspace.ts b/shared/properties/i18n/messages/ptBR/workspace.ts index 46b6a21ff..8f28fec8c 100644 --- a/shared/properties/i18n/messages/ptBR/workspace.ts +++ b/shared/properties/i18n/messages/ptBR/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'Fechar (as edições são salvas na hora)', 'workspace.code.title': 'Código', + 'workspace.notifications.copied': 'Copiado', + 'workspace.notifications.copy': 'Copiar', 'workspace.notifications.dismiss': 'Dispensar notificação', 'workspace.notifications.label': 'Notificações', 'workspace.notifications.loadMore': 'Carregar mais ({count})', diff --git a/shared/properties/i18n/messages/ru/workspace.ts b/shared/properties/i18n/messages/ru/workspace.ts index 6f18e1e3e..20c3eb2ac 100644 --- a/shared/properties/i18n/messages/ru/workspace.ts +++ b/shared/properties/i18n/messages/ru/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'Закрыть (правки сохраняются сразу)', 'workspace.code.title': 'Код', + 'workspace.notifications.copied': 'Скопировано', + 'workspace.notifications.copy': 'Копировать', 'workspace.notifications.dismiss': 'Скрыть уведомление', 'workspace.notifications.label': 'Уведомления', 'workspace.notifications.loadMore': 'Показать ещё ({count})', diff --git a/shared/properties/i18n/messages/tr/workspace.ts b/shared/properties/i18n/messages/tr/workspace.ts index 913324dd0..4768c0322 100644 --- a/shared/properties/i18n/messages/tr/workspace.ts +++ b/shared/properties/i18n/messages/tr/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': 'Kapat (düzenlemeler anında kaydedilir)', 'workspace.code.title': 'Kod', + 'workspace.notifications.copied': 'Kopyalandı', + 'workspace.notifications.copy': 'Kopyala', 'workspace.notifications.dismiss': 'Bildirimi kapat', 'workspace.notifications.label': 'Bildirimler', 'workspace.notifications.loadMore': 'Daha fazla yükle ({count})', diff --git a/shared/properties/i18n/messages/zhCN/workspace.ts b/shared/properties/i18n/messages/zhCN/workspace.ts index 93f37ff9b..526f80a58 100644 --- a/shared/properties/i18n/messages/zhCN/workspace.ts +++ b/shared/properties/i18n/messages/zhCN/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': '关闭(编辑会实时保存)', 'workspace.code.title': '代码', + 'workspace.notifications.copied': '已复制', + 'workspace.notifications.copy': '复制', 'workspace.notifications.dismiss': '关闭通知', 'workspace.notifications.label': '通知', 'workspace.notifications.loadMore': '加载更多({count})', diff --git a/shared/properties/i18n/messages/zhTW/workspace.ts b/shared/properties/i18n/messages/zhTW/workspace.ts index 51e43aba1..aa0d6d642 100644 --- a/shared/properties/i18n/messages/zhTW/workspace.ts +++ b/shared/properties/i18n/messages/zhTW/workspace.ts @@ -5,6 +5,8 @@ import type { MessageKey } from '../en/workspace'; export const messages = { 'workspace.code.close': '關閉(編輯會即時儲存)', 'workspace.code.title': '程式碼', + 'workspace.notifications.copied': '已複製', + 'workspace.notifications.copy': '複製', 'workspace.notifications.dismiss': '關閉通知', 'workspace.notifications.label': '通知', 'workspace.notifications.loadMore': '載入更多({count})', diff --git a/shared/properties/packageManager.ts b/shared/properties/packageManager.ts index cade19776..ae1f39c47 100644 --- a/shared/properties/packageManager.ts +++ b/shared/properties/packageManager.ts @@ -6,7 +6,7 @@ export type PackageManager = (typeof PACKAGE_MANAGERS)[number]; // The managers a new site can be created with: those tested end to end so far. Yarn's newer // versions skip node_modules by default, which the preview has not been checked against. -export const CREATE_PACKAGE_MANAGERS = ['npm', 'pnpm'] as const satisfies readonly PackageManager[]; +export const CREATE_PACKAGE_MANAGERS = ['npm', 'pnpm', 'bun'] as const satisfies readonly PackageManager[]; export type CreatePackageManager = (typeof CREATE_PACKAGE_MANAGERS)[number]; const FIELD_CHARS_MAX = 256; @@ -14,11 +14,19 @@ const FIELD_CHARS_MAX = 256; export function parseCreatePackageManager(input: unknown): CreatePackageManager { const manager = CREATE_PACKAGE_MANAGERS.find((candidate) => candidate === input); if (manager === undefined) { - throw new Error(`Package manager: expected ${CREATE_PACKAGE_MANAGERS.join(' or ')}`); + throw new Error( + `Package manager: expected ${CREATE_PACKAGE_MANAGERS.slice(0, -1).join(', ')} or ${CREATE_PACKAGE_MANAGERS[CREATE_PACKAGE_MANAGERS.length - 1]}`, + ); } return manager; } +// The program to start for a manager. npm, pnpm and Yarn are Node shims, `.cmd` files on Windows; Bun is a +// native binary there (`bun.exe`), so a `bun.cmd` would never be found. +export function packageManagerProgram(manager: PackageManager, options: { readonly windows: boolean }): string { + return options.windows && manager !== 'bun' ? `${manager}.cmd` : manager; +} + // The name people know each manager by, for messages. export function packageManagerLabel(manager: PackageManager): string { switch (manager) { diff --git a/src/features/notifications/ToastStack.tsx b/src/features/notifications/ToastStack.tsx index 28c37842e..0f1d9fddb 100644 --- a/src/features/notifications/ToastStack.tsx +++ b/src/features/notifications/ToastStack.tsx @@ -3,7 +3,7 @@ import { checkCircle as centralCheckCircle, close as centralClose, info as centr import { createPortal } from 'react-dom'; import { useToastHost } from './useToastHost'; import { runToastRecovery } from '../../ui/errorNotices'; -import type { CSSProperties, ReactNode } from 'react'; +import { useEffect, useState, type CSSProperties, type ReactNode } from 'react'; import { useToastInteraction } from './useToastInteraction'; import { TOAST_LIMIT, type ToastNotice } from './useToastStack'; import { useToastLayout } from './useToastLayout'; @@ -126,6 +126,7 @@ function ToastCard({ {notice.message} {action} + {notice.kind === 'error' && } @@ -133,6 +134,36 @@ function ToastCard({ ); } +// Copies the message so an error can be pasted into a search, an issue or a chat. The toast stays up, and the +// button says "Copied" for a moment so the click is seen to have worked. +const COPIED_LABEL_MS = 2000; + +function ToastCopy({ message }: { readonly message: string }) { + const translate = useTranslate(); + const [copied, setCopied] = useState(false); + useEffect(() => { + if (!copied) { + return undefined; + } + const timer = window.setTimeout(() => setCopied(false), COPIED_LABEL_MS); + return () => window.clearTimeout(timer); + }, [copied]); + return ( + + ); +} + function ToastClose({ close }: { readonly close: () => void }) { const translate = useTranslate(); return ( diff --git a/src/features/notifications/toasts.css b/src/features/notifications/toasts.css index 5c984d5f3..b6c88592b 100644 --- a/src/features/notifications/toasts.css +++ b/src/features/notifications/toasts.css @@ -183,7 +183,8 @@ } } -.toast-recovery { +.toast-recovery, +.toast-copy { display: inline-block; margin-block: 6px 0; margin-inline: 0 8px; diff --git a/test/electron/project/packageManager.test.ts b/test/electron/project/packageManager.test.ts index 43877670d..1beaab2a0 100644 --- a/test/electron/project/packageManager.test.ts +++ b/test/electron/project/packageManager.test.ts @@ -15,6 +15,7 @@ import { PACKAGE_MANAGERS, packageManagerLabel, parseCreatePackageManager, + packageManagerProgram, parsePackageManagerField, } from '#dist/shared/properties/packageManager.js'; import { parseIpcPayload } from '#dist/shared/ipc/ipcPayloads.js'; @@ -47,16 +48,17 @@ test('the packageManager field names nothing when unknown, malformed or oversize } }); -test('a new site can be created with npm or pnpm, and nothing else yet', () => { - assert.deepEqual(CREATE_PACKAGE_MANAGERS, ['npm', 'pnpm']); +test('a new site can be created with npm, pnpm or bun, and nothing else yet', () => { + assert.deepEqual(CREATE_PACKAGE_MANAGERS, ['npm', 'pnpm', 'bun']); assert.equal(parseCreatePackageManager('npm'), 'npm'); assert.equal(parseCreatePackageManager('pnpm'), 'pnpm'); - for (const input of [undefined, 7, '', 'yarn', 'bun', 'PNPM', ' npm']) { - assert.throws(() => parseCreatePackageManager(input), /expected npm or pnpm/, String(input)); + assert.equal(parseCreatePackageManager('bun'), 'bun'); + for (const input of [undefined, 7, '', 'yarn', 'BUN', 'PNPM', ' npm']) { + assert.throws(() => parseCreatePackageManager(input), /expected npm, pnpm or bun/, String(input)); } assert.equal(parseIpcPayload('project:createStarter', starter('pnpm')).packageManager, 'pnpm'); assert.equal(parseIpcPayload('project:createStarter', starter(undefined)).packageManager, undefined); - assert.throws(() => parseIpcPayload('project:createStarter', starter('yarn')), /npm or pnpm/); + assert.throws(() => parseIpcPayload('project:createStarter', starter('yarn')), /npm, pnpm or bun/); }); test('each package manager installs dependencies with its own command', () => { @@ -95,3 +97,11 @@ test('lockfiles decide when the field is absent, unknown or unreadable', async ( assert.equal(detectPackageManager(await project(context, files)), expected); } }); + +test('Bun is started as itself on Windows, the Node shims as .cmd files', () => { + assert.equal(packageManagerProgram('bun', { windows: true }), 'bun'); + assert.equal(packageManagerProgram('pnpm', { windows: true }), 'pnpm.cmd'); + assert.equal(packageManagerProgram('npm', { windows: true }), 'npm.cmd'); + assert.equal(packageManagerProgram('bun', { windows: false }), 'bun'); + assert.equal(packageManagerProgram('yarn', { windows: false }), 'yarn'); +}); diff --git a/test/electron/project/projectFiles.test.ts b/test/electron/project/projectFiles.test.ts index f874074f0..a7001871f 100644 --- a/test/electron/project/projectFiles.test.ts +++ b/test/electron/project/projectFiles.test.ts @@ -7,7 +7,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import * as path from 'node:path'; import { ASTRO_BIN_NAME, buildProject, removeProject, volumeIsCaseInsensitive } from '../../helpers/projectFixtures.ts'; -import { hasDependencies, isAstroProject, listAstroFiles, routeForPage } from '#dist/electron/project/projectFiles.js'; +import { hasDependencies, isAstroProject, listAstroFiles, localAstroBin, routeForPage } from '#dist/electron/project/projectFiles.js'; import { detectPackageManager } from '#dist/electron/project/packageManager.js'; const PAGE = '

x

'; @@ -57,6 +57,25 @@ test('installed packages are found in the package or in any parent workspace roo assert.equal(has('none'), false); }); +// Goal: a Bun install on Windows is found. Method: lay out .bin the way each manager does and ask for the command. +// Bun writes astro.exe and no astro.cmd; looking only for the .cmd made Stacki say astro was not installed. +test('the astro command is the .cmd npm leaves or the .exe Bun leaves on Windows', { skip: process.platform !== 'win32' }, (context) => { + const built = buildProject({ + 'bun/node_modules/.bin/astro.exe': 'MZ', + 'npm/node_modules/.bin/astro.cmd': '@echo off', + 'both/node_modules/.bin/astro.cmd': '@echo off', + 'both/node_modules/.bin/astro.exe': 'MZ', + 'empty/package.json': '{}', + }); + context.after(() => removeProject(built.root)); + const bin = (folder: string) => path.basename(localAstroBin(path.join(built.root, folder))); + assert.equal(bin('bun'), 'astro.exe'); + assert.equal(bin('npm'), 'astro.cmd'); + assert.equal(bin('both'), 'astro.cmd'); + assert.equal(bin('empty'), 'astro.cmd'); + assert.equal(hasDependencies(path.join(built.root, 'bun')), true); +}); + test('the package manager comes from the nearest field or lockfile, looking through parents', (context) => { const built = buildProject({ 'field/package.json': '{"packageManager":"yarn@4.1.0+sha512.abc"}', diff --git a/test/electron/project/starter.test.js b/test/electron/project/starter.test.js index 8000a0b61..fee13b7c4 100644 --- a/test/electron/project/starter.test.js +++ b/test/electron/project/starter.test.js @@ -18,7 +18,7 @@ const fs = require('fs'); const os = require('os'); const path = require('path'); const { execFileSync } = require('child_process'); -const { createStarter, startSiteHistory, STARTERS } = require('#dist/electron/project/starter.js'); +const { createStarter, scaffolderEnvironment, startSiteHistory, STARTERS } = require('#dist/electron/project/starter.js'); const failures = []; let checked = 0; @@ -120,6 +120,12 @@ console.log('Ready.'); calls()[0], ); check('the log says what it ran', log.join('').includes('> npm create lumos@latest my-site'), log.join('')); + + // Bun runs the scaffolder with its own `create`, which takes no `--yes` and no `--` separator. + const bunLog = []; + await createStarter({ npm, manager: 'bun', parentPath: parent, name: 'bun-site', onLog: (text) => bunLog.push(text) }); + check('with Bun chosen, it runs bun create without npm-only flags', calls().at(-1) === 'create lumos@latest bun-site --no-install', calls().at(-1)); + check('and the log names bun', bunLog.join('').includes('> bun create lumos@latest bun-site'), bunLog.join('')); check('and shows what it said', log.join('').includes('Ready.'), log.join('')); // The package is the site now. @@ -165,7 +171,7 @@ console.log('Ready.'); ); check('a starter nobody has heard of is refused', /not a starter/.test(await refuses({ starter: 'nope', name: 'x' }))); check('and so is a folder that is not there', /Choose where/.test(await refuses({ parentPath: path.join(root, 'nowhere'), name: 'x' }))); - check('a refused name never reaches the command line', calls().length === 1, calls().join(' | ')); + check('a refused name never reaches the command line (only the npm and Bun sites ran)', calls().length === 2, calls().join(' | ')); // A scaffolder that fails is a site that was not made, said out loud. { @@ -225,6 +231,29 @@ g('-c', 'user.email=t@t', '-c', 'user.name=T', check('a second site is made alongside the first', fs.existsSync(second.projectPath)); check('with its own name', JSON.parse(fs.readFileSync(path.join(second.projectPath, 'package.json'), 'utf8')).name === 'another-site'); + // The scaffolder's Windows fallback copies a folder with `copyFile`, which fails with EPERM. The preload it runs under + // turns that into a recursive copy, and leaves copying a file alone. + { + const from = path.join(root, 'skill'); + fs.mkdirSync(path.join(from, 'nested'), { recursive: true }); + fs.writeFileSync(path.join(from, 'nested', 'a.md'), 'skill'); + fs.writeFileSync(path.join(root, 'plain.txt'), 'plain'); + const probe = `import { copyFile } from 'node:fs/promises'; +await copyFile(${JSON.stringify(from)}, ${JSON.stringify(path.join(root, 'skill-copy'))}); +await copyFile(${JSON.stringify(path.join(root, 'plain.txt'))}, ${JSON.stringify(path.join(root, 'plain-copy.txt'))});`; + fs.writeFileSync(path.join(root, 'probe.mjs'), probe); + execFileSync(process.execPath, [path.join(root, 'probe.mjs')], { env: { ...process.env, ...scaffolderEnvironment() } }); + check('a folder given to copyFile is copied whole', fs.readFileSync(path.join(root, 'skill-copy', 'nested', 'a.md'), 'utf8') === 'skill'); + check('a file given to copyFile is still copied', fs.readFileSync(path.join(root, 'plain-copy.txt'), 'utf8') === 'plain'); + let plainFailed = false; + try { + execFileSync(process.execPath, [path.join(root, 'probe.mjs')], { stdio: 'pipe' }); + } catch { + plainFailed = true; + } + check('without the preload, copying a folder is refused as before', plainFailed || process.platform !== 'win32'); + } + fs.rmSync(root, { recursive: true, force: true }); if (failures.length) {