@stacksjs/actions 0.75.514 → 0.75.518
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/action.js +1 -1
- package/dist/auth/client-options.js +1 -1
- package/dist/auth/client.js +1 -1
- package/dist/auth/prune.js +1 -1
- package/dist/auth/setup.js +2 -2
- package/dist/blog-admin.js +3 -3
- package/dist/blog.js +23 -23
- package/dist/build/android-config.js +1 -1
- package/dist/build/android-icons.js +1 -1
- package/dist/build/android.js +1 -1
- package/dist/build/component-library.js +1 -1
- package/dist/build/core.js +1 -1
- package/dist/build/craft-entry.js +1 -1
- package/dist/build/craft-provenance.js +1 -1
- package/dist/build/desktop-macos.js +2 -2
- package/dist/build/desktop.js +2 -2
- package/dist/build/dmg-macos.js +1 -1
- package/dist/build/dmg.js +1 -1
- package/dist/build/docs.js +1 -1
- package/dist/build/frontend-static.js +5 -5
- package/dist/build/ios-config.js +3 -3
- package/dist/build/ios-shell.js +3 -3
- package/dist/build/ios-toolchain.js +2 -2
- package/dist/build/ios.js +2 -2
- package/dist/build/macos-native.js +3 -3
- package/dist/build/mobile-splash.js +1 -1
- package/dist/build/mobile-target.js +1 -1
- package/dist/build/native-screens.js +1 -1
- package/dist/build/native-sensors.js +1 -1
- package/dist/build/notarize.js +2 -2
- package/dist/build/run-build-step.js +1 -1
- package/dist/build/stacks.js +1 -1
- package/dist/build/views.js +1 -1
- package/dist/build.js +1 -1
- package/dist/bump.js +7 -7
- package/dist/calendar-version.js +1 -1
- package/dist/changelog.js +1 -1
- package/dist/check/ports.js +1 -1
- package/dist/commit.js +1 -1
- package/dist/database/seed.js +1 -1
- package/dist/deploy/create-receipt-rule.js +1 -1
- package/dist/deploy/hooks.js +1 -1
- package/dist/deploy/index.js +17 -17
- package/dist/deploy/stack.js +6 -6
- package/dist/dev/api.js +1 -1
- package/dist/dev/components.js +1 -1
- package/dist/dev/csrf.js +1 -1
- package/dist/dev/dashboard-native.js +1 -1
- package/dist/dev/dashboard-request-routing.js +1 -1
- package/dist/dev/dashboard-supervisor.js +2 -2
- package/dist/dev/dashboard-utils.js +1 -1
- package/dist/dev/dashboard.js +4 -4
- package/dist/dev/defaults-resources.js +1 -1
- package/dist/dev/docs.js +1 -1
- package/dist/dev/exit-with-parent.js +1 -1
- package/dist/dev/migrate-watcher.js +1 -1
- package/dist/dev/system-tray.js +2 -2
- package/dist/dev/tray-origin.js +1 -1
- package/dist/dev/views.js +1 -1
- package/dist/discover-packages.js +1 -1
- package/dist/domains/add.js +1 -1
- package/dist/domains/purchase.js +1 -1
- package/dist/domains/remove.js +1 -1
- package/dist/examples.js +1 -1
- package/dist/find-projects.js +1 -1
- package/dist/generate/action-types.js +3 -3
- package/dist/generate/erd.js +2 -2
- package/dist/generate/ide-helpers.js +1 -1
- package/dist/generate/images.js +1 -1
- package/dist/generate/index.js +1 -1
- package/dist/generate/lib-entries.js +1 -1
- package/dist/generate/vschema.js +2 -2
- package/dist/github-release.js +5 -5
- package/dist/helpers/api-host.js +3 -3
- package/dist/helpers/api-shutdown.js +1 -1
- package/dist/helpers/component-meta.js +3 -3
- package/dist/helpers/utils.js +1 -1
- package/dist/helpers/vscode-custom-data.js +1 -1
- package/dist/key-generate.js +1 -1
- package/dist/library/build.js +2 -2
- package/dist/library/entries.js +1 -1
- package/dist/library/globals.js +1 -1
- package/dist/library/manifest.js +2 -2
- package/dist/library/packages.js +1 -1
- package/dist/library/publish.js +2 -2
- package/dist/library-publish.js +1 -1
- package/dist/lint/files.js +1 -1
- package/dist/lint/lint.js +1 -1
- package/dist/lint/stx-gate.js +3 -3
- package/dist/make-command.js +2 -2
- package/dist/make-job.js +2 -2
- package/dist/make-policy.js +2 -2
- package/dist/make-resource.js +1 -1
- package/dist/make.js +7 -7
- package/dist/migrate/database.js +1 -1
- package/dist/migrate/fresh.js +1 -1
- package/dist/pantry-lock.js +1 -1
- package/dist/pantry-toolchain.js +1 -1
- package/dist/project-scripts.js +1 -1
- package/dist/publication-preflight.js +1 -1
- package/dist/queue/clear.js +1 -1
- package/dist/queue/dlq-purge.js +1 -1
- package/dist/queue/dlq-retry.js +1 -1
- package/dist/queue/dlq.js +2 -2
- package/dist/queue/failed.js +2 -2
- package/dist/queue/flush.js +1 -1
- package/dist/queue/inspect.js +6 -6
- package/dist/queue/list.js +2 -2
- package/dist/queue/monitor.js +5 -5
- package/dist/queue/options.js +1 -1
- package/dist/queue/pause.js +1 -1
- package/dist/queue/quarantine.js +1 -1
- package/dist/queue/resume.js +1 -1
- package/dist/queue/retry.js +1 -1
- package/dist/queue/schedule-list.js +2 -2
- package/dist/queue/status.js +2 -2
- package/dist/queue/unquarantine.js +1 -1
- package/dist/queue/work.js +1 -1
- package/dist/release-evidence.js +1 -1
- package/dist/release-notes.js +5 -5
- package/dist/release-preflight.js +2 -2
- package/dist/release-push-target.js +3 -3
- package/dist/release.js +1 -1
- package/dist/reviewos-evidence.js +1 -1
- package/dist/route/list.js +1 -1
- package/dist/saas/setup.js +1 -1
- package/dist/scaffold-crud.js +7 -7
- package/dist/search/flush.js +1 -1
- package/dist/search/import.js +1 -1
- package/dist/search/settings-list.js +1 -1
- package/dist/seo.js +4 -4
- package/dist/serve/api.js +1 -1
- package/dist/serve/dashboard-gate.js +1 -1
- package/dist/serve/dashboard.js +1 -1
- package/dist/setup/ssl.js +2 -2
- package/dist/stacks.js +1 -1
- package/dist/stx-source.js +1 -1
- package/dist/test/feature.js +1 -1
- package/dist/test/runner.js +1 -1
- package/dist/test/unit.js +1 -1
- package/dist/upgrade/binary.js +1 -1
- package/dist/upgrade/framework-hooks.d.ts +6 -0
- package/dist/upgrade/framework-hooks.js +1 -1
- package/dist/upgrade/framework-utils.js +2 -2
- package/dist/upgrade/framework.js +10 -10
- package/dist/upgrade/package-project.js +2 -2
- package/dist/upgrade/packages.js +23 -22
- package/dist/upgrade/route-actions.js +3 -3
- package/dist/upgrade/shell.js +4 -4
- package/dist/upgrade.js +1 -1
- package/package.json +40 -40
package/dist/build/ios-config.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{assertCraftSupportsNativeSensors,nativeSensorCapabilityKeys}from"./native-sensors";import{existsSync,readFileSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative,resolve}from"node:path";import{spotlightActivityTypes}from"@stacksjs/mobile";import{nativeScreenRoutes}from"./native-screens";export const NATIVE_APP_ROUTE="__app";const CAPABILITY_KEYS={speechRecognition:"enableSpeechRecognition",haptics:"enableHaptics",share:"enableShare",camera:"enableCamera",biometric:"enableBiometric",passkeys:"enablePasskeys",pushNotifications:"enablePushNotifications",notificationAttachments:"enableNotificationAttachments",secureStorage:"enableSecureStorage",geolocation:"enableGeolocation",backgroundLocation:"enableBackgroundLocation",clipboard:"enableClipboard",contacts:"enableContacts",calendar:"enableCalendar",localNotifications:"enableLocalNotifications",inAppPurchase:"enableInAppPurchase",keepAwake:"enableKeepAwake",orientationLock:"enableOrientationLock",deepLinks:"enableDeepLinks",qrScanner:"enableQRScanner",localNetwork:"enableLocalNetwork",filePicker:"enableFilePicker",fileDownload:"enableFileDownload",socialAuth:"enableSocialAuth",audioRecording:"enableAudioRecording",videoRecording:"enableVideoRecording",motionSensors:"enableMotionSensors",shakeGesture:"enableShakeGesture",wallet:"enableWallet",localDatabase:"enableLocalDatabase",bluetooth:"enableBluetooth",nfc:"enableNFC",healthKit:"enableHealthKit",appleMusic:"enableAppleMusic",heartRate:"enableHeartRate",backgroundAudio:"enableBackgroundAudio",scheduledWorkouts:"enableScheduledWorkouts",liveActivities:"enableLiveActivities",watchApp:"enableWatchApp",backgroundTasks:"enableBackgroundTasks",screenCapture:"enableScreenCapture",pdfViewer:"enablePDFViewer",augmentedReality:"enableAR",machineLearning:"enableMLKit"};export{CAPABILITY_KEYS as IOS_CAPABILITY_KEYS};export function iosCapabilityKeys(nativeSensorCapabilities){return{...CAPABILITY_KEYS,...nativeSensorCapabilityKeys("ios",nativeSensorCapabilities)}}export const IOS_UNMAPPED_CRAFT_FLAGS={},CRAFT_CAPABILITY_FLOORS={passkeys:"0.0.451",notificationAttachments:"0.0.464",audioRecording:"0.0.324",appleMusic:"0.0.144",heartRate:"0.0.152",backgroundAudio:"0.0.162",scheduledWorkouts:"0.0.163",shakeGesture:"0.0.435"};export function unsupportedCraftCapabilities(capabilities,version){const missing=[];for(const[capability,needs]of Object.entries(CRAFT_CAPABILITY_FLOORS))if(capabilities?.[capability]&&!Bun.semver.satisfies(version,`>=${needs}`))missing.push({capability,needs});return missing}export function assertCraftSupportsCapabilities(capabilities,version,source){const missing=unsupportedCraftCapabilities(capabilities,version);if(missing.length===0)return;const needed=missing.reduce((max,{needs})=>Bun.semver.order(needs,max)>0?needs:max,"0.0.0");throw Error(`The Craft iOS builder is craft-native ${version} (${source}), which would build the app without ${missing.map(({capability,needs})=>`ios.capabilities.${capability} (needs >= ${needs})`).join(", ")}. Install craft-native >= ${needed}: look for an older copy nested under @stacksjs/mobile in bun.lock, or raise the app's own craft-native pin.`)}export const CRAFT_CRASH_REPORTING_FLOOR="0.0.179";export function resolveCrashReporting(shared,platform){const set=(config)=>Object.fromEntries(Object.entries(config??{}).filter(([,value])=>value!==void 0&&value!=="")),merged={...set(shared),...set(platform)};if(!merged.key?.trim())return;if(merged.host){const url=new URL(normalizeMobileUrl(merged.host)),local=["localhost","127.0.0.1","::1","10.0.2.2"].includes(url.hostname);if(url.protocol!=="https:"&&!local)throw Error("crashReporting.host must use HTTPS outside local development");merged.host=url.origin}return merged}export function toCraftCrashReporting(config){if(!config?.key)return;const craft={key:config.key,host:config.host,environment:config.environment,release:config.release,sessions:config.sessions};for(const key of Object.keys(craft))if(craft[key]===void 0)delete craft[key];return craft}export function assertCraftSupportsCrashReporting(config,version,source){if(!config?.key||Bun.semver.satisfies(version,`>=${CRAFT_CRASH_REPORTING_FLOOR}`))return;throw Error(`The Craft builder is craft-native ${version} (${source}), which would build the app without crash reporting (crashReporting needs >= ${CRAFT_CRASH_REPORTING_FLOOR}). Install craft-native >= ${CRAFT_CRASH_REPORTING_FLOOR}: look for an older copy nested under @stacksjs/mobile in bun.lock, or raise the app's own craft-native pin.`)}export function normalizeMobileUrl(value){const input=value?.trim();if(!input)return;return new URL(/^https?:\/\//i.test(input)?input:`https://${input}`).toString().replace(/\/$/,"")}export function portablePaths(value,projectDir,appRoot){if(typeof value==="string")return isAbsolute(value)&&!relative(appRoot,value).startsWith("..")?relative(projectDir,value)||".":value;if(Array.isArray(value))return value.map((item)=>portablePaths(item,projectDir,appRoot));if(value&&typeof value==="object"){const out={};for(const[key,item]of Object.entries(value))out[key]=typeof item==="string"&&!/(?:path(?:dark)?|bundle)$|^(?:src|license)$/i.test(key)?item:portablePaths(item,projectDir,appRoot);return out}return value}export function resolveMobilePath(root,value){if(!value)return;return isAbsolute(value)?value:resolve(root,value)}export function resolveSwipeNavigation(config){if(config.swipeNavigation!==void 0)return config.swipeNavigation;return config.swipeBack==="webview"}export function toCraftIosConfig(config,nativeSensorCapabilities){assertCraftSupportsNativeSensors("ios",config.capabilities,nativeSensorCapabilities);const devServerURL=normalizeMobileUrl(config.url),trustedOrigins=new Set(config.trustedOrigins??[]);if(devServerURL)trustedOrigins.add(new URL(devServerURL).origin);const declaresAppBoundDomains=(config.appBoundDomains?.length??0)>0,craft={nativeFonts:config.nativeFonts,appName:config.appName,bundleId:config.bundleId,version:config.version,buildNumber:config.buildNumber,darkMode:config.darkMode,appearance:config.appearance,backgroundColor:config.backgroundColor,tintColor:config.tintColor,backgroundColorDark:config.backgroundColorDark,fontFamily:config.fontFamily,headingFontFamily:config.headingFontFamily,swipeNavigation:resolveSwipeNavigation(config),allowsLinkPreview:config.allowsLinkPreview,keyboardAccessory:config.keyboardAccessory,disableZoom:config.disableZoom,splashMaxSeconds:config.splashMaxSeconds,requestTimeoutSeconds:config.requestTimeoutSeconds,backgroundRefresh:config.backgroundRefresh,iosVersion:config.deploymentTarget,watchosVersion:config.watchDeploymentTarget,teamId:config.teamId,devServerURL,urlSchemes:config.urlSchemes,appShortcuts:config.appShortcuts,trustedOrigins:[...trustedOrigins],appBoundDomains:config.appBoundDomains,limitNavigationsToAppBoundDomains:config.limitNavigationsToAppBoundDomains??(declaresAppBoundDomains||void 0),associatedDomains:config.associatedDomains,renderer:config.renderer,nativeScreens:nativeScreenRoutes(config),nativeScreenConstraints:config.nativeScreenConstraints,nativeApp:config.nativeApp?NATIVE_APP_ROUTE:void 0,nativeScriptThread:config.nativeScriptThread,tabs:config.tabs,shareStorage:config.shareStorage,appGroups:config.appGroups,appIconPath:config.appIcon,privacy:config.privacy,usageDescriptions:config.usageDescriptions,healthKitBackgroundTypes:config.healthKitBackgroundTypes,healthKitBackgroundFrequency:config.healthKitBackgroundFrequency,orientations:config.orientations,deviceFamilies:config.deviceFamilies,crashReporting:toCraftCrashReporting(config.crashReporting)};for(const[key,nativeKey]of Object.entries(iosCapabilityKeys(nativeSensorCapabilities))){const enabled=config.capabilities?.[key];if(enabled!==void 0)craft[nativeKey]=enabled}if(config.capabilities?.backgroundLocation)craft.enableGeolocation=!0;for(const key of Object.keys(craft))if(craft[key]===void 0)delete craft[key];return craft}export function validateIosMobileConfig(config){if(config.tintColor!==void 0&&!/^#[0-9a-f]{6}$/i.test(config.tintColor))throw Error("ios.tintColor must be a #RRGGBB color");if(!config.appName?.trim())throw Error("config/mobile.ts must define ios.appName");if(!/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(config.bundleId))throw Error(`Invalid iOS bundle identifier: ${config.bundleId}`);if(config.url&&config.webAssets)throw Error("Choose either ios.url or ios.webAssets in config/mobile.ts, not both");if(!config.url&&!config.webAssets)throw Error("config/mobile.ts must define ios.url or ios.webAssets");if(config.renderer!==void 0&&config.renderer!=="web"&&config.renderer!=="native")throw Error(`ios.renderer must be 'web' or 'native', not ${String(config.renderer)}`);if(config.renderer==="native"){if(!Object.keys(config.nativeScreens??{}).length)throw Error("ios.renderer 'native' draws every screen natively: list them in ios.nativeScreens");if(config.webAssets)throw Error("ios.renderer 'native' has no web view to show ios.webAssets in: set ios.url to the app's site instead");if(config.fallbackWebAssets)throw Error("ios.fallbackWebAssets is the web view's offline page; ios.renderer 'native' has no web view")}if(config.fallbackWebAssets&&!config.url)throw Error("ios.fallbackWebAssets requires ios.url");if(config.deviceFamilies&&(config.deviceFamilies.length===0||config.deviceFamilies.some((family)=>family!=="iphone"&&family!=="ipad")))throw Error("ios.deviceFamilies must contain iphone and/or ipad");if(config.url){const url=new URL(normalizeMobileUrl(config.url)),isLocal=["localhost","127.0.0.1","::1"].includes(url.hostname);if(url.protocol!=="https:"&&!isLocal)throw Error("ios.url must use HTTPS outside local development")}for(const domain of config.associatedDomains??[])if(!/^(applinks|webcredentials|activitycontinuation):[^/\s]+$/.test(domain))throw Error(`Invalid iOS associated domain: ${domain}`);for(const key of["splashMaxSeconds","requestTimeoutSeconds"]){const value=config[key];if(value!==void 0&&(!Number.isFinite(value)||value<=0))throw Error(`ios.${key} must be a positive number of seconds`)}const refresh=config.backgroundRefresh;if(refresh){if(refresh.identifier!==void 0&&!/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(refresh.identifier))throw Error(`Invalid iOS background refresh identifier: ${refresh.identifier}`);if(refresh.minimumIntervalMinutes!==void 0&&(!Number.isFinite(refresh.minimumIntervalMinutes)||refresh.minimumIntervalMinutes<=0))throw Error("ios.backgroundRefresh.minimumIntervalMinutes must be a positive number of minutes")}if(config.capabilities?.watchApp){const target=Number.parseFloat(config.watchDeploymentTarget??"9.0");if(!Number.isFinite(target)||target<9)throw Error("ios.watchDeploymentTarget must be watchOS 9.0 or newer")}}const ACTIVITY_TYPES_BLOCK=/[ \t]*<key>NSUserActivityTypes<\/key>\s*<array>[\s\S]*?<\/array>\n?/;export function withActivityTypes(plist,types){const entries=types.map((type)=>` <string>${escapeXml(type)}</string>`).join(`
|
|
2
|
-
`)
|
|
1
|
+
import{assertCraftSupportsNativeSensors,nativeSensorCapabilityKeys}from"./native-sensors";import{existsSync,readFileSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative,resolve}from"node:path";import{spotlightActivityTypes}from"@stacksjs/mobile";import{nativeScreenRoutes}from"./native-screens";export const NATIVE_APP_ROUTE="__app";const CAPABILITY_KEYS={speechRecognition:"enableSpeechRecognition",haptics:"enableHaptics",share:"enableShare",camera:"enableCamera",biometric:"enableBiometric",passkeys:"enablePasskeys",pushNotifications:"enablePushNotifications",notificationAttachments:"enableNotificationAttachments",secureStorage:"enableSecureStorage",geolocation:"enableGeolocation",backgroundLocation:"enableBackgroundLocation",clipboard:"enableClipboard",contacts:"enableContacts",calendar:"enableCalendar",localNotifications:"enableLocalNotifications",inAppPurchase:"enableInAppPurchase",keepAwake:"enableKeepAwake",orientationLock:"enableOrientationLock",deepLinks:"enableDeepLinks",qrScanner:"enableQRScanner",localNetwork:"enableLocalNetwork",filePicker:"enableFilePicker",fileDownload:"enableFileDownload",socialAuth:"enableSocialAuth",audioRecording:"enableAudioRecording",videoRecording:"enableVideoRecording",motionSensors:"enableMotionSensors",shakeGesture:"enableShakeGesture",wallet:"enableWallet",localDatabase:"enableLocalDatabase",bluetooth:"enableBluetooth",nfc:"enableNFC",healthKit:"enableHealthKit",appleMusic:"enableAppleMusic",heartRate:"enableHeartRate",backgroundAudio:"enableBackgroundAudio",scheduledWorkouts:"enableScheduledWorkouts",liveActivities:"enableLiveActivities",watchApp:"enableWatchApp",backgroundTasks:"enableBackgroundTasks",screenCapture:"enableScreenCapture",pdfViewer:"enablePDFViewer",augmentedReality:"enableAR",machineLearning:"enableMLKit"};export{CAPABILITY_KEYS as IOS_CAPABILITY_KEYS};export function iosCapabilityKeys(nativeSensorCapabilities){return{...CAPABILITY_KEYS,...nativeSensorCapabilityKeys("ios",nativeSensorCapabilities)}}export const IOS_UNMAPPED_CRAFT_FLAGS={};export const CRAFT_CAPABILITY_FLOORS={passkeys:"0.0.451",notificationAttachments:"0.0.464",audioRecording:"0.0.324",appleMusic:"0.0.144",heartRate:"0.0.152",backgroundAudio:"0.0.162",scheduledWorkouts:"0.0.163",shakeGesture:"0.0.435"};export function unsupportedCraftCapabilities(capabilities,version){const missing=[];for(const[capability,needs]of Object.entries(CRAFT_CAPABILITY_FLOORS)){if(capabilities?.[capability]&&!Bun.semver.satisfies(version,`>=${needs}`))missing.push({capability,needs})}return missing}export function assertCraftSupportsCapabilities(capabilities,version,source){const missing=unsupportedCraftCapabilities(capabilities,version);if(missing.length===0)return;const needed=missing.reduce((max,{needs})=>Bun.semver.order(needs,max)>0?needs:max,"0.0.0");throw new Error(`The Craft iOS builder is craft-native ${version} (${source}), which would build the app without `+`${missing.map(({capability,needs})=>`ios.capabilities.${capability} (needs >= ${needs})`).join(", ")}. `+`Install craft-native >= ${needed}: look for an older copy nested under @stacksjs/mobile in bun.lock, `+"or raise the app's own craft-native pin.")}export const CRAFT_CRASH_REPORTING_FLOOR="0.0.179";export function resolveCrashReporting(shared,platform){const set=(config)=>Object.fromEntries(Object.entries(config??{}).filter(([,value])=>value!==undefined&&value!==""));const merged={...set(shared),...set(platform)};if(!merged.key?.trim())return;if(merged.host){const url=new URL(normalizeMobileUrl(merged.host));const local=["localhost","127.0.0.1","::1","10.0.2.2"].includes(url.hostname);if(url.protocol!=="https:"&&!local)throw new Error("crashReporting.host must use HTTPS outside local development");merged.host=url.origin}return merged}export function toCraftCrashReporting(config){if(!config?.key)return;const craft={key:config.key,host:config.host,environment:config.environment,release:config.release,sessions:config.sessions};for(const key of Object.keys(craft)){if(craft[key]===undefined)delete craft[key]}return craft}export function assertCraftSupportsCrashReporting(config,version,source){if(!config?.key||Bun.semver.satisfies(version,`>=${CRAFT_CRASH_REPORTING_FLOOR}`))return;throw new Error(`The Craft builder is craft-native ${version} (${source}), which would build the app without crash reporting `+`(crashReporting needs >= ${CRAFT_CRASH_REPORTING_FLOOR}). Install craft-native >= ${CRAFT_CRASH_REPORTING_FLOOR}: `+"look for an older copy nested under @stacksjs/mobile in bun.lock, or raise the app's own craft-native pin.")}export function normalizeMobileUrl(value){const input=value?.trim();if(!input)return;return new URL(/^https?:\/\//i.test(input)?input:`https://${input}`).toString().replace(/\/$/,"")}export function portablePaths(value,projectDir,appRoot){if(typeof value==="string")return isAbsolute(value)&&!relative(appRoot,value).startsWith("..")?relative(projectDir,value)||".":value;if(Array.isArray(value))return value.map((item)=>portablePaths(item,projectDir,appRoot));if(value&&typeof value==="object"){const out={};for(const[key,item]of Object.entries(value))out[key]=typeof item==="string"&&!/(?:path(?:dark)?|bundle)$|^(?:src|license)$/i.test(key)?item:portablePaths(item,projectDir,appRoot);return out}return value}export function resolveMobilePath(root,value){if(!value)return;return isAbsolute(value)?value:resolve(root,value)}export function resolveSwipeNavigation(config){if(config.swipeNavigation!==undefined)return config.swipeNavigation;return config.swipeBack==="webview"}export function toCraftIosConfig(config,nativeSensorCapabilities){assertCraftSupportsNativeSensors("ios",config.capabilities,nativeSensorCapabilities);const devServerURL=normalizeMobileUrl(config.url);const trustedOrigins=new Set(config.trustedOrigins??[]);if(devServerURL)trustedOrigins.add(new URL(devServerURL).origin);const declaresAppBoundDomains=(config.appBoundDomains?.length??0)>0;const craft={nativeFonts:config.nativeFonts,appName:config.appName,bundleId:config.bundleId,version:config.version,buildNumber:config.buildNumber,darkMode:config.darkMode,appearance:config.appearance,backgroundColor:config.backgroundColor,tintColor:config.tintColor,backgroundColorDark:config.backgroundColorDark,fontFamily:config.fontFamily,headingFontFamily:config.headingFontFamily,swipeNavigation:resolveSwipeNavigation(config),allowsLinkPreview:config.allowsLinkPreview,keyboardAccessory:config.keyboardAccessory,disableZoom:config.disableZoom,splashMaxSeconds:config.splashMaxSeconds,requestTimeoutSeconds:config.requestTimeoutSeconds,backgroundRefresh:config.backgroundRefresh,iosVersion:config.deploymentTarget,watchosVersion:config.watchDeploymentTarget,teamId:config.teamId,devServerURL,urlSchemes:config.urlSchemes,appShortcuts:config.appShortcuts,trustedOrigins:[...trustedOrigins],appBoundDomains:config.appBoundDomains,limitNavigationsToAppBoundDomains:config.limitNavigationsToAppBoundDomains??(declaresAppBoundDomains||undefined),associatedDomains:config.associatedDomains,renderer:config.renderer,nativeScreens:nativeScreenRoutes(config),nativeScreenConstraints:config.nativeScreenConstraints,nativeApp:config.nativeApp?NATIVE_APP_ROUTE:undefined,nativeScriptThread:config.nativeScriptThread,tabs:config.tabs,shareStorage:config.shareStorage,appGroups:config.appGroups,appIconPath:config.appIcon,privacy:config.privacy,usageDescriptions:config.usageDescriptions,healthKitBackgroundTypes:config.healthKitBackgroundTypes,healthKitBackgroundFrequency:config.healthKitBackgroundFrequency,orientations:config.orientations,deviceFamilies:config.deviceFamilies,crashReporting:toCraftCrashReporting(config.crashReporting)};for(const[key,nativeKey]of Object.entries(iosCapabilityKeys(nativeSensorCapabilities))){const enabled=config.capabilities?.[key];if(enabled!==undefined)craft[nativeKey]=enabled}if(config.capabilities?.backgroundLocation)craft.enableGeolocation=true;for(const key of Object.keys(craft)){if(craft[key]===undefined)delete craft[key]}return craft}export function validateIosMobileConfig(config){if(config.tintColor!==undefined&&!/^#[0-9a-f]{6}$/i.test(config.tintColor))throw new Error("ios.tintColor must be a #RRGGBB color");if(!config.appName?.trim())throw new Error("config/mobile.ts must define ios.appName");if(!/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(config.bundleId)){throw new Error(`Invalid iOS bundle identifier: ${config.bundleId}`)}if(config.url&&config.webAssets){throw new Error("Choose either ios.url or ios.webAssets in config/mobile.ts, not both")}if(!config.url&&!config.webAssets){throw new Error("config/mobile.ts must define ios.url or ios.webAssets")}if(config.renderer!==undefined&&config.renderer!=="web"&&config.renderer!=="native")throw new Error(`ios.renderer must be 'web' or 'native', not ${String(config.renderer)}`);if(config.renderer==="native"){if(!Object.keys(config.nativeScreens??{}).length)throw new Error("ios.renderer 'native' draws every screen natively: list them in ios.nativeScreens");if(config.webAssets)throw new Error("ios.renderer 'native' has no web view to show ios.webAssets in: set ios.url to the app's site instead");if(config.fallbackWebAssets)throw new Error("ios.fallbackWebAssets is the web view's offline page; ios.renderer 'native' has no web view")}if(config.fallbackWebAssets&&!config.url){throw new Error("ios.fallbackWebAssets requires ios.url")}if(config.deviceFamilies&&(config.deviceFamilies.length===0||config.deviceFamilies.some((family)=>family!=="iphone"&&family!=="ipad"))){throw new Error("ios.deviceFamilies must contain iphone and/or ipad")}if(config.url){const url=new URL(normalizeMobileUrl(config.url));const isLocal=["localhost","127.0.0.1","::1"].includes(url.hostname);if(url.protocol!=="https:"&&!isLocal)throw new Error("ios.url must use HTTPS outside local development")}for(const domain of config.associatedDomains??[]){if(!/^(applinks|webcredentials|activitycontinuation):[^/\s]+$/.test(domain)){throw new Error(`Invalid iOS associated domain: ${domain}`)}}for(const key of["splashMaxSeconds","requestTimeoutSeconds"]){const value=config[key];if(value!==undefined&&(!Number.isFinite(value)||value<=0))throw new Error(`ios.${key} must be a positive number of seconds`)}const refresh=config.backgroundRefresh;if(refresh){if(refresh.identifier!==undefined&&!/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(refresh.identifier))throw new Error(`Invalid iOS background refresh identifier: ${refresh.identifier}`);if(refresh.minimumIntervalMinutes!==undefined&&(!Number.isFinite(refresh.minimumIntervalMinutes)||refresh.minimumIntervalMinutes<=0))throw new Error("ios.backgroundRefresh.minimumIntervalMinutes must be a positive number of minutes")}if(config.capabilities?.watchApp){const target=Number.parseFloat(config.watchDeploymentTarget??"9.0");if(!Number.isFinite(target)||target<9)throw new Error("ios.watchDeploymentTarget must be watchOS 9.0 or newer")}}const ACTIVITY_TYPES_BLOCK=/[ \t]*<key>NSUserActivityTypes<\/key>\s*<array>[\s\S]*?<\/array>\n?/;export function withActivityTypes(plist,types){const entries=types.map((type)=>` <string>${escapeXml(type)}</string>`).join(`
|
|
2
|
+
`);const block=types.length===0?"":` <key>NSUserActivityTypes</key>
|
|
3
3
|
<array>
|
|
4
4
|
${entries}
|
|
5
5
|
</array>
|
|
6
|
-
`;if(ACTIVITY_TYPES_BLOCK.test(plist))return plist.replace(ACTIVITY_TYPES_BLOCK,block);if(block==="")return plist;const close=plist.lastIndexOf("</dict>");if(close<0)throw Error("Info.plist has no root dictionary to declare activity types in");return plist.slice(0,close)+block+plist.slice(close)}function escapeXml(value){return value.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}export function writeIosActivityTypes(output,config){const types=[...new Set([...spotlightActivityTypes(config.spotlight,config.ios.bundleId),...(config.ios.appShortcuts??[]).map((shortcut)=>`${config.ios.bundleId}.${shortcut.id}`)])]
|
|
6
|
+
`;if(ACTIVITY_TYPES_BLOCK.test(plist))return plist.replace(ACTIVITY_TYPES_BLOCK,block);if(block==="")return plist;const close=plist.lastIndexOf("</dict>");if(close<0)throw new Error("Info.plist has no root dictionary to declare activity types in");return plist.slice(0,close)+block+plist.slice(close)}function escapeXml(value){return value.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}export function writeIosActivityTypes(output,config){const types=[...new Set([...spotlightActivityTypes(config.spotlight,config.ios.bundleId),...(config.ios.appShortcuts??[]).map((shortcut)=>`${config.ios.bundleId}.${shortcut.id}`)])];const path=join(output,"Info.plist");if(types.length===0||!existsSync(path))return null;writeFileSync(path,withActivityTypes(readFileSync(path,"utf8"),types));return types}export function resolveNativeFonts(fonts,root){if(!fonts)return;return Object.fromEntries(Object.entries(fonts).map(([family,file])=>[family,{src:resolve(root,file.src),...file.license?{license:resolve(root,file.license)}:{}}]))}export const CRAFT_NATIVE_FONTS_FLOOR="0.0.229";export function assertCraftSupportsChromeFonts(config,version){if(config.fontFamily===undefined&&config.headingFontFamily===undefined||version&&Bun.semver.satisfies(version,">=0.0.398"))return;throw new Error("fontFamily / headingFontFamily need craft-native >= 0.0.398; install a published version that draws native chrome in the app's fonts.")}export function assertCraftSupportsTint(color,version){if(color===undefined||version&&Bun.semver.satisfies(version,">=0.0.380"))return;throw new Error("ios.tintColor needs craft-native >= 0.0.380; install a published version that supports native tint in both runtimes.")}export function assertCraftSupportsAppShortcuts(shortcuts,version){if(!shortcuts?.length)return;if(version&&Bun.semver.satisfies(version,">=0.0.237"))return;throw new Error("appShortcuts needs craft-native >= 0.0.237; install a published version that generates App Intents.")}export function assertCraftSupportsNativeFonts(fonts,version){if(!Object.keys(fonts??{}).length)return;if(version&&Bun.semver.satisfies(version,`>=${CRAFT_NATIVE_FONTS_FLOOR}`))return;throw new Error(`nativeFonts needs craft-native >= ${CRAFT_NATIVE_FONTS_FLOOR}; install a published version that bundles native fonts.`)}
|
package/dist/build/ios-shell.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{chmodSync,mkdirSync,rmSync,writeFileSync}from"node:fs";import{join}from"node:path";export function writeIosShellSupport(output,config,bunVersion=Bun.version,crashReporting){const version=config.shell?.bunVersion??bunVersion;if(!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version))throw Error("ios.shell.bunVersion must be a Bun version such as 1.3.14");writeFileSync(join(output,".gitignore"),`# Native sources are restored from the locked Craft package.
|
|
1
|
+
import{chmodSync,mkdirSync,rmSync,writeFileSync}from"node:fs";import{join}from"node:path";export function writeIosShellSupport(output,config,bunVersion=Bun.version,crashReporting){const version=config.shell?.bunVersion??bunVersion;if(!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version))throw new Error("ios.shell.bunVersion must be a Bun version such as 1.3.14");writeFileSync(join(output,".gitignore"),`# Native sources are restored from the locked Craft package.
|
|
2
2
|
*.swift
|
|
3
3
|
# Compiled screens ship from dist/; this is the compiler's copy.
|
|
4
4
|
/native-screens.js
|
|
5
5
|
/native-screens/
|
|
6
|
-
`);const scripts=join(output,"ci_scripts");mkdirSync(scripts,{recursive
|
|
6
|
+
`);const scripts=join(output,"ci_scripts");mkdirSync(scripts,{recursive:true});writeFileSync(join(scripts,"bunfig.toml"),`preload = []
|
|
7
7
|
`);const path=join(scripts,"ci_post_clone.sh");writeFileSync(path,`#!/bin/sh
|
|
8
8
|
set -eu
|
|
9
9
|
PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
|
@@ -40,4 +40,4 @@ for DSYM in "\${CI_ARCHIVE_PATH}"/dSYMs/*.dSYM; do
|
|
|
40
40
|
rm -f "$OUT"
|
|
41
41
|
done
|
|
42
42
|
exit 0
|
|
43
|
-
`}function writeDsymUpload(scripts,crashReporting){const path=join(scripts,"ci_post_xcodebuild.sh");if(!crashReporting?.key||crashReporting.uploadSymbols
|
|
43
|
+
`}function writeDsymUpload(scripts,crashReporting){const path=join(scripts,"ci_post_xcodebuild.sh");if(!crashReporting?.key||crashReporting.uploadSymbols===false){rmSync(path,{force:true});return}writeFileSync(path,renderDsymUpload(crashReporting.host??"https://bughq.org"));chmodSync(path,493)}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{existsSync,readdirSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";export const XCODEGEN_PACKAGE="github.com/yonaskolb/XcodeGen"
|
|
2
|
-
${detail}`:""}`)}}export function xcodeDeveloperDir(){try{const result=Bun.spawnSync(["xcode-select","--print-path"],{stdout:"pipe",stderr:"ignore"})
|
|
1
|
+
import{existsSync,readdirSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";export const XCODEGEN_PACKAGE="github.com/yonaskolb/XcodeGen";export const DEFAULT_IOS_DEPENDENCIES={[XCODEGEN_PACKAGE]:"^2.46.0"};export const XCODE_NOTE="Xcode itself does not come from Pantry: install it from the Mac App Store or developer.apple.com, then select it with `sudo xcode-select --switch /Applications/Xcode.app`.";export class IosToolchainError extends Error{name="IosToolchainError"}const realFilesystem={exists:existsSync,list:(path)=>{try{return readdirSync(path)}catch{return[]}}};export function pantryPackageRoots(projectRoot,env=process.env){const home=env.HOME||homedir();const data=env.XDG_DATA_HOME||join(home,".local","share");return[join(projectRoot,"pantry"),join(data,"pantry","global","packages"),"/usr/local/packages"]}export function findPantryProgram(pkg,constraint,program,roots,fs=realFilesystem){for(const root of roots){const versions=fs.list(join(root,pkg)).filter((entry)=>/^v\d+\.\d+\.\d+$/.test(entry)).map((entry)=>entry.slice(1)).filter((version)=>Bun.semver.satisfies(version,constraint)).sort((a,b)=>Bun.semver.order(b,a));for(const version of versions){const path=join(root,pkg,`v${version}`,"bin",program);if(fs.exists(path))return{pkg,constraint,version,path}}}return null}export async function loadIosDependencies(projectRoot){const depsPath=join(projectRoot,"config","deps.ts");if(!existsSync(depsPath))return{...DEFAULT_IOS_DEPENDENCIES};const deps=await import(pathToFileURL(depsPath).href);return{...DEFAULT_IOS_DEPENDENCIES,...deps.iosDependencies??{}}}export function pantryInstallArgs(dependencies){return["install","--user","--no-save",...Object.entries(dependencies).map(([pkg,constraint])=>`${pkg}@${constraint}`)]}export function pantryExecutable(projectRoot,env=process.env,exists=existsSync){const home=env.HOME||homedir();const data=env.XDG_DATA_HOME||join(home,".local","share");const candidates=[env.PANTRY_BIN,join(projectRoot,"pantry",".bin","pantry"),join(home,".local","bin","pantry"),join(data,"pantry","global","bin","pantry")];return candidates.find((candidate)=>candidate&&exists(candidate))??"pantry"}export function missingToolMessage(pkg,constraint,program){return`${program} ${constraint} is not installed through Pantry, and the iOS build only runs the version config/deps.ts pins (\`iosDependencies\`, else the framework default). Run \`buddy setup:ios\`, or \`pantry install --user ${pkg}@${constraint}\`, then build again. `+XCODE_NOTE}export async function resolveXcodegen(projectRoot,options={}){const dependencies=await loadIosDependencies(projectRoot);const constraint=dependencies[XCODEGEN_PACKAGE];const tool=findPantryProgram(XCODEGEN_PACKAGE,constraint,"xcodegen",pantryPackageRoots(projectRoot,options.env),options.fs);if(!tool)throw new IosToolchainError(missingToolMessage(XCODEGEN_PACKAGE,constraint,"xcodegen"));const presets=xcodegenPresets(tool);if(!(options.fs??realFilesystem).exists(presets)){throw new IosToolchainError(`xcodegen ${tool.version} at ${tool.path} has no setting presets (${presets}), so the project it generates would lose its base build settings. Remove ${dirname(dirname(tool.path))} and run \`buddy setup:ios\` to reinstall it.`)}return tool}export function xcodegenPresets(tool){return join(dirname(dirname(tool.path)),"share","xcodegen","SettingPresets","base.yml")}export function generateXcodeProject(xcodegen,output){const result=Bun.spawnSync([xcodegen.path,"generate","--quiet"],{cwd:output,stdout:"pipe",stderr:"pipe"});if(result.exitCode!==0){const detail=`${result.stderr.toString()}${result.stdout.toString()}`.trim();throw new IosToolchainError(`xcodegen ${xcodegen.version} (${xcodegen.path}) could not generate the Xcode project in ${output}${detail?`:
|
|
2
|
+
${detail}`:""}`)}}export function xcodeDeveloperDir(){try{const result=Bun.spawnSync(["xcode-select","--print-path"],{stdout:"pipe",stderr:"ignore"});const path=result.stdout.toString().trim();return result.exitCode===0&&path&&!path.includes("CommandLineTools")?path:null}catch{return null}}
|
package/dist/build/ios.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync,readFileSync,writeFileSync}from"node:fs";import{pathToFileURL}from"node:url";import process from"node:process";import{log}from"@stacksjs/cli";import{applyWithheldEnv}from"@stacksjs/env";import{projectPath,storagePath}from"@stacksjs/path";import{craftBuilderSpecifier,craftBuilderVersion}from"./craft-entry";import{resolveCraftBuilderProvenance}from"./craft-provenance";import{assertCraftSupportsAppShortcuts,assertCraftSupportsCapabilities,assertCraftSupportsCrashReporting,portablePaths,resolveCrashReporting,resolveMobilePath,resolveNativeFonts,assertCraftSupportsNativeFonts,toCraftIosConfig,validateIosMobileConfig,writeIosActivityTypes}from"./ios-config";import{generateXcodeProject,resolveXcodegen}from"./ios-toolchain";import{assertCraftSupportsRouteConstraints,compileNativeScreens}from"./native-screens";import{writeIosShellSupport}from"./ios-shell";import{reportMobileBuildTarget}from"./mobile-target";import{resolveMobileSplash}from"./mobile-splash";import{assertCraftSupportsChromeFonts,assertCraftSupportsTint}from"./ios-config";process.exitCode=1;function craftIosEntry(){const explicit=process.env.CRAFT_IOS_SRC;return explicit?pathToFileURL(explicit).href:craftBuilderSpecifier("ios",projectPath())}async function loadCraftIosBuilder(){try{return await import(craftIosEntry())}catch(error){throw Error("Craft iOS builder is unavailable. Install the current craft-native package or set CRAFT_IOS_SRC to packages/ios/src/index.ts in a Craft checkout.",{cause:error})}}const configPath=projectPath("config/mobile.ts");if(!existsSync(configPath))throw Error("Missing config/mobile.ts. Add an ios section before running `buddy build:ios`.")
|
|
2
|
-
`);writeFileSync(`${output}/stacks-mobile.json`,`${JSON.stringify(portablePaths({schemaVersion:"1.0.0",platform:"ios",sourceRevision,source:native?{kind:"native",site:craftConfig.devServerURL}:webAssets?{kind:"bundled",path:webAssets}:{kind:"remote",url:craftConfig.devServerURL,fallback:fallbackWebAssets?{kind:"bundled",path:fallbackWebAssets}:
|
|
1
|
+
import{existsSync,readFileSync,writeFileSync}from"node:fs";import{pathToFileURL}from"node:url";import process from"node:process";import{log}from"@stacksjs/cli";import{applyWithheldEnv}from"@stacksjs/env";import{projectPath,storagePath}from"@stacksjs/path";import{craftBuilderSpecifier,craftBuilderVersion}from"./craft-entry";import{resolveCraftBuilderProvenance}from"./craft-provenance";import{assertCraftSupportsAppShortcuts,assertCraftSupportsCapabilities,assertCraftSupportsCrashReporting,portablePaths,resolveCrashReporting,resolveMobilePath,resolveNativeFonts,assertCraftSupportsNativeFonts,toCraftIosConfig,validateIosMobileConfig,writeIosActivityTypes}from"./ios-config";import{generateXcodeProject,resolveXcodegen}from"./ios-toolchain";import{assertCraftSupportsRouteConstraints,compileNativeScreens}from"./native-screens";import{writeIosShellSupport}from"./ios-shell";import{reportMobileBuildTarget}from"./mobile-target";import{resolveMobileSplash}from"./mobile-splash";import{assertCraftSupportsChromeFonts,assertCraftSupportsTint}from"./ios-config";process.exitCode=1;function craftIosEntry(){const explicit=process.env.CRAFT_IOS_SRC;return explicit?pathToFileURL(explicit).href:craftBuilderSpecifier("ios",projectPath())}async function loadCraftIosBuilder(){try{return await import(craftIosEntry())}catch(error){throw new Error("Craft iOS builder is unavailable. Install the current craft-native package or set CRAFT_IOS_SRC to packages/ios/src/index.ts in a Craft checkout.",{cause:error})}}const configPath=projectPath("config/mobile.ts");if(!existsSync(configPath)){throw new Error("Missing config/mobile.ts. Add an ios section before running `buddy build:ios`.")}applyWithheldEnv();const configModule=await import(`${pathToFileURL(configPath).href}?t=${Date.now()}`);const mobile=configModule.default;const config=mobile.ios;validateIosMobileConfig(config);if(config.swipeNavigation===true&&config.swipeBack!=="webview")log.warn("ios.swipeNavigation turns on WebKit's edge swipe alongside the stx router's own. Remove it, or set ios.swipeBack: 'webview' for an app not on the router.");const output=resolveMobilePath(projectPath(),config.output)??storagePath("framework/mobile/ios");const generateProject=process.env.STACKS_IOS_SKIP_XCODEGEN!=="1";const xcodegen=generateProject?await resolveXcodegen(projectPath()):null;const webAssets=resolveMobilePath(projectPath(),config.webAssets);const fallbackWebAssets=resolveMobilePath(projectPath(),config.fallbackWebAssets);const crashReporting=resolveCrashReporting(mobile.crashReporting,config.crashReporting);const builder=await loadCraftIosBuilder();assertCraftSupportsRouteConstraints(config.nativeScreenConstraints,builder.nativeRouteConstraints,"ios");const craftConfig=toCraftIosConfig({...config,crashReporting},builder.nativeSensorCapabilities);craftConfig.nativeFonts=resolveNativeFonts(config.nativeFonts,projectPath());craftConfig.appIconPath=resolveMobilePath(projectPath(),config.appIcon);const nativeBundle=await compileNativeScreens(config,projectPath(),output,undefined,"ios",{routes:builder.nativeRouteBundles===true,runtime:builder.nativeRouteRuntime===true,messages:builder.nativeMessages===true});if(nativeBundle){craftConfig.nativeBundle=nativeBundle.outFile;for(const diagnostic of nativeBundle.diagnostics??[])log.warn(`${diagnostic.file?`${diagnostic.file}: `:""}${diagnostic.message}`);log.info(`Compiled ${Object.keys(config.nativeScreens??{}).length} native screen path(s) into ${nativeBundle.outFile}`)}const craftVersion=craftBuilderVersion(craftIosEntry(),projectPath());assertCraftSupportsNativeFonts(config.nativeFonts,craftVersion?.version);assertCraftSupportsTint(config.tintColor,craftVersion?.version);assertCraftSupportsChromeFonts(config,craftVersion?.version);assertCraftSupportsAppShortcuts(config.appShortcuts,craftVersion?.version);if(craftVersion){assertCraftSupportsCapabilities(config.capabilities,craftVersion.version,craftVersion.manifest);assertCraftSupportsCrashReporting(crashReporting,craftVersion.version,craftVersion.manifest)}else log.warn(`Could not read the craft-native version behind ${craftIosEntry()}, so the build cannot check that it supports every capability config/mobile.ts turns on.`);const splash=await resolveMobileSplash({platform:"ios",splash:config.splash,appIcon:config.appIcon,backgroundColor:config.backgroundColor,backgroundColorDark:config.backgroundColorDark,tintColor:config.tintColor},storagePath("framework/mobile/splash"),projectPath(),craftVersion?.version,log);craftConfig.splashImagePath=splash?.image;craftConfig.splashImagePathDark=splash?.imageDark;await builder.init({name:config.appName,bundleId:config.bundleId,teamId:config.teamId,output,config:craftConfig});const native=config.renderer==="native";if(native&&!nativeBundle)throw new Error("ios.renderer 'native' needs native screens to draw: list them in ios.nativeScreens");reportMobileBuildTarget({renderer:config.renderer,site:craftConfig.devServerURL,nativeBundle:nativeBundle?.outFile,webAssets,fallbackWebAssets,production:process.env.NODE_ENV==="production"},log);await builder.build(native?{output,nativeBundlePath:nativeBundle.outFile,generateProject:false}:{output,htmlPath:webAssets??fallbackWebAssets,devServer:craftConfig.devServerURL,generateProject:false});if(xcodegen){generateXcodeProject(xcodegen,output);log.info(`Generated the Xcode project with xcodegen ${xcodegen.version} from Pantry`)}writeIosShellSupport(output,config,undefined,crashReporting);if(crashReporting)log.info(`Crash reporting to ${crashReporting.host??"https://bughq.org"}${crashReporting.uploadSymbols===false?"":": dSYMs upload from Xcode Cloud when BUGHQ_UPLOAD_TOKEN is set in the workflow"}`);const activityTypes=writeIosActivityTypes(output,mobile);if(activityTypes)log.info(`Declared ${activityTypes.length} activity types, so a tapped Spotlight or Siri entry reaches the app`);const sourceRevision=Bun.spawnSync(["git","rev-parse","HEAD"],{cwd:projectPath()}).stdout.toString().trim();const craftConfigPath=`${output}/craft.config.json`;const generatedConfig=portablePaths(JSON.parse(readFileSync(craftConfigPath,"utf8")),output,projectPath());writeFileSync(craftConfigPath,`${JSON.stringify(generatedConfig,null,2)}
|
|
2
|
+
`);writeFileSync(`${output}/stacks-mobile.json`,`${JSON.stringify(portablePaths({schemaVersion:"1.0.0",platform:"ios",sourceRevision,source:native?{kind:"native",site:craftConfig.devServerURL}:webAssets?{kind:"bundled",path:webAssets}:{kind:"remote",url:craftConfig.devServerURL,fallback:fallbackWebAssets?{kind:"bundled",path:fallbackWebAssets}:undefined},capabilities:config.capabilities??{},builder:resolveCraftBuilderProvenance(process.env.CRAFT_IOS_SRC),craft:generatedConfig},output,projectPath()),null,2)}
|
|
3
3
|
`);log.success(`Built the Craft iOS project in ${output}`);await log.flush();process.exitCode=0;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{existsSync,mkdirSync,readdirSync,readFileSync,writeFileSync}from"node:fs";import{dirname,join,resolve}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";import{log}from"@stacksjs/cli";import{AGENT_MANIFEST,agentHostArguments,desktopLauncherCompileArgs,macosOutputDirectory,macosScreens,renderAgentEntry,validateMacosDesktop}from"@stacksjs/desktop-build";import{projectPath,storagePath}from"@stacksjs/path";import{craftBuilderVersion}from"./craft-entry";function entryFile(entry,root){try{return entry.startsWith("file:")?new URL(entry).pathname:Bun.resolveSync(entry,root)}catch{return null}}export function craftSupportsWebkit(source){return/\.webkit\b|[{,]\s*webkit\s*[,}=]/.test(source)}function craftMacosEntry(root){if(process.env.CRAFT_MACOS_SRC)return pathToFileURL(process.env.CRAFT_MACOS_SRC).href;try{const desktop=Bun.resolveSync("@stacksjs/desktop-build/package.json",root);return pathToFileURL(Bun.resolveSync("craft-native/macos",dirname(desktop))).href}catch{return"craft-native/macos"}}function hostKey(entry,root,webkit
|
|
1
|
+
import{createHash}from"node:crypto";import{existsSync,mkdirSync,readdirSync,readFileSync,writeFileSync}from"node:fs";import{dirname,join,resolve}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";import{log}from"@stacksjs/cli";import{AGENT_MANIFEST,agentHostArguments,desktopLauncherCompileArgs,macosOutputDirectory,macosScreens,renderAgentEntry,validateMacosDesktop}from"@stacksjs/desktop-build";import{projectPath,storagePath}from"@stacksjs/path";import{craftBuilderVersion}from"./craft-entry";function entryFile(entry,root){try{return entry.startsWith("file:")?new URL(entry).pathname:Bun.resolveSync(entry,root)}catch{return null}}export function craftSupportsWebkit(source){return/\.webkit\b|[{,]\s*webkit\s*[,}=]/.test(source)}function craftMacosEntry(root){if(process.env.CRAFT_MACOS_SRC)return pathToFileURL(process.env.CRAFT_MACOS_SRC).href;try{const desktop=Bun.resolveSync("@stacksjs/desktop-build/package.json",root);return pathToFileURL(Bun.resolveSync("craft-native/macos",dirname(desktop))).href}catch{return"craft-native/macos"}}function hostKey(entry,root,webkit=false){const hash=createHash("sha256");if(webkit)hash.update("webkit");const path=entry.startsWith("file:")?new URL(entry).pathname:entry;const version=craftBuilderVersion(entry,root)?.version;hash.update(version??"unversioned");if(process.env.CRAFT_MACOS_SRC||!version){const templates=join(dirname(path),"../templates");if(existsSync(templates))for(const file of readdirSync(templates).sort())hash.update(readFileSync(join(templates,file)))}return hash.digest("hex").slice(0,16)}export async function prepareMacosNative(config,options={}){const root=options.root??projectPath();const errors=validateMacosDesktop(config);if(errors.length)throw new Error(`config/desktop.ts macos is not buildable:
|
|
2
2
|
${errors.map((error)=>` - ${error}`).join(`
|
|
3
|
-
`)}`);if(process.platform!=="darwin")throw Error("The native macOS app builds on macOS");const output=macosOutputDirectory(root,config)
|
|
4
|
-
${compile.stderr.toString().trim()||compile.stdout.toString().trim()}`);return{launcher,manifest:{appName:config.appName,bundleId:config.bundleId,version:config.version,hostArguments:agentHostArguments(config),...config.agent.port?{port:config.agent.port}:{},...config.agent.staticDir?{staticDir:resolve(prepared.root,config.agent.staticDir)}:{},...agentResources(config,prepared.root),appRoutes
|
|
3
|
+
`)}`);if(process.platform!=="darwin")throw new Error("The native macOS app builds on macOS");const output=macosOutputDirectory(root,config);const work=join(output,".build");mkdirSync(work,{recursive:true});const screens=Object.fromEntries(Object.entries(macosScreens(config)).map(([name,file])=>[name,join(root,file)]));for(const[name,file]of Object.entries(screens))if(!existsSync(file))throw new Error(`macos.nativeScreens: screen "${name}" is ${file}, which does not exist`);const{compileNativeBundle}=await(process.env.STX_NATIVE_SRC?import(pathToFileURL(process.env.STX_NATIVE_SRC).href):import("@stacksjs/stx/native"));const app=config.nativeApp?join(root,config.nativeApp):undefined;const compiled=await compileNativeBundle({screens,initialScreen:config.initialScreen,minify:true,outFile:join(work,"native-screen.js"),root,...app?{app}:{},...config.shareStorage&&Object.keys(config.shareStorage).length?{shareStorage:{...config.shareStorage}}:{}});const problems=(compiled.diagnostics??[]).filter((item)=>item.message!=="dropped-subtree: script");for(const item of problems)await log.warn(`${item.file?`${item.file}: `:""}${item.message}`);if(problems.some((item)=>item.level==="error"))throw new Error("The native screens did not compile");const nativeBundle=compiled.outFile??join(work,"native-screen.js");const entry=craftMacosEntry(root);const webkit=config.webkit===true;if(webkit){const file=entryFile(entry,root);if(!file||!existsSync(file)||!craftSupportsWebkit(readFileSync(file,"utf8")))throw new Error(`macos.webkit needs a Craft whose buildMacOSNative links WebKit, and ${file??entry} does not. Upgrade craft-native, or point CRAFT_MACOS_SRC at a Craft checkout that has it.`)}const key=hostKey(entry,root,webkit);const hostDirectory=storagePath(`framework/desktop/host/${key}`);const host=join(hostDirectory,"craft-native-macos");if(!existsSync(host)){await log.info(`Building the AppKit host${webkit?" with WebKit":""} (first build for this Craft; the toolchain installs through Pantry)`);const builder=await import(entry);mkdirSync(hostDirectory,{recursive:true});await builder.buildMacOSNative({outdir:hostDirectory,nativeBundle,...webkit?{webkit:true}:{}})}return{root,output,nativeBundle,host,hostKey:key}}export function macosAgentEntry(root,config){if(!config.agent)return;if(config.agent.entry){const entry=resolve(root,config.agent.entry);if(!existsSync(entry))throw new Error(`macos.agent.entry does not exist: ${entry}`);return entry}const conventional=join(root,"app/Desktop/Agent.ts");return existsSync(conventional)?conventional:undefined}function agentResources(config,root){const resources=config.agent?.resources;return resources&&Object.keys(resources).length?{resources:Object.fromEntries(Object.entries(resources).map(([name,path])=>[name,resolve(root,path)]))}:{}}export function macosAgentDevManifest(config,prepared){return{appName:config.appName,bundleId:config.bundleId,version:config.version,host:prepared.host,nativeBundle:prepared.nativeBundle,hostArguments:agentHostArguments(config),...config.agent?.port?{port:config.agent.port}:{},...config.agent?.staticDir?{staticDir:resolve(prepared.root,config.agent.staticDir)}:{},...agentResources(config,prepared.root),projectRoot:prepared.root,appRoutes:config.agent?.appRoutes!==false}}export async function macosAgentRouteFiles(root){const manifest=join(root,"app/Routes.ts");const loaded=existsSync(manifest)?(await import(pathToFileURL(manifest).href)).default:undefined;const registry=loaded&&typeof loaded==="object"&&Object.keys(loaded).length?loaded:{api:"api"};const files=[];for(const[key,definition]of Object.entries(registry)){const config=typeof definition==="string"?{path:definition}:definition;const file=[".ts",".js"].map((extension)=>join(root,"routes",`${config.path}${extension}`)).find((candidate)=>existsSync(candidate));if(!file)continue;const prefix=config.prefix!==undefined?config.prefix?config.prefix.startsWith("/")?config.prefix:`/${config.prefix}`:undefined:key==="web"?undefined:`/${key}`;const middleware=config.middleware===undefined?[]:Array.isArray(config.middleware)?config.middleware:[config.middleware];files.push({file,...prefix?{prefix}:{},...middleware.length?{middleware}:{}})}return files}export function macosAgentActionFiles(root,sources){const actions={};for(const source of sources){if(!existsSync(source))continue;for(const match of readFileSync(source,"utf8").matchAll(/['"`](Actions\/[\w/-]+?)(?:\.ts)?['"`]/g)){const name=match[1];if(actions[name])continue;const file=[join(root,"app",`${name}.ts`),join(root,"storage/framework/defaults/app",`${name}.ts`)].find((candidate)=>existsSync(candidate));if(file)actions[name]=file}}return actions}export async function prepareMacosAgent(config,prepared,_distribution){if(!config.agent)throw new Error("config/desktop.ts has no macos.agent");const work=join(prepared.output,".build");const entry=join(work,"agent-entry.ts");const routes=config.agent.appRoutes===false?[]:await macosAgentRouteFiles(prepared.root);const agentEntry=macosAgentEntry(prepared.root,config);const actions=macosAgentActionFiles(prepared.root,[...routes.map((route)=>route.file),...agentEntry?[agentEntry]:[]]);writeFileSync(entry,renderAgentEntry({agentEntry,routes,actions}));const launcher=join(work,`${config.executable}-agent`);const compile=Bun.spawnSync(["bun",...desktopLauncherCompileArgs({entry,outfile:launcher})],{cwd:prepared.root,stdout:"pipe",stderr:"pipe"});if(compile.exitCode!==0)throw new Error(`Compiling the agent launcher failed:
|
|
4
|
+
${compile.stderr.toString().trim()||compile.stdout.toString().trim()}`);return{launcher,manifest:{appName:config.appName,bundleId:config.bundleId,version:config.version,hostArguments:agentHostArguments(config),...config.agent.port?{port:config.agent.port}:{},...config.agent.staticDir?{staticDir:resolve(prepared.root,config.agent.staticDir)}:{},...agentResources(config,prepared.root),appRoutes:false}}}export function macosAgentDevFiles(prepared){const work=join(prepared.output,".build");return{entry:join(work,"agent-entry.ts"),manifest:join(work,AGENT_MANIFEST)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join}from"node:path";export const CRAFT_GENERATED_SPLASH_FLOOR="0.0.443";export async function resolveMobileSplash(input,outputDir,root,craftVersion,log){const{platform,splash}=input;if(splash
|
|
1
|
+
import{join}from"node:path";export const CRAFT_GENERATED_SPLASH_FLOOR="0.0.443";export async function resolveMobileSplash(input,outputDir,root,craftVersion,log){const{platform,splash}=input;if(splash===false)return null;const handMade=platform==="ios"&&Boolean(splash?.image);if(!handMade&&!splash?.logo&&!input.appIcon)return null;if(!handMade&&craftVersion&&!Bun.semver.satisfies(craftVersion,`>=${CRAFT_GENERATED_SPLASH_FLOOR}`)){log.warn(`The generated launch splash needs craft-native >= ${CRAFT_GENERATED_SPLASH_FLOOR} (installed: ${craftVersion}); the launch screen shows only the background colour. Run \`buddy upgrade\` to raise it to the framework's floor, or give ${platform}.splash.image.`);return null}const{generateMobileSplash}=await import("@stacksjs/image");const result=await generateMobileSplash(input,outputDir,root);if(result?.generated)log.info(`Generated the ${platform==="ios"?"iOS launch image":"Android launch splash"} from ${splash&&splash.logo?`${platform}.splash.logo`:`${platform}.appIcon`} in ${join(outputDir,platform)}`);return result}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function isLocalSite(site){const host=site.hostname.replace(/^\[|\]$/g,"");if(["localhost","127.0.0.1","::1","10.0.2.2"].includes(host))return
|
|
1
|
+
export function isLocalSite(site){const host=site.hostname.replace(/^\[|\]$/g,"");if(["localhost","127.0.0.1","::1","10.0.2.2"].includes(host))return true;if(host.endsWith(".localhost")||host.endsWith(".test")||host.endsWith(".local"))return true;const octets=host.split(".").map(Number);if(octets.length!==4||octets.some((octet)=>!Number.isInteger(octet)))return false;const[a,b]=octets;return a===10||a===127||a===192&&b===168||a===172&&b>=16&&b<=31}export function reportMobileBuildTarget(target,log){const site=target.site?new URL(target.site):undefined;if(site){site.username="";site.password="";site.search="";site.hash=""}if(target.renderer==="native"){log.info(`Native screens: ${target.nativeBundle}`);if(site)log.info(`API site: ${site}`)}else if(target.webAssets){log.info(`Bundled web source: ${target.webAssets}`)}else{if(site)log.info(`Web source: ${site}`);if(target.fallbackWebAssets)log.info(`Offline web fallback: ${target.fallbackWebAssets}`)}if(site&&!target.production&&!isLocalSite(site)&&(target.renderer==="native"||!target.webAssets))log.warn(`This development build talks to ${site}, which is not a local server. To build against your dev server, point the app's url in config/mobile.ts at it (for example http://localhost:3000). Build with NODE_ENV=production for a release.`)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,mkdirSync,rmSync,writeFileSync}from"node:fs";import{join,resolve}from"node:path";export function assertCraftSupportsRouteConstraints(constraints,supported,platform="ios"){if(constraints!==
|
|
1
|
+
import{existsSync,mkdirSync,rmSync,writeFileSync}from"node:fs";import{join,resolve}from"node:path";export function assertCraftSupportsRouteConstraints(constraints,supported,platform="ios"){if(constraints!==undefined&&supported!==true)throw new Error(`${platform}.nativeScreenConstraints requires a Craft builder with nativeRouteConstraints support. Install the current published craft-native package.`)}export function nativeScreenName(value){if(!value.endsWith(".stx"))return value;return value.replace(/\.stx$/,"").replace(/^resources\//,"").replace(/^\.?\//,"").replace(/[^\w-]+/g,"-").replace(/^-+|-+$/g,"")}export function nativeScreenRoutes(config){if(!config.nativeScreens)return;return Object.fromEntries(Object.entries(config.nativeScreens).map(([path,value])=>[path,nativeScreenName(value)]))}export function nativeScreenFiles(config,root,section="ios"){const dir=resolve(root,config.nativeScreensDir??"resources/native");const files={};for(const value of Object.values(config.nativeScreens??{})){const name=nativeScreenName(value);if(files[name])continue;const file=value.endsWith(".stx")?resolve(root,value):join(dir,`${value}.stx`);if(!existsSync(file))throw new Error(`${section}.nativeScreens names the screen "${value}", but ${file} does not exist.`);files[name]=file}return files}export function nativeAppFile(config,root,section="ios"){if(!config.nativeApp)return null;const file=resolve(root,config.nativeApp);if(!existsSync(file))throw new Error(`${section}.nativeApp names ${config.nativeApp}, but ${file} does not exist.`);return file}export async function compileNativeScreens(config,root,output,compile,section="ios",options={}){const screens=nativeScreenFiles(config,root,section);const names=Object.keys(screens);const app=nativeAppFile(config,root,section);if(!names.length){if(app)throw new Error(`${section}.nativeApp runs beside native screens: list them in ${section}.nativeScreens`);return null}const compileBundle=compile??(await import("@stacksjs/stx/native")).compileNativeBundle;const share=config.shareStorage&&Object.keys(config.shareStorage).length?{shareStorage:{...config.shareStorage}}:{};mkdirSync(output,{recursive:true});const outFile=join(output,"native-screens.js");const routesDir=join(output,"native-screens");rmSync(options.routes?outFile:routesDir,{recursive:true,force:true});if(options.routes){rmSync(routesDir,{recursive:true,force:true});const sharedRuntime=options.runtime===true;const messages=sharedRuntime&&options.messages&&config.nativeMessages?{dir:config.nativeMessages.dir,languages:[...config.nativeMessages.languages]}:undefined;const result=await compileBundle({screens,initialScreen:names[0],minify:true,routesDir,root,...sharedRuntime?{sharedRuntime}:{},...app?{app}:{},...messages?{messages}:{},...share});if(result.routes&&Object.keys(result.routes).length)return{outFile:routesDir,diagnostics:result.diagnostics??[]};if(!result.code)throw new Error("stx compiled no native bundle: it wrote no route files and returned no code");writeFileSync(outFile,result.code);return{outFile,diagnostics:result.diagnostics??[]}}const result=await compileBundle({screens,initialScreen:names[0],minify:true,outFile,root,...app?{app}:{},...share});return{outFile:result.outFile||outFile,diagnostics:result.diagnostics??[]}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const SENSOR_CAPABILITY_KEYS={ios:{barometer:"enableBarometer",pedometer:"enablePedometer",healthKitBackground:"enableHealthKitBackground"},android:{motionSensors:"enableMotionSensors",barometer:"enableBarometer",pedometer:"enablePedometer"}};export function nativeSensorCapabilityKeys(platform,supported){return Object.fromEntries(Object.entries(SENSOR_CAPABILITY_KEYS[platform]).filter(([name])=>supported?.includes(name)))}export function assertCraftSupportsNativeSensors(platform,capabilities,supported){const
|
|
1
|
+
const SENSOR_CAPABILITY_KEYS={ios:{barometer:"enableBarometer",pedometer:"enablePedometer",healthKitBackground:"enableHealthKitBackground"},android:{motionSensors:"enableMotionSensors",barometer:"enableBarometer",pedometer:"enablePedometer"}};export function nativeSensorCapabilityKeys(platform,supported){return Object.fromEntries(Object.entries(SENSOR_CAPABILITY_KEYS[platform]).filter(([name])=>supported?.includes(name)))}export function assertCraftSupportsNativeSensors(platform,capabilities,supported){const checked=Object.keys(SENSOR_CAPABILITY_KEYS[platform]);const missing=checked.filter((name)=>capabilities?.[name]&&!supported?.includes(name));if(missing.length)throw new Error(`The selected Craft ${platform} builder does not support ${missing.join(", ")}. Install a published craft-native builder supporting these capabilities; these flags cannot be silently ignored.`)}
|
package/dist/build/notarize.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{mkdtempSync,rmSync,symlinkSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{basename,dirname,join}from"node:path";import process from"node:process";import{log,runCommand}from"@stacksjs/cli";import{notarizationOutcome,notarytoolAuthArgs}from"@stacksjs/desktop-build";import{runBuildStep}from"./run-build-step";export function notaryArguments(credentials){if(!("keyPem"in credentials))return notarytoolAuthArgs(credentials);const directory=mkdtempSync(join(tmpdir(),"stacks-notary-key-"))
|
|
2
|
-
`,{mode:384});process.on("exit",()=>rmSync(directory,{recursive
|
|
1
|
+
import{mkdtempSync,rmSync,symlinkSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{basename,dirname,join}from"node:path";import process from"node:process";import{log,runCommand}from"@stacksjs/cli";import{notarizationOutcome,notarytoolAuthArgs}from"@stacksjs/desktop-build";import{runBuildStep}from"./run-build-step";export function notaryArguments(credentials){if(!("keyPem"in credentials))return notarytoolAuthArgs(credentials);const directory=mkdtempSync(join(tmpdir(),"stacks-notary-key-"));const keyPath=join(directory,`AuthKey_${credentials.keyId}.p8`);writeFileSync(keyPath,`${credentials.keyPem}
|
|
2
|
+
`,{mode:384});process.on("exit",()=>rmSync(directory,{recursive:true,force:true}));return notarytoolAuthArgs({keyId:credentials.keyId,issuerId:credentials.issuerId,keyPath})}export async function notarizeAndStaple(target,what,auth,scratch){const upload=target.endsWith(".app")?join(scratch,`${basename(target)}.zip`):target;if(upload!==target)await runBuildStep(["ditto","-c","-k","--keepParent",target,upload],{cwd:scratch,describe:`Zipping ${basename(target)} for notarization`});log.info(`Notarizing ${what} (Apple usually answers within a few minutes)...`);const submitted=Bun.spawnSync(["xcrun","notarytool","submit",upload,...auth,"--wait"],{stderr:"pipe"});const report=`${submitted.stdout.toString()}${submitted.stderr.toString()}`;const outcome=notarizationOutcome(report,submitted.exitCode);if(!outcome.accepted){console.error(report.trim());throw new Error(`Notarization of ${what} ${outcome.status??"failed"}${outcome.id?` - see \`xcrun notarytool log ${outcome.id} ${auth.join(" ")}\``:""}`)}await runBuildStep(["xcrun","stapler","staple",target],{cwd:dirname(target),describe:`Stapling the notarization ticket to ${what}`})}export async function imageDmg(options){symlinkSync("/Applications",join(options.staging,"Applications"));const created=await runCommand(["hdiutil","create","-volname",options.volumeName,"-srcfolder",options.staging,"-ov","-format","UDZO",options.dmgPath],{cwd:options.staging});if(created.isErr)throw new Error(`hdiutil failed to create ${options.dmgPath}`);if(options.signingIdentity){await runBuildStep(["codesign","--force","--timestamp","--sign",options.signingIdentity,options.dmgPath],{cwd:dirname(options.dmgPath),describe:"Signing the DMG"})}}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import process from"node:process";import{runCommand}from"@stacksjs/cli";export async function runBuildStep(command,options){const{describe,...cliOptions}=options;
|
|
1
|
+
import process from"node:process";import{runCommand}from"@stacksjs/cli";export async function runBuildStep(command,options){const{describe,...cliOptions}=options;const result=await runCommand(command,cliOptions);if(!result.isErr)return;const printable=Array.isArray(command)?command.join(" "):command;console.error(`
|
|
2
2
|
${describe} failed: \`${printable}\` exited non-zero.`);console.error(`The error it printed above is the cause - this step only relays its exit status.
|
|
3
3
|
`);process.exit(1)}
|
package/dist/build/stacks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{projectPath}from"@stacksjs/path";import{runBuildStep}from"./run-build-step";await runBuildStep("bun storage/framework/core/actions/src/build/cli.ts",{verbose
|
|
1
|
+
import{projectPath}from"@stacksjs/path";import{runBuildStep}from"./run-build-step";await runBuildStep("bun storage/framework/core/actions/src/build/cli.ts",{verbose:true,cwd:projectPath(),describe:"The CLI build"});await runBuildStep("bun storage/framework/core/actions/src/build/core.ts",{verbose:true,cwd:projectPath(),describe:"The core packages build"});
|
package/dist/build/views.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{projectPath}from"@stacksjs/path";import{runBuildStep}from"./run-build-step";const projectBuild=projectPath("build.ts");if(await Bun.file(projectBuild).exists())await runBuildStep("bun build.ts",{cwd:projectPath(),describe:"The frontend build"})
|
|
1
|
+
import{projectPath}from"@stacksjs/path";import{runBuildStep}from"./run-build-step";const projectBuild=projectPath("build.ts");if(await Bun.file(projectBuild).exists()){await runBuildStep("bun build.ts",{cwd:projectPath(),describe:"The frontend build"})}else{await runBuildStep("bunx --bun @stacksjs/stx build --pages resources/views --out dist",{cwd:projectPath(),describe:"The frontend build"})}
|
package/dist/build.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{hasFunctions}from"@stacksjs/storage";import{runNpmScript}from"@stacksjs/utils";import{buildStxComponentLibrary}from"./build/component-library";import{generateTypes}from"./generate";import{generateProjectImages}from"./generate/images";export async function invoke(options){if(options.components)await componentLibraries(options);else if(options.webComponents||options.elements)await webComponentLibrary();else if(options.functions)await functionsLibrary(options);else if(options.docs)await docs(options);else if(options.stacks)await stacks(options);await generateTypes();try{await generateProjectImages({only:["social","app-icons"]})}catch(error){log.warn(`[build] image generation skipped: ${error.message}`)}}export async function build(options){return await invoke(options)}export async function componentLibraries(options){await runNpmScript(NpmScript.GenerateEntries,options);await stxComponentLibrary()}export async function stxComponentLibrary(){await buildStxComponentLibrary()}export async function webComponentLibrary(){await buildStxComponentLibrary()}export async function docs(options){log.info("Building the documentation site...");await runNpmScript(NpmScript.BuildDocs,options);log.success("Docs built successfully")}export async function stacks(options){log.info("Building the Stacks Framework...");await runNpmScript(NpmScript.BuildStacks,options);log.success("Stacks built successfully")}export async function functionsLibrary(options){if(hasFunctions()){log.info("Building your functions library for production usages...");log.info("Production usages include: manual npm distribution and/or CDN distribution");await runNpmScript(NpmScript.BuildFunctions,options);log.success("Functions library built successfully")}else
|
|
1
|
+
import{NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{hasFunctions}from"@stacksjs/storage";import{runNpmScript}from"@stacksjs/utils";import{buildStxComponentLibrary}from"./build/component-library";import{generateTypes}from"./generate";import{generateProjectImages}from"./generate/images";export async function invoke(options){if(options.components)await componentLibraries(options);else if(options.webComponents||options.elements)await webComponentLibrary();else if(options.functions)await functionsLibrary(options);else if(options.docs)await docs(options);else if(options.stacks)await stacks(options);await generateTypes();try{await generateProjectImages({only:["social","app-icons"]})}catch(error){log.warn(`[build] image generation skipped: ${error.message}`)}}export async function build(options){return await invoke(options)}export async function componentLibraries(options){await runNpmScript(NpmScript.GenerateEntries,options);await stxComponentLibrary()}export async function stxComponentLibrary(){await buildStxComponentLibrary()}export async function webComponentLibrary(){await buildStxComponentLibrary()}export async function docs(options){log.info("Building the documentation site...");await runNpmScript(NpmScript.BuildDocs,options);log.success("Docs built successfully")}export async function stacks(options){log.info("Building the Stacks Framework...");await runNpmScript(NpmScript.BuildStacks,options);log.success("Stacks built successfully")}export async function functionsLibrary(options){if(hasFunctions()){log.info("Building your functions library for production usages...");log.info("Production usages include: manual npm distribution and/or CDN distribution");await runNpmScript(NpmScript.BuildFunctions,options);log.success("Functions library built successfully")}else{log.info("No functions found")}}
|
package/dist/bump.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import{execSync,log,parseOptions}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";import{incrementVersion,isReleaseType,isValidVersion,versionBump}from"@stacksjs/bumpx";import{isCalendarBump,nextCalendarVersion}from"./calendar-version";import{describeGitHubRelease,publishGitHubRelease}from"./github-release";import{pantryLockViolations}from"./pantry-lock";import{resolvePantryToolchain}from"./pantry-toolchain";import{releasePushTarget}from"./release-push-target";import{generateChangelog,loadLogsmithConfig}from"@stacksjs/logsmith";import{existsSync,readdirSync,readFileSync,unlinkSync,writeFileSync}from"node:fs";import{join,relative}from"node:path";const options=parseOptions()
|
|
1
|
+
import{execSync,log,parseOptions}from"@stacksjs/cli";import{path as p}from"@stacksjs/path";import{incrementVersion,isReleaseType,isValidVersion,versionBump}from"@stacksjs/bumpx";import{isCalendarBump,nextCalendarVersion}from"./calendar-version";import{describeGitHubRelease,publishGitHubRelease}from"./github-release";import{pantryLockViolations}from"./pantry-lock";import{resolvePantryToolchain}from"./pantry-toolchain";import{releasePushTarget}from"./release-push-target";import{generateChangelog,loadLogsmithConfig}from"@stacksjs/logsmith";import{existsSync,readdirSync,readFileSync,unlinkSync,writeFileSync}from"node:fs";import{join,relative}from"node:path";const options=parseOptions();const rawBump=options?.bump?.toString();const bumpArg=rawBump?isReleaseType(rawBump)||isCalendarBump(rawBump)||isValidVersion(rawBump)?rawBump:null:null;if(rawBump&&!bumpArg)throw new Error(`Invalid --bump "${rawBump}"; expected a Bumpx release type, calendar, or semantic version`);const isDryRun=options?.dryRun===true;const isVerbose=options?.verbose===true;async function readPackage(file){if(!existsSync(file))return;return await Bun.file(file).json()}const rootManifest=p.projectPath("package.json");const rootPkg=await readPackage(rootManifest);const isFrameworkRelease=rootPkg?.name==="stacks"&&existsSync(p.frameworkPath("core/package.json"));const bumpCwd=isFrameworkRelease?p.frameworkPath("core"):p.projectPath();const primaryManifest=isFrameworkRelease?p.frameworkPath("core/package.json"):rootManifest;async function resolveBumpArg(bump){if(!bump)return bump;if(isCalendarBump(bump)){const pkg=await readPackage(primaryManifest);return nextCalendarVersion(pkg?.version)}const pkg=await readPackage(primaryManifest);if(!pkg?.version)throw new Error(`${primaryManifest} declares no version`);return incrementVersion(pkg.version,bump,options?.preid)}const resolvedBumpArg=await resolveBumpArg(bumpArg);async function git(args,cwd=p.projectPath(),options={}){return await execSync(["git",...args],{cwd,stdin:"inherit",stderr:"pipe",throwOnError:options.throwOnError??true})}const pushTarget=isDryRun?undefined:releasePushTarget(p.projectPath(),isFrameworkRelease?"main":undefined);async function isGitIgnored(file){const output=await git(["check-ignore","--",file],p.projectPath(),{throwOnError:false});return output.trim().length>0}async function readVersion(file){const pkg=await readPackage(file);if(!pkg?.version||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(pkg.version))throw new Error(`Invalid version in ${file}: ${pkg?.version??"<missing>"}`);return pkg.version}function lockfileVersion(contents){const match=contents.match(/"lockfileVersion"\s*:\s*(\d+)/);return match?Number(match[1]):null}async function packageFilesFor(pattern,cwd){const glob=new Bun.Glob(pattern);const files=[];for await(const file of glob.scan({cwd,absolute:true,onlyFiles:true})){if(file.includes("/node_modules/")||file.includes("/dist/")||file.includes("/pantry/"))continue;files.push(`./${relative(bumpCwd,file)}`)}return files}async function existingPackageFiles(files){const existing=[];for(const file of files){const absolutePath=join(bumpCwd,file);if(await Bun.file(absolutePath).exists())existing.push(file)}return existing}async function frameworkBumpFiles(){return Array.from(new Set([...await packageFilesFor("package.json",bumpCwd),...await packageFilesFor("*/package.json",bumpCwd),...await packageFilesFor("*/*/package.json",bumpCwd),...await existingPackageFiles(["../package.json","../defaults/ide/vscode/package.json","../api/package.json","../cloud/package.json","../docs/package.json","../orm/package.json","../server/package.json"]),...await packageFilesFor("../libs/**/package.json",bumpCwd)]))}const bumpFiles=isFrameworkRelease?await frameworkBumpFiles():["./package.json"];const pantryToolchain=!isDryRun&&existsSync(p.projectPath("pantry.lock"))?resolvePantryToolchain({cwd:p.projectPath()}):undefined;if(pantryToolchain&&!pantryToolchain.ok)throw new Error(pantryToolchain.message);log.debug(`Release mode: ${isFrameworkRelease?"framework monorepo":"consumer app"} (${rootPkg?.name??"unknown"})`);log.debug(`Bumping ${bumpFiles.length} package manifest(s) in ${bumpCwd}`);await versionBump({release:resolvedBumpArg??undefined,preid:options?.preid,files:bumpFiles,cwd:bumpCwd,recursive:false,commit:false,tag:false,push:false,changelog:false,noGitCheck:true,dryRun:isDryRun,yes:Boolean(resolvedBumpArg),verbose:isVerbose});const nextVersion=isDryRun&&resolvedBumpArg&&isValidVersion(resolvedBumpArg)?resolvedBumpArg:await readVersion(primaryManifest);const latestTag=(await git(["describe","--abbrev=0","--tags"],p.projectPath(),{throwOnError:false}).catch(()=>"")).trim();async function writeChangelog(){const config=await loadLogsmithConfig({dir:p.projectPath(),from:latestTag||undefined,to:"HEAD",output:isDryRun?false:"CHANGELOG.md",theme:"github",verbose:isVerbose});const result=await generateChangelog(config);if(isDryRun){log.info(result.content);return}const changelogPath=p.projectPath("CHANGELOG.md");if(!existsSync(changelogPath))return;let content=readFileSync(changelogPath,"utf-8");const versionSeen=new RegExp(`\\bv?${nextVersion.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`);if(/\/compare\/[^)\s]+\.\.\.HEAD\)/.test(content)){content=content.replace(/(\/compare\/[^)\s]+\.\.\.)HEAD(\))/,`$1v${nextVersion}$2`)}else if(!versionSeen.test(content.split(`
|
|
2
2
|
`).slice(0,4).join(`
|
|
3
|
-
`)))content=content.replace(/^(#\s.*\n+)?/,(match)=>`${match??""}## v${nextVersion}
|
|
3
|
+
`))){content=content.replace(/^(#\s.*\n+)?/,(match)=>`${match??""}## v${nextVersion}
|
|
4
4
|
|
|
5
|
-
`)
|
|
5
|
+
`)}writeFileSync(changelogPath,content)}await writeChangelog();if(!isDryRun&&isFrameworkRelease)pinLockstepDeps(nextVersion);async function refreshPantryLock(){const lockPath=p.projectPath("pantry.lock");if(!existsSync(lockPath))return;const previousLock=readFileSync(lockPath);try{await execSync([pantryToolchain?.ok?pantryToolchain.bin:"pantry","install","--ignore-scripts","--quiet"],{cwd:p.projectPath(),stdin:"inherit",throwOnError:true,env:{PANTRY_ENV_DEPS:"0"}});if(!existsSync(lockPath))throw new Error("Pantry completed without writing pantry.lock")}catch(error){writeFileSync(lockPath,previousLock);throw new Error("Release aborted: Pantry could not refresh pantry.lock without lifecycle scripts. The previous lockfile was restored.",{cause:error})}const declarations=existsSync(bunLockPath)?Bun.JSONC.parse(readFileSync(bunLockPath,"utf8")).workspaces:undefined;const violations=pantryLockViolations(readFileSync(lockPath,"utf8"),previousLock.toString("utf8"),declarations);if(violations.length>0){writeFileSync(lockPath,previousLock);throw new Error("Release aborted: refreshing pantry.lock produced a lockfile that does not describe this workspace, "+`so the previous one has been restored.
|
|
6
6
|
`+violations.map((violation)=>` - ${violation}`).join(`
|
|
7
|
-
`)+"\n\nThis is platform divergence in `pantry install`, not something the version bump did. Regenerate pantry.lock on the platform CI validates against, commit that on its own, then re-run the release.")}}const bunLockPath=p.projectPath("bun.lock")
|
|
7
|
+
`)+"\n\nThis is platform divergence in `pantry install`, not something the version bump did. "+"Regenerate pantry.lock on the platform CI validates against, commit that on its own, then re-run the release.")}}const bunLockPath=p.projectPath("bun.lock");const pantryLockPath=p.projectPath("pantry.lock");const committedBunLock=existsSync(bunLockPath)?readFileSync(bunLockPath):null;const committedPantryLock=existsSync(pantryLockPath)?readFileSync(pantryLockPath):null;function restoreCommittedLockfiles(){if(committedBunLock)writeFileSync(bunLockPath,committedBunLock);if(committedPantryLock)writeFileSync(pantryLockPath,committedPantryLock)}if(!isDryRun&&committedBunLock){const lockPath=bunLockPath;unlinkSync(lockPath);try{await execSync(["bun","install","--lockfile-only"],{cwd:p.projectPath(),stdin:"inherit"})}catch(error){restoreCommittedLockfiles();throw error}if(!existsSync(lockPath)){restoreCommittedLockfiles();throw new Error("Release aborted: `bun install --lockfile-only` wrote no lockfile, so the previous one has been restored. "+"This usually means a dependency range this bump just raised names a version that is not published yet - "+"release that package first, then re-run.")}}if(!isDryRun){try{await refreshPantryLock()}catch(error){restoreCommittedLockfiles();throw error}}if(!isDryRun&&committedBunLock){const lockPath=bunLockPath;const previousLock=committedBunLock;const expectedLockfileVersion=lockfileVersion(previousLock.toString("utf8"));const regeneratedLock=readFileSync(lockPath,"utf8");const producedVersion=lockfileVersion(regeneratedLock);if(expectedLockfileVersion==null||producedVersion!==expectedLockfileVersion){restoreCommittedLockfiles();const remedy=producedVersion!=null&&expectedLockfileVersion!=null&&producedVersion>expectedLockfileVersion?"the committed lockfile predates the Bun this repository declares. Regenerate it once with that toolchain "+"(`bun install --lockfile-only`) and commit the result as its own change, then re-run the release.":"this machine's Bun is older than the one that wrote the committed lockfile. Re-run the release with the "+"repository's declared Bun toolchain through `pantry install`.";throw new Error(`Release aborted: regenerating bun.lock produced lockfileVersion ${producedVersion??"unknown"}, `+`but the committed one is v${expectedLockfileVersion??"unknown"} — ${remedy}`)}}function lockstepPackages(version){const names=new Set;for(const entry of readdirSync(p.frameworkPath("core"),{withFileTypes:true})){if(!entry.isDirectory())continue;const manifest=p.frameworkPath(`core/${entry.name}/package.json`);if(!existsSync(manifest))continue;const pkg=JSON.parse(readFileSync(manifest,"utf-8"));if(pkg.name?.startsWith("@stacksjs/")&&pkg.version===version)names.add(pkg.name)}return names}function pinLockstepDeps(version){const lockstep=lockstepPackages(version);const next=version;const manifests=[p.frameworkPath("core/package.json"),...readdirSync(p.frameworkPath("core"),{withFileTypes:true}).filter((entry)=>entry.isDirectory()).map((entry)=>p.frameworkPath(`core/${entry.name}/package.json`)).filter((path)=>existsSync(path))];let pinned=0;for(const manifestPath of manifests){const manifest=JSON.parse(readFileSync(manifestPath,"utf-8"));let changed=false;for(const field of["dependencies","devDependencies"]){const deps=manifest[field];if(!deps)continue;for(const name of Object.keys(deps)){if(!lockstep.has(name)||deps[name].startsWith("workspace:")||deps[name]===next)continue;deps[name]=next;changed=true;pinned++}}if(changed)writeFileSync(manifestPath,`${JSON.stringify(manifest,null,2)}
|
|
8
8
|
`)}if(pinned>0)log.debug(`Pinned ${pinned} lockstep core dep(s) to ${version}`)}async function stageReleaseArtifacts(){const pathspecs=isFrameworkRelease?[":(glob)storage/framework/**/package.json","package.json"]:["package.json"];for(const file of["CHANGELOG.md","bun.lock","pantry.lock"]){if(!existsSync(p.projectPath(file)))continue;if(await isGitIgnored(file))continue;pathspecs.push(file)}await git(["add","--",...pathspecs]);const leftover=(await git(["status","--porcelain"])).split(`
|
|
9
|
-
`).map((line)=>line.trimEnd()).filter((line)=>line&&!line.startsWith("A ")&&!line.startsWith("M "));if(leftover.length)log.warn(`Kept ${leftover.length} change(s) out of the release commit:
|
|
9
|
+
`).map((line)=>line.trimEnd()).filter((line)=>line&&!line.startsWith("A ")&&!line.startsWith("M "));if(leftover.length){log.warn(`Kept ${leftover.length} change(s) out of the release commit:
|
|
10
10
|
${leftover.slice(0,20).join(`
|
|
11
|
-
`)}
|
|
12
|
-
|
|
11
|
+
`)}`+`${leftover.length>20?`
|
|
12
|
+
… and ${leftover.length-20} more`:""}`)}}if(!isDryRun){await stageReleaseArtifacts();await git(["commit","-m",`chore: release v${nextVersion}`]);await git(["tag",`v${nextVersion}`]);if(!pushTarget)throw new Error("No release push destination was resolved");await git(["push","--atomic","--",pushTarget.remote,`HEAD:${pushTarget.ref}`,`refs/tags/v${nextVersion}`])}if(!isFrameworkRelease&&options?.skipGithubRelease!==true){const tag=`v${nextVersion}`;const result=await publishGitHubRelease({cwd:p.projectPath(),tag,ref:isDryRun?"HEAD":undefined,dryRun:isDryRun});if(isDryRun&&result.draft)log.info(`Would create the GitHub release ${tag}:
|
|
13
13
|
|
|
14
14
|
${result.draft.body}`);else if(result.status==="failed")log.warn(describeGitHubRelease(tag,result));else log.info(describeGitHubRelease(tag,result))}
|
package/dist/calendar-version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function parseCalendarVersion(version){const match=version.match(/^(\d{4})\.(0|[1-9]\d?)\.(0|[1-9]\d*)$/);if(!match)return null;const month=Number(match[2]);if(month<1||month>12)return null;return{year:Number(match[1]),month,sequence:Number(match[3])}}export function nextCalendarVersion(current,now=new Date){const year=now.getUTCFullYear()
|
|
1
|
+
export function parseCalendarVersion(version){const match=version.match(/^(\d{4})\.(0|[1-9]\d?)\.(0|[1-9]\d*)$/);if(!match)return null;const month=Number(match[2]);if(month<1||month>12)return null;return{year:Number(match[1]),month,sequence:Number(match[3])}}export function nextCalendarVersion(current,now=new Date){const year=now.getUTCFullYear();const month=now.getUTCMonth()+1;const parsed=current?parseCalendarVersion(current):null;if(!parsed)return`${year}.${month}.0`;if(parsed.year>year||parsed.year===year&&parsed.month>month)return`${parsed.year}.${parsed.month}.${parsed.sequence+1}`;if(parsed.year===year&&parsed.month===month)return`${year}.${month}.${parsed.sequence+1}`;return`${year}.${month}.0`}export const CALENDAR_BUMPS=new Set(["calendar","calver","date"]);export function isCalendarBump(bump){return typeof bump==="string"&&CALENDAR_BUMPS.has(bump.toLowerCase())}
|
package/dist/changelog.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execSync,log,parseOptions}from"@stacksjs/cli";import{projectPath}from"@stacksjs/path";import{generateChangelog,loadLogsmithConfig}from"@stacksjs/logsmith";const sanitizeRevision=(revision)=>{const value=revision.trim();if(!/^[A-Za-z0-9._/-]+$/.test(value))throw Error(`Invalid git revision: ${value}`);return value};log.debug("Generating changelog");const options=parseOptions()
|
|
1
|
+
import{execSync,log,parseOptions}from"@stacksjs/cli";import{projectPath}from"@stacksjs/path";import{generateChangelog,loadLogsmithConfig}from"@stacksjs/logsmith";const sanitizeRevision=(revision)=>{const value=revision.trim();if(!/^[A-Za-z0-9._/-]+$/.test(value))throw new Error(`Invalid git revision: ${value}`);return value};log.debug("Generating changelog");const options=parseOptions();const fromRevision=sanitizeRevision(options?.from?.toString()??await execSync("git describe --abbrev=0 --tags HEAD^").catch(()=>""));log.debug("FromRevision",fromRevision);const toRevision=sanitizeRevision(options?.to?.toString()??"HEAD");log.debug("ToRevision",toRevision);log.debug("Changelog Options",options);if(options?.version??options?.r)log.debug("Ignoring --version: logsmith headers the section from the from…to range");const isDryRun=options?.dryRun===true;const config=await loadLogsmithConfig({dir:projectPath(),from:fromRevision||undefined,to:toRevision,output:isDryRun?false:"CHANGELOG.md",theme:"github",verbose:options?.verbose===true});const result=await generateChangelog(config);if(isDryRun&&!options?.quiet)log.info(result.content);
|
package/dist/check/ports.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$}from"bun";import process from"node:process";import{log}from"@stacksjs/logging";import{findStacksProjects}from"@stacksjs/utils";const projects=await findStacksProjects(
|
|
1
|
+
import{$}from"bun";import process from"node:process";import{log}from"@stacksjs/logging";import{findStacksProjects}from"@stacksjs/utils";const projects=await findStacksProjects(undefined,{quiet:true});log.debug("Running `buddy ports`");log.debug(`Found ${projects.length} projects`);log.debug("Projects:",projects);for(const project of projects){log.debug("Running `buddy ports`");log.debug("Project:",project);$.cwd(project);const ports=await $`./buddy ports --project ${project} --quiet`.text();log.debug("ports",ports)}process.exit(0);
|
package/dist/commit.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{runNpmScript}from"@stacksjs/utils";export async function invoke(options){log.info("Committing...");
|
|
1
|
+
import process from"node:process";import{NpmScript}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{runNpmScript}from"@stacksjs/utils";export async function invoke(options){log.info("Committing...");const result=await runNpmScript(NpmScript.Commit,{cwd:projectPath(),...options});if(result.isErr){await log.error("Nothing was committed.");await log.flush();process.exit(ExitCode.FatalError)}log.success("Committed")}export async function commit(options){return await invoke(options)}
|
package/dist/database/seed.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{log}from"@stacksjs/cli";import{seed}from"@stacksjs/database";const argv=process.argv.slice(2)
|
|
1
|
+
import process from"node:process";import{log}from"@stacksjs/cli";import{seed}from"@stacksjs/database";const argv=process.argv.slice(2);const allowProtected=argv.includes("--allow-protected")||argv.includes("--allowProtected");const attachAccounts=argv.includes("--attach-accounts")||argv.includes("--attachAccounts");const fresh=argv.includes("--fresh");const startTime=Date.now();try{const result=await seed({verbose:true,fresh,allowProtected,attachAccounts});const duration=Date.now()-startTime;if(result.failed>0){log.warn("");log.warn(`Seeding completed with ${result.failed} failure(s):`);for(const r of result.results){if(!r.success){log.error(` - ${r.model}: ${r.error}`)}}log.info("");log.info("Note: Failed models may have schema mismatches or invalid factory functions.");log.info("Tip: Run `./buddy migrate:fresh` to ensure schema is up to date.")}log.info("");log.success(`Seeding completed in ${duration}ms`);log.info(` Total models: ${result.total}`);log.info(` Successful: ${result.successful}`);log.info(` Failed: ${result.failed}`);await log.flush();process.exit(0)}catch(err){await log.error("Seeding failed catastrophically:",err);process.exit(1)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";import{S3Client,SESClient}from"@stacksjs/ts-cloud";import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";const ses=new SESClient
|
|
1
|
+
import process from"node:process";import{S3Client,SESClient}from"@stacksjs/ts-cloud";import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";const ses=new SESClient;const s3=new S3Client;let bucketName;const data=await s3.listBuckets();if(data.Buckets)bucketName=data.Buckets.find((bucket)=>bucket.Name?.includes("-email-"))?.Name;console.log("Bucket Name:",bucketName);if(!bucketName){console.log("Stacks Email Bucket not found");process.exit(ExitCode.FatalError)}try{await ses.createReceiptRule({RuleSetName:"your-rule-set-name",Rule:{Name:"Inbound",Enabled:true,ScanEnabled:true,TlsPolicy:"Require",Actions:[{S3Action:{BucketName:bucketName,ObjectKeyPrefix:"tmp/email_in"}}]}});log.info("Success: Receipt rule created")}catch(error){console.error(error)}
|
package/dist/deploy/hooks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{join}from"node:path";import{pathToFileURL}from"node:url";export async function runBeforeDeployHook(cwd,context){const file=[".ts",".js",".mts",".mjs",".cts",".cjs"].map((extension)=>join(cwd,`cloud/deploy-script${extension}`)).find(existsSync);if(!file)return
|
|
1
|
+
import{existsSync}from"node:fs";import{join}from"node:path";import{pathToFileURL}from"node:url";export async function runBeforeDeployHook(cwd,context){const file=[".ts",".js",".mts",".mjs",".cts",".cjs"].map((extension)=>join(cwd,`cloud/deploy-script${extension}`)).find(existsSync);if(!file)return false;const module=await import(pathToFileURL(file).href);const owner=Object.hasOwn(module,"beforeDeploy")?module:module.default;if(!owner||!Object.hasOwn(owner,"beforeDeploy"))return false;const hook=owner.beforeDeploy;if(typeof hook!=="function")throw new Error("cloud/deploy-script beforeDeploy must be a function");await hook(context);return true}
|