@stacksjs/buddy 0.75.41 → 0.75.42

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.
@@ -3,46 +3,97 @@ import type { CLI } from '@stacksjs/types';
3
3
  /**
4
4
  * Validate the flags, or throw with the message the operator should see.
5
5
  *
6
- * `env` is read for `SHOPWARE_ACCESS_KEY` only, and only for `--from shopware`.
6
+ * `env` is read for `SHOPWARE_ACCESS_KEY` only, and only for a Shopware
7
+ * catalog import. Admin API credentials are read by the importer itself
8
+ * (`readAccountCredentials`), before its first request.
7
9
  */
8
10
  export declare function parseImportFlags(flags: CommerceImportFlags, env?: Record<string, string | undefined>): CommerceImportSettings;
9
11
  /** One line per product, as the import runs. */
10
12
  export declare function formatImportedProduct(product: ImportedProduct, format: (minor: number, currency: string | null) => string, dryRun?: boolean): string;
13
+ /** One line per customer, as the import runs. */
14
+ export declare function formatImportedCustomer(customer: ImportedCustomer, dryRun?: boolean): string;
15
+ /** One line per order, as the import runs. */
16
+ export declare function formatImportedOrder(order: ImportedOrder, format: (minor: number, currency: string | null) => string, dryRun?: boolean): string;
11
17
  /** The closing summary, one fact per line. */
12
18
  export declare function formatImportSummary(result: ImportResult): string[];
19
+ /** The closing summary of a customer import. */
20
+ export declare function formatCustomerSummary(result: CustomerImportResult): string[];
21
+ /** The closing summary of an order import. */
22
+ export declare function formatOrderSummary(result: OrderImportResult): string[];
13
23
  /** Why the operator should look twice at the currency, or null if it is fine. */
14
24
  export declare function currencyMismatch(result: ImportResult, configured: string | undefined): string | null;
25
+ /**
26
+ * Why a writing import cannot start, or null. With the commerce bundle
27
+ * disabled (`enabled: false` in config/commerce.ts) its tables are never
28
+ * migrated, and the import used to get as far as the first insert and stop on
29
+ * "no such table: products". A dry run writes nothing, so it may still look.
30
+ */
31
+ export declare function commerceDisabledReason(enabled: boolean, dryRun: boolean): string | null;
15
32
  export declare function commerceImport(buddy: CLI): void;
16
33
  export declare const SUPPORTED_SOURCES: readonly ['shopify', 'woocommerce', 'shopware'];
34
+ /**
35
+ * The env vars each platform's customer and order import reads, for --help and errors.
36
+ * @defaultValue
37
+ * ```ts
38
+ * {
39
+ * shopify: 'SHOPIFY_ADMIN_TOKEN',
40
+ * woocommerce: 'WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET',
41
+ * shopware: 'SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET'
42
+ * }
43
+ * ```
44
+ */
45
+ export declare const CREDENTIAL_ENV: Record<typeof SUPPORTED_SOURCES[number], string>;
17
46
  /** Where to find a Shopware sales channel access key, for the error that asks for one. */
18
47
  export declare const SHOPWARE_ACCESS_KEY_HELP: 'It is public by design, not a secret. Find it in the Shopware Administration under Sales Channels: open the storefront or headless sales channel and copy the key from its "API access" card.';
19
- export declare const OUT_OF_SCOPE_NOTE: 'Catalog only. Customers and orders are not imported: they need the Shopify Admin API, WooCommerce REST API keys or a Shopware Admin API integration.';
48
+ export declare const OUT_OF_SCOPE_NOTE: 'Customers and orders were not imported. Add --customers and/or --orders, with the admin API credentials in env: SHOPIFY_ADMIN_TOKEN, WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET, or SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET.';
20
49
  export declare interface CommerceImportFlags {
21
50
  from?: string
22
51
  limit?: string | number
23
52
  currency?: string
24
53
  accessKey?: string
54
+ adminUrl?: string
55
+ catalog?: boolean
56
+ customers?: boolean
57
+ orders?: boolean
25
58
  dryRun?: boolean
26
59
  }
60
+ export declare interface ImportSelection {
61
+ catalog: boolean
62
+ customers: boolean
63
+ orders: boolean
64
+ }
27
65
  export declare interface CommerceImportSettings {
28
66
  source: typeof SUPPORTED_SOURCES[number]
29
67
  limit?: number
30
68
  currency?: string
31
69
  accessKey?: string
70
+ adminUrl?: string
71
+ include: ImportSelection
32
72
  dryRun: boolean
33
73
  }
34
74
  /**
35
75
  * `buddy commerce:import <store-url> --from shopify|woocommerce|shopware`
36
76
  *
37
- * Moves a store's CATALOG into the built-in commerce tables: products,
38
- * variants, categories, brands and image URLs (stacksjs/stacks#1319, #1320,
39
- * #1321). It reads only each platform's public storefront API, so it needs no
40
- * credentials (Shopware's Store API asks for the sales channel access key,
41
- * which is public by design), and for the same reason it cannot see customers
42
- * or orders. Those need the platform's admin API and are not imported.
77
+ * By default moves a store's CATALOG into the built-in commerce tables:
78
+ * products, variants, categories, brands and image URLs (stacksjs/stacks#1319,
79
+ * #1320, #1321). That reads only each platform's public storefront API, so it
80
+ * needs no credentials (Shopware's Store API asks for the sales channel access
81
+ * key, which is public by design).
82
+ *
83
+ * `--customers` and `--orders` import those too (stacksjs/stacks#2853), from
84
+ * the platform's admin API. That needs credentials, which are read from env
85
+ * only (SHOPIFY_ADMIN_TOKEN, WOOCOMMERCE_CONSUMER_KEY / _SECRET,
86
+ * SHOPWARE_CLIENT_ID / _SECRET) and never from a flag, where they would land
87
+ * in shell history. A missing one fails before the first request.
43
88
  *
44
- * Re-running is safe: rows are matched on a UUID derived from the source
45
- * product id, so a second run updates what the first one wrote.
89
+ * Re-running is safe: rows are matched on a UUID derived from the source id
90
+ * (customers on their email as well), so a second run updates what the first
91
+ * one wrote.
46
92
  */
47
93
  declare type ImportResult = catalogImport.ImportResult;
48
94
  declare type ImportedProduct = catalogImport.ImportedProduct;
95
+ declare type ImportedCustomer = catalogImport.ImportedCustomer;
96
+ declare type ImportedOrder = catalogImport.ImportedOrder;
97
+ declare type CustomerImportResult = catalogImport.CustomerImportResult;
98
+ declare type OrderImportResult = catalogImport.OrderImportResult;
99
+ declare type AccountCredentials = catalogImport.AccountCredentials;
@@ -1,2 +1,4 @@
1
- import process from"node:process";import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export const SUPPORTED_SOURCES=["shopify","woocommerce","shopware"],SHOPWARE_ACCESS_KEY_HELP='It is public by design, not a secret. Find it in the Shopware Administration under Sales Channels: open the storefront or headless sales channel and copy the key from its "API access" card.';export function parseImportFlags(flags,env=process.env){const source=String(flags.from??"").trim().toLowerCase();if(!source)throw Error(`Say where the catalog comes from: --from ${SUPPORTED_SOURCES.join(" or --from ")}.`);if(!SUPPORTED_SOURCES.includes(source))throw Error(`--from must be one of ${SUPPORTED_SOURCES.join(", ")}; got "${flags.from}".`);let limit;if(flags.limit!==void 0&&flags.limit!==""){limit=Number(flags.limit);if(!Number.isInteger(limit)||limit<=0)throw Error(`--limit must be a whole number above 0; got "${flags.limit}".`)}let currency;if(flags.currency!==void 0&&flags.currency!==""){currency=String(flags.currency).trim().toUpperCase();if(!/^[A-Z]{3}$/.test(currency))throw Error(`--currency must be a three-letter ISO 4217 code such as USD; got "${flags.currency}".`)}const flagKey=flags.accessKey===void 0?"":String(flags.accessKey).trim();let accessKey;if(source==="shopware"){accessKey=flagKey||env.SHOPWARE_ACCESS_KEY?.trim()||void 0;if(!accessKey)throw Error(`Shopware's Store API needs the sales channel access key: pass --access-key <key> or set SHOPWARE_ACCESS_KEY. ${SHOPWARE_ACCESS_KEY_HELP}`);if(/\s/.test(accessKey))throw Error("--access-key must be a single key with no spaces.");if(/^SW(?:IA|UA)/i.test(accessKey))throw Error(`That looks like an Admin API key (it starts with ${accessKey.slice(0,4).toUpperCase()}), not a sales channel access key (SWSC...). ${SHOPWARE_ACCESS_KEY_HELP}`)}else if(flagKey)throw Error(`--access-key only applies to --from shopware; ${source} needs no key.`);return{source,limit,currency,...accessKey?{accessKey}:{},dryRun:flags.dryRun===!0}}function money(minor,currency,format){return minor===null?"unpriced":format(minor,currency)}export function formatImportedProduct(product,format,dryRun=!1){const verb=product.action==="create"?dryRun?"would create":"created":dryRun?"would update":"updated",variantCount=product.variants.create+product.variants.update,details=[money(product.priceMinor,product.currency,format),variantCount>0?`${variantCount} variant${variantCount===1?"":"s"}`:null,product.category?`in ${product.category}`:null,product.vendor?`by ${product.vendor}`:null,product.imageCount===0?"no image":null].filter(Boolean).join(", ");return` ${verb.padEnd(12)} ${product.name} (${product.handle}) ${details}`}export function formatImportSummary(result){const{counts}=result,would=result.dryRun?"would be ":"";return[`Products: ${counts.products.created} ${would}created, ${counts.products.updated} ${would}updated`,`Variants: ${counts.variants.created} ${would}created, ${counts.variants.updated} ${would}updated`,`Categories: ${counts.categories.created} ${would}created. Manufacturers: ${counts.manufacturers.created} ${would}created`,...counts.duplicates>0?[`Duplicates skipped: ${counts.duplicates}`]:[],`Currency: ${result.currencies.length>0?result.currencies.join(", "):"not reported by the store"}`]}export function currencyMismatch(result,configured){if(!configured||result.currencies.length===0)return null;const other=result.currencies.filter((code)=>code!==configured.toUpperCase());if(other.length===0)return null;return`Prices were imported in ${other.join(", ")} minor units, but config/commerce.ts sets currency to ${configured}. products.price has no currency column, so set commerce.currency to match.`}export const OUT_OF_SCOPE_NOTE="Catalog only. Customers and orders are not imported: they need the Shopify Admin API, WooCommerce REST API keys or a Shopware Admin API integration.";async function fail(message){await log.error(message);await log.flush();process.exit(ExitCode.FatalError)}export function commerceImport(buddy){buddy.command("commerce:import <url>","Import a Shopify, WooCommerce or Shopware 6 catalog (products, variants, categories, brands, image URLs)").option("--from <platform>",`Where the catalog comes from: ${SUPPORTED_SOURCES.join(", ")}`).option("--access-key <key>","Shopware only: the sales channel access key (public, from Sales Channels > API access), or set SHOPWARE_ACCESS_KEY").option("--limit <count>","Import at most this many products").option("--currency <code>","ISO 4217 currency, for a store that does not report one (Shopify /meta.json, Shopware /store-api/context)").option("--dry-run","Show what would be created or updated without writing anything",{default:!1}).example("buddy commerce:import https://shop.example.com --from shopify --dry-run").example("buddy commerce:import example.com/shop --from woocommerce --limit 50").example("buddy commerce:import https://shop.example.de --from shopware --access-key SWSC... --dry-run").action(async(url,options)=>{let settings;try{settings=parseImportFlags(options)}catch(error){return fail(error.message)}const{catalogImport}=await import("@stacksjs/commerce"),adapter=catalogImport.catalogAdapter(settings.source);let storeUrl;try{storeUrl=catalogImport.normalizeStoreUrl(url)}catch(error){return fail(error.message)}let repository=catalogImport.createDatabaseRepository();if(settings.dryRun)try{await repository.findProducts(["00000000-0000-0000-0000-000000000000"]);repository=catalogImport.createReadOnlyRepository(repository)}catch(error){log.warn(`No database to compare against (${error.message}). Every product is reported as new.`);repository=catalogImport.createMemoryRepository()}log.info(`${settings.dryRun?"Dry run: reading":"Importing"} the ${settings.source} catalog at ${storeUrl}`);let result;try{result=await catalogImport.importCatalog({adapter,storeUrl,repository,dryRun:settings.dryRun,limit:settings.limit,currency:settings.currency,accessKey:settings.accessKey,onProduct:(product)=>process.stdout.write(`${formatImportedProduct(product,catalogImport.formatMinor,settings.dryRun)}
2
- `)})}catch(error){return fail(`Import stopped: ${error.message}${settings.dryRun?"":" Products written before this point are kept; re-running resumes safely."}`)}if(result.products.length===0)log.info(`${storeUrl} has no products to import.`);for(const warning of result.warnings)log.warn(warning.externalId?`${warning.externalId}: ${warning.message}`:warning.message);for(const line of formatImportSummary(result))log.info(line);try{const{config}=await import("@stacksjs/config"),mismatch=currencyMismatch(result,config.commerce?.currency);if(mismatch)log.warn(mismatch)}catch{}log.info(OUT_OF_SCOPE_NOTE);if(settings.dryRun)log.info("Dry run complete. Nothing was written.");else log.success(`Imported ${result.products.length} product${result.products.length===1?"":"s"} from ${storeUrl}`);await log.flush();process.exit(ExitCode.Success)})}
1
+ import process from"node:process";import{log}from"@stacksjs/cli";import{ExitCode}from"@stacksjs/types";export const SUPPORTED_SOURCES=["shopify","woocommerce","shopware"],CREDENTIAL_ENV={shopify:"SHOPIFY_ADMIN_TOKEN",woocommerce:"WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET",shopware:"SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET"},SHOPWARE_ACCESS_KEY_HELP='It is public by design, not a secret. Find it in the Shopware Administration under Sales Channels: open the storefront or headless sales channel and copy the key from its "API access" card.';export function parseImportFlags(flags,env=process.env){const source=String(flags.from??"").trim().toLowerCase();if(!source)throw Error(`Say where the catalog comes from: --from ${SUPPORTED_SOURCES.join(" or --from ")}.`);if(!SUPPORTED_SOURCES.includes(source))throw Error(`--from must be one of ${SUPPORTED_SOURCES.join(", ")}; got "${flags.from}".`);const customers=flags.customers===!0,orders=flags.orders===!0,include={catalog:flags.catalog===!0||!customers&&!orders,customers,orders};let limit;if(flags.limit!==void 0&&flags.limit!==""){limit=Number(flags.limit);if(!Number.isInteger(limit)||limit<=0)throw Error(`--limit must be a whole number above 0; got "${flags.limit}".`)}let currency;if(flags.currency!==void 0&&flags.currency!==""){currency=String(flags.currency).trim().toUpperCase();if(!/^[A-Z]{3}$/.test(currency))throw Error(`--currency must be a three-letter ISO 4217 code such as USD; got "${flags.currency}".`)}let adminUrl;if(flags.adminUrl!==void 0&&String(flags.adminUrl).trim()!==""){if(!customers&&!orders)throw Error("--admin-url only applies to --customers and --orders; the catalog is read from the storefront.");adminUrl=String(flags.adminUrl).trim()}const flagKey=flags.accessKey===void 0?"":String(flags.accessKey).trim();let accessKey;if(source==="shopware"&&include.catalog){accessKey=flagKey||env.SHOPWARE_ACCESS_KEY?.trim()||void 0;if(!accessKey)throw Error(`Shopware's Store API needs the sales channel access key: pass --access-key <key> or set SHOPWARE_ACCESS_KEY. ${SHOPWARE_ACCESS_KEY_HELP}`);if(/\s/.test(accessKey))throw Error("--access-key must be a single key with no spaces.");if(/^SW(?:IA|UA)/i.test(accessKey))throw Error(`That looks like an Admin API key (it starts with ${accessKey.slice(0,4).toUpperCase()}), not a sales channel access key (SWSC...). Customers and orders read SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET from env instead. ${SHOPWARE_ACCESS_KEY_HELP}`)}else if(flagKey&&source==="shopware")throw Error("--access-key is for the catalog (the Store API). Customers and orders read SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET from env.");else if(flagKey)throw Error(`--access-key only applies to --from shopware; ${source} needs no key.`);return{source,limit,currency,...accessKey?{accessKey}:{},...adminUrl?{adminUrl}:{},include,dryRun:flags.dryRun===!0}}function money(minor,currency,format){return minor===null?"unpriced":format(minor,currency)}function verbOf(action,dryRun){if(action==="create")return dryRun?"would create":"created";return dryRun?"would update":"updated"}export function formatImportedProduct(product,format,dryRun=!1){const variantCount=product.variants.create+product.variants.update,details=[money(product.priceMinor,product.currency,format),variantCount>0?`${variantCount} variant${variantCount===1?"":"s"}`:null,product.category?`in ${product.category}`:null,product.vendor?`by ${product.vendor}`:null,product.imageCount===0?"no image":null].filter(Boolean).join(", ");return` ${verbOf(product.action,dryRun).padEnd(12)} ${product.name} (${product.handle}) ${details}`}export function formatImportedCustomer(customer,dryRun=!1){const matched=customer.matchedBy==="email"?" (matched an existing customer by email)":"";return` ${verbOf(customer.action,dryRun).padEnd(12)} ${customer.name} <${customer.email}>${matched}`}export function formatImportedOrder(order,format,dryRun=!1){const details=[format(order.totalMinor,order.currency),`${order.status} (${order.sourceStatus})`,`${order.lines} line${order.lines===1?"":"s"}`,order.unlinkedLines>0?`${order.unlinkedLines} without a product`:null,order.refundedMinor>0&&order.status!=="REFUNDED"?`${format(order.refundedMinor,order.currency)} refunded`:null,order.customerEmail?`for ${order.customerEmail}`:"no customer"].filter(Boolean).join(", ");return` ${verbOf(order.action,dryRun).padEnd(12)} ${order.number??order.externalId} ${details}`}export function formatImportSummary(result){const{counts}=result,would=result.dryRun?"would be ":"";return[`Products: ${counts.products.created} ${would}created, ${counts.products.updated} ${would}updated`,`Variants: ${counts.variants.created} ${would}created, ${counts.variants.updated} ${would}updated`,`Categories: ${counts.categories.created} ${would}created. Manufacturers: ${counts.manufacturers.created} ${would}created`,...counts.duplicates>0?[`Duplicates skipped: ${counts.duplicates}`]:[],`Currency: ${result.currencies.length>0?result.currencies.join(", "):"not reported by the store"}`]}export function formatCustomerSummary(result){const would=result.dryRun?"would be ":"",{customers,merged}=result.counts;return[`Customers: ${customers.created} ${would}created, ${customers.updated} ${would}updated${merged>0?`, ${merged} merged by email`:""}`]}export function formatOrderSummary(result){const would=result.dryRun?"would be ":"",{orders,customers,lines,duplicates}=result.counts;return[`Orders: ${orders.created} ${would}created, ${orders.updated} ${would}updated${duplicates>0?`, ${duplicates} duplicates skipped`:""}`,`Order lines: ${lines.linked} linked to a product, ${lines.unlinked} without one${lines.productless>0?`, ${lines.productless} with no product at the source (fees, custom or deleted items)`:""}`,...customers.created>0?[`Customers created from orders: ${customers.created}`]:[],`Order currencies: ${result.currencies.length>0?result.currencies.join(", "):"none"}`]}export function currencyMismatch(result,configured){if(!configured||result.currencies.length===0)return null;const other=result.currencies.filter((code)=>code!==configured.toUpperCase());if(other.length===0)return null;return`Prices were imported in ${other.join(", ")} minor units, but config/commerce.ts sets currency to ${configured}. products.price has no currency column, so set commerce.currency to match.`}export function commerceDisabledReason(enabled,dryRun){if(enabled||dryRun)return null;return"Commerce is disabled, so its tables (products, customers, orders) are not migrated. Set enabled: true in config/commerce.ts (or run buddy commerce:install), run buddy migrate, then import again. --dry-run works without it."}export const OUT_OF_SCOPE_NOTE="Customers and orders were not imported. Add --customers and/or --orders, with the admin API credentials in env: SHOPIFY_ADMIN_TOKEN, WOOCOMMERCE_CONSUMER_KEY and WOOCOMMERCE_CONSUMER_SECRET, or SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET.";async function fail(message){await log.error(message);await log.flush();process.exit(ExitCode.FatalError)}function reportWarnings(warnings){for(const warning of warnings)log.warn(warning.externalId?`${warning.externalId}: ${warning.message}`:warning.message)}export function commerceImport(buddy){buddy.command("commerce:import <url>","Import a Shopify, WooCommerce or Shopware 6 catalog, and optionally its customers and orders").option("--from <platform>",`Where the store lives: ${SUPPORTED_SOURCES.join(", ")}`).option("--customers","Also import customers from the admin API (credentials from env: SHOPIFY_ADMIN_TOKEN, WOOCOMMERCE_CONSUMER_KEY/_SECRET or SHOPWARE_CLIENT_ID/_SECRET)",{default:!1}).option("--orders","Also import orders and their lines from the admin API (same credentials as --customers)",{default:!1}).option("--catalog","Import the catalog too when --customers or --orders is given (it is the default otherwise)",{default:!1}).option("--access-key <key>","Shopware catalog only: the sales channel access key (public, from Sales Channels > API access), or set SHOPWARE_ACCESS_KEY").option("--admin-url <url>","Customers and orders only: the admin API address when it differs from <url>, e.g. https://<store>.myshopify.com for a Shopify custom domain").option("--limit <count>","Import at most this many products, customers and orders (each)").option("--currency <code>","ISO 4217 currency, for a store or order that does not report one").option("--dry-run","Show what would be created or updated without writing anything",{default:!1}).example("buddy commerce:import https://shop.example.com --from shopify --dry-run").example("buddy commerce:import example.com/shop --from woocommerce --limit 50").example("buddy commerce:import https://shop.example.de --from shopware --access-key SWSC... --dry-run").example("SHOPIFY_ADMIN_TOKEN=shpat_... buddy commerce:import https://shop.example.com --from shopify --customers --orders --admin-url northwind.myshopify.com").action(async(url,options)=>{let settings;try{settings=parseImportFlags(options)}catch(error){return fail(error.message)}try{const{feature}=await import("@stacksjs/config"),disabled=commerceDisabledReason(feature("commerce"),settings.dryRun);if(disabled)return fail(disabled)}catch{}const{catalogImport}=await import("@stacksjs/commerce"),formatMinor=catalogImport.formatMinor,{include,dryRun}=settings,accounts=include.customers||include.orders;let storeUrl,credentials;try{storeUrl=catalogImport.normalizeStoreUrl(url);if(accounts)credentials=catalogImport.readAccountCredentials(settings.source,process.env)}catch(error){return fail(error.message)}if(include.catalog){let repository=catalogImport.createDatabaseRepository();if(dryRun)try{await repository.findProducts(["00000000-0000-0000-0000-000000000000"]);repository=catalogImport.createReadOnlyRepository(repository)}catch(error){log.warn(`No database to compare against (${error.message}). Every product is reported as new.`);repository=catalogImport.createMemoryRepository()}log.info(`${dryRun?"Dry run: reading":"Importing"} the ${settings.source} catalog at ${storeUrl}`);let result;try{result=await catalogImport.importCatalog({adapter:catalogImport.catalogAdapter(settings.source),storeUrl,repository,dryRun,limit:settings.limit,currency:settings.currency,accessKey:settings.accessKey,onProduct:(product)=>process.stdout.write(`${formatImportedProduct(product,formatMinor,dryRun)}
2
+ `)})}catch(error){return fail(`Import stopped: ${error.message}${dryRun?"":" Products written before this point are kept; re-running resumes safely."}`)}if(result.products.length===0)log.info(`${storeUrl} has no products to import.`);reportWarnings(result.warnings);for(const line of formatImportSummary(result))log.info(line);try{const{config}=await import("@stacksjs/config"),mismatch=currencyMismatch(result,config.commerce?.currency);if(mismatch)log.warn(mismatch)}catch{}}if(accounts){let repository=catalogImport.createDatabaseAccountRepository();if(dryRun){try{await repository.findOrders(["00000000-0000-0000-0000-000000000000"]);repository=catalogImport.createReadOnlyAccountRepository(repository)}catch(error){log.warn(`No database to compare against (${error.message}). Every customer and order is reported as new.`);repository=catalogImport.createReadOnlyAccountRepository(catalogImport.createMemoryAccountRepository())}if(include.catalog&&include.orders)log.info("A dry run writes no products, so order lines are matched only against products already in Stacks.")}const shared={adapter:catalogImport.accountAdapter(settings.source),storeUrl,repository,credentials,dryRun,limit:settings.limit,currency:settings.currency,adminUrl:settings.adminUrl};if(include.customers){log.info(`${dryRun?"Dry run: reading":"Importing"} ${settings.source} customers from ${settings.adminUrl??storeUrl}`);try{const result=await catalogImport.importCustomers({...shared,onCustomer:(customer)=>process.stdout.write(`${formatImportedCustomer(customer,dryRun)}
3
+ `)});reportWarnings(result.warnings);for(const line of formatCustomerSummary(result))log.info(line)}catch(error){return fail(`Customer import stopped: ${error.message}${dryRun?"":" Customers written before this point are kept; re-running resumes safely."}`)}}if(include.orders){log.info(`${dryRun?"Dry run: reading":"Importing"} ${settings.source} orders from ${settings.adminUrl??storeUrl}`);try{const result=await catalogImport.importOrders({...shared,onOrder:(order)=>process.stdout.write(`${formatImportedOrder(order,formatMinor,dryRun)}
4
+ `)});reportWarnings(result.warnings);for(const line of formatOrderSummary(result))log.info(line)}catch(error){return fail(`Order import stopped: ${error.message}${dryRun?"":" Orders written before this point are kept; re-running resumes safely."}`)}}}else log.info(OUT_OF_SCOPE_NOTE);if(dryRun)log.info("Dry run complete. Nothing was written.");else log.success(`Import from ${storeUrl} complete.`);await log.flush();process.exit(ExitCode.Success)})}
@@ -125,6 +125,7 @@ declare interface AppleDesktopOptions {
125
125
  universal?: boolean
126
126
  craftArm64?: string
127
127
  craftX64?: string
128
+ keychain?: string
128
129
  }
129
130
  export declare interface AppleDesktopConfig {
130
131
  appName: string
@@ -144,6 +145,7 @@ export declare interface AppleDesktopConfig {
144
145
  universal?: boolean
145
146
  craftArm64?: string
146
147
  craftX64?: string
148
+ keychain?: string
147
149
  }
148
150
  /** What {@link signingPlan} needs to know; paths are absolute. */
149
151
  export declare interface SigningPlanInput {
@@ -152,6 +154,7 @@ export declare interface SigningPlanInput {
152
154
  helperPath: string
153
155
  appEntitlements: string
154
156
  helperEntitlements: string
157
+ keychain?: string
155
158
  }
156
159
  export declare interface UniversalBinaryInput {
157
160
  name: string
@@ -1,4 +1,4 @@
1
- import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{basename,join,resolve}from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";import{projectPath,storagePath}from"@stacksjs/path";import{resultFailed}from"../result";const REQUIRED_TOOLS=["codesign","security","productbuild","pkgutil","xcrun"];function env(name){return process.env[name]?.trim()||""}function xml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function packageMetadata(){const packageJson=JSON.parse(readFileSync(projectPath("package.json"),"utf8"));return{name:packageJson.name||"Stacks",version:packageJson.version||"0.1.0"}}export function resolveAppleDesktopConfig(options={}){const metadata=packageMetadata(),provisioningProfile=options.provisioningProfile||env("APPLE_PROVISIONING_PROFILE"),apiKeyPath=options.apiKeyPath||env("APP_STORE_CONNECT_API_KEY_PATH"),craftArm64=options.craftArm64||env("CRAFT_BIN_ARM64"),craftX64=options.craftX64||env("CRAFT_BIN_X64");return{appName:options.appName||env("APPLE_APP_NAME")||env("APP_NAME")||metadata.name,bundleId:options.bundleId||env("APPLE_BUNDLE_ID"),teamId:options.teamId||env("APPLE_TEAM_ID"),version:options.appVersion||env("APPLE_APP_VERSION")||metadata.version,buildNumber:options.buildNumber||env("APPLE_BUILD_NUMBER")||env("GITHUB_RUN_NUMBER")||String(Math.floor(Date.now()/1000)),minimumMacos:options.minimumMacos||env("APPLE_MINIMUM_MACOS")||"13.0",category:options.category||env("APPLE_APP_CATEGORY")||"public.app-category.productivity",appSigningIdentity:options.appSigningIdentity||env("APPLE_APP_SIGNING_IDENTITY"),installerSigningIdentity:options.installerSigningIdentity||env("APPLE_INSTALLER_SIGNING_IDENTITY"),provisioningProfile:provisioningProfile?resolve(provisioningProfile):"",apiKeyId:options.apiKeyId||env("APP_STORE_CONNECT_API_KEY_ID"),apiIssuerId:options.apiIssuerId||env("APP_STORE_CONNECT_API_ISSUER_ID"),apiKeyPath:apiKeyPath?resolve(apiKeyPath):"",icon:options.icon||env("APPLE_APP_ICON")||void 0,universal:Boolean(options.universal)||env("APPLE_UNIVERSAL")==="true",craftArm64:craftArm64?resolve(craftArm64):void 0,craftX64:craftX64?resolve(craftX64):void 0}}export function validateAppleDesktopConfig(config,includeApi=!0){const errors=[];if(process.platform!=="darwin")errors.push("Mac App Store packaging must run on macOS");if(!config.appName)errors.push("APPLE_APP_NAME or --app-name is required");if(!/^[A-Za-z0-9][A-Za-z0-9.-]+$/.test(config.bundleId))errors.push("APPLE_BUNDLE_ID must be a reverse-DNS bundle identifier");if(!/^[A-Z0-9]{10}$/.test(config.teamId))errors.push("APPLE_TEAM_ID must be the 10-character Apple Developer team ID");if(!/^\d+(?:\.\d+){0,2}$/.test(config.version))errors.push("The marketing version must contain one to three numeric components");if(!/^[A-Za-z0-9.-]+$/.test(config.buildNumber))errors.push("The build number must contain only letters, numbers, periods, and hyphens");if(!config.appSigningIdentity)errors.push("APPLE_APP_SIGNING_IDENTITY is required");if(!config.installerSigningIdentity)errors.push("APPLE_INSTALLER_SIGNING_IDENTITY is required");if(!config.provisioningProfile||!existsSync(config.provisioningProfile))errors.push("APPLE_PROVISIONING_PROFILE must point to an existing .provisionprofile file");if(config.icon&&!existsSync(resolve(config.icon)))errors.push(`Apple app icon does not exist: ${config.icon}`);if(!/^\d+(?:\.\d+){0,2}$/.test(config.minimumMacos))errors.push("APPLE_MINIMUM_MACOS must be a macOS version such as 13.0");if(!isAppleCategory(config.category))errors.push("APPLE_APP_CATEGORY must be an Apple LSApplicationCategoryType such as public.app-category.productivity");if(includeApi){if(!config.apiKeyId)errors.push("APP_STORE_CONNECT_API_KEY_ID is required");if(!config.apiIssuerId)errors.push("APP_STORE_CONNECT_API_ISSUER_ID is required");if(!config.apiKeyPath||!existsSync(config.apiKeyPath))errors.push("APP_STORE_CONNECT_API_KEY_PATH must point to an existing .p8 file")}if(config.universal){for(const[variable,path]of[["CRAFT_BIN_ARM64",config.craftArm64],["CRAFT_BIN_X64",config.craftX64]])if(!path||!existsSync(path))errors.push(`${variable} must point to a native Craft runtime for a universal build`);else if(readFileSync(path).subarray(0,2).toString()==="#!")errors.push(`${variable} points at a script, not a native Craft runtime: ${path}`)}for(const tool of config.universal?[...REQUIRED_TOOLS,"lipo"]:REQUIRED_TOOLS)if(!Bun.which(tool))errors.push(`Required Apple command is unavailable: ${tool}`);return errors}function bundleFiles(appPath){const walk=(dir,prefix)=>readdirSync(dir,{withFileTypes:!0}).flatMap((entry)=>{const relative=prefix?`${prefix}/${entry.name}`:entry.name;return entry.isDirectory()?walk(join(dir,entry.name),relative):[relative]});return walk(appPath,"")}export function isAppleCategory(value){return/^public\.app-category\.[a-z][a-z0-9-]*$/.test(value)}export function storeRejectionFindings(paths,executable="stacks-desktop"){const findings=[],has=(path)=>paths.includes(path);for(const required of["Contents/Info.plist",`Contents/MacOS/${executable}`,"Contents/embedded.provisionprofile"])if(!has(required))findings.push(`missing required bundle file: ${required}`);for(const path of paths){const base=path.split("/").pop()??"";if(base===".DS_Store"||path.startsWith("__MACOSX/")||base.startsWith("._"))findings.push(`forbidden file in the bundle: ${path}`);if(/\.(?:dylib|so|framework|app|xpc)$/.test(path)){if(!(path.startsWith("Contents/Frameworks/")||path.startsWith("Contents/MacOS/")||path.startsWith("Contents/XPCServices/")||path.startsWith("Contents/PlugIns/")))findings.push(`nested code outside a signed location: ${path}`)}if(path.startsWith("Contents/Resources/")&&/\.(?:sh|command|dylib|so)$/.test(path))findings.push(`executable content under Resources: ${path}`)}return findings}export function renderInfoPlist(config,executable="stacks-desktop"){const iconEntry=config.icon?`
1
+ import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{basename,join,resolve}from"node:path";import process from"node:process";import{log}from"@stacksjs/cli";import{projectPath,storagePath}from"@stacksjs/path";import{resultFailed}from"../result";const REQUIRED_TOOLS=["codesign","security","productbuild","pkgutil","xcrun"];function env(name){return process.env[name]?.trim()||""}function xml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function packageMetadata(){const packageJson=JSON.parse(readFileSync(projectPath("package.json"),"utf8"));return{name:packageJson.name||"Stacks",version:packageJson.version||"0.1.0"}}export function resolveAppleDesktopConfig(options={}){const metadata=packageMetadata(),provisioningProfile=options.provisioningProfile||env("APPLE_PROVISIONING_PROFILE"),apiKeyPath=options.apiKeyPath||env("APP_STORE_CONNECT_API_KEY_PATH"),craftArm64=options.craftArm64||env("CRAFT_BIN_ARM64"),craftX64=options.craftX64||env("CRAFT_BIN_X64"),keychain=options.keychain||env("APPLE_KEYCHAIN");return{appName:options.appName||env("APPLE_APP_NAME")||env("APP_NAME")||metadata.name,bundleId:options.bundleId||env("APPLE_BUNDLE_ID"),teamId:options.teamId||env("APPLE_TEAM_ID"),version:options.appVersion||env("APPLE_APP_VERSION")||metadata.version,buildNumber:options.buildNumber||env("APPLE_BUILD_NUMBER")||env("GITHUB_RUN_NUMBER")||String(Math.floor(Date.now()/1000)),minimumMacos:options.minimumMacos||env("APPLE_MINIMUM_MACOS")||"13.0",category:options.category||env("APPLE_APP_CATEGORY")||"public.app-category.productivity",appSigningIdentity:options.appSigningIdentity||env("APPLE_APP_SIGNING_IDENTITY"),installerSigningIdentity:options.installerSigningIdentity||env("APPLE_INSTALLER_SIGNING_IDENTITY"),provisioningProfile:provisioningProfile?resolve(provisioningProfile):"",apiKeyId:options.apiKeyId||env("APP_STORE_CONNECT_API_KEY_ID"),apiIssuerId:options.apiIssuerId||env("APP_STORE_CONNECT_API_ISSUER_ID"),apiKeyPath:apiKeyPath?resolve(apiKeyPath):"",icon:options.icon||env("APPLE_APP_ICON")||void 0,universal:Boolean(options.universal)||env("APPLE_UNIVERSAL")==="true",craftArm64:craftArm64?resolve(craftArm64):void 0,craftX64:craftX64?resolve(craftX64):void 0,keychain:keychain?resolve(keychain):void 0}}export function validateAppleDesktopConfig(config,includeApi=!0){const errors=[];if(process.platform!=="darwin")errors.push("Mac App Store packaging must run on macOS");if(!config.appName)errors.push("APPLE_APP_NAME or --app-name is required");if(!/^[A-Za-z0-9][A-Za-z0-9.-]+$/.test(config.bundleId))errors.push("APPLE_BUNDLE_ID must be a reverse-DNS bundle identifier");if(!/^[A-Z0-9]{10}$/.test(config.teamId))errors.push("APPLE_TEAM_ID must be the 10-character Apple Developer team ID");if(!/^\d+(?:\.\d+){0,2}$/.test(config.version))errors.push("The marketing version must contain one to three numeric components");if(!/^[A-Za-z0-9.-]+$/.test(config.buildNumber))errors.push("The build number must contain only letters, numbers, periods, and hyphens");if(!config.appSigningIdentity)errors.push("APPLE_APP_SIGNING_IDENTITY is required");if(!config.installerSigningIdentity)errors.push("APPLE_INSTALLER_SIGNING_IDENTITY is required");if(!config.provisioningProfile||!existsSync(config.provisioningProfile))errors.push("APPLE_PROVISIONING_PROFILE must point to an existing .provisionprofile file");if(config.icon&&!existsSync(resolve(config.icon)))errors.push(`Apple app icon does not exist: ${config.icon}`);if(!/^\d+(?:\.\d+){0,2}$/.test(config.minimumMacos))errors.push("APPLE_MINIMUM_MACOS must be a macOS version such as 13.0");if(!isAppleCategory(config.category))errors.push("APPLE_APP_CATEGORY must be an Apple LSApplicationCategoryType such as public.app-category.productivity");if(includeApi){if(!config.apiKeyId)errors.push("APP_STORE_CONNECT_API_KEY_ID is required");if(!config.apiIssuerId)errors.push("APP_STORE_CONNECT_API_ISSUER_ID is required");if(!config.apiKeyPath||!existsSync(config.apiKeyPath))errors.push("APP_STORE_CONNECT_API_KEY_PATH must point to an existing .p8 file")}if(config.universal){for(const[variable,path]of[["CRAFT_BIN_ARM64",config.craftArm64],["CRAFT_BIN_X64",config.craftX64]])if(!path||!existsSync(path))errors.push(`${variable} must point to a native Craft runtime for a universal build`);else if(readFileSync(path).subarray(0,2).toString()==="#!")errors.push(`${variable} points at a script, not a native Craft runtime: ${path}`)}for(const tool of config.universal?[...REQUIRED_TOOLS,"lipo"]:REQUIRED_TOOLS)if(!Bun.which(tool))errors.push(`Required Apple command is unavailable: ${tool}`);return errors}function bundleFiles(appPath){const walk=(dir,prefix)=>readdirSync(dir,{withFileTypes:!0}).flatMap((entry)=>{const relative=prefix?`${prefix}/${entry.name}`:entry.name;return entry.isDirectory()?walk(join(dir,entry.name),relative):[relative]});return walk(appPath,"")}export function isAppleCategory(value){return/^public\.app-category\.[a-z][a-z0-9-]*$/.test(value)}export function storeRejectionFindings(paths,executable="stacks-desktop"){const findings=[],has=(path)=>paths.includes(path);for(const required of["Contents/Info.plist",`Contents/MacOS/${executable}`,"Contents/embedded.provisionprofile"])if(!has(required))findings.push(`missing required bundle file: ${required}`);for(const path of paths){const base=path.split("/").pop()??"";if(base===".DS_Store"||path.startsWith("__MACOSX/")||base.startsWith("._"))findings.push(`forbidden file in the bundle: ${path}`);if(/\.(?:dylib|so|framework|app|xpc)$/.test(path)){if(!(path.startsWith("Contents/Frameworks/")||path.startsWith("Contents/MacOS/")||path.startsWith("Contents/XPCServices/")||path.startsWith("Contents/PlugIns/")))findings.push(`nested code outside a signed location: ${path}`)}if(path.startsWith("Contents/Resources/")&&/\.(?:sh|command|dylib|so)$/.test(path))findings.push(`executable content under Resources: ${path}`)}return findings}export function renderInfoPlist(config,executable="stacks-desktop"){const iconEntry=config.icon?`
2
2
  <key>CFBundleIconFile</key>
3
3
  <string>AppIcon</string>`:"";return`<?xml version="1.0" encoding="UTF-8"?>
4
4
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -94,14 +94,14 @@ jobs:
94
94
  s3-prefix: \${{ vars.RELEASE_S3_PREFIX }}
95
95
  s3-public-url: \${{ vars.RELEASE_S3_PUBLIC_URL }}
96
96
  secrets: inherit
97
- `}function command(args,cwd=projectPath()){const result=Bun.spawnSync(args,{cwd,stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(result.exitCode!==0)throw Error(`${args[0]} ${args.slice(1).join(" ")} exited with code ${result.exitCode}`)}export function signingPlan(input){const sign=(entitlements,target)=>["codesign","--force","--timestamp","--options","runtime","--entitlements",entitlements,"--sign",input.identity,target];return[sign(input.helperEntitlements,input.helperPath),sign(input.appEntitlements,input.appPath)]}export const captureCommand=(args)=>{const result=Bun.spawnSync(args,{cwd:projectPath(),stdin:"inherit",stdout:"pipe",stderr:"inherit"});if(result.exitCode!==0)throw Error(`${args[0]} ${args.slice(1).join(" ")} exited with code ${result.exitCode}`);return result.stdout.toString()},MACH_O_ARCHITECTURE={arm64:"arm64",x64:"x86_64"};export function parseLipoArchs(output){return output.trim().split(/\s+/).filter(Boolean).sort()}export function mergeUniversalBinary(input,run=captureCommand){for(const architecture of["arm64","x64"]){const expected=MACH_O_ARCHITECTURE[architecture],found=parseLipoArchs(run(["lipo","-archs",input[architecture]]));if(found.length!==1||found[0]!==expected)throw Error(`${input.name}: the ${architecture} input ${input[architecture]} contains ${found.join(" + ")||"no architectures"}, expected only ${expected}`)}run(["lipo","-create","-output",input.output,input.arm64,input.x64]);const merged=parseLipoArchs(run(["lipo","-archs",input.output])),expected=Object.values(MACH_O_ARCHITECTURE).sort();if(merged.join(" ")!==expected.join(" "))throw Error(`${input.name}: the universal binary ${input.output} contains ${merged.join(" + ")||"no architectures"}, expected ${expected.join(" + ")}`);return merged}export function buildUniversalPayload(input,run=captureCommand){const slice=(architecture)=>join(input.directory,architecture,"stacks-desktop");for(const architecture of["arm64","x64"]){mkdirSync(join(input.directory,architecture),{recursive:!0});run(input.launcherCompileArgs(architecture,slice(architecture)))}const launcher=join(input.directory,"stacks-desktop"),runtime=join(input.directory,"craft-runtime");mergeUniversalBinary({name:"stacks-desktop",arm64:slice("arm64"),x64:slice("x64"),output:launcher},run);const architectures=mergeUniversalBinary({name:"craft-runtime",arm64:input.craft.arm64,x64:input.craft.x64,output:runtime},run);return{launcher,runtime,architectures}}export function launcherSliceCompileArgs(base,architecture){return["bun",...base,`--target=bun-darwin-${architecture}`]}function signingIdentityExists(identity){if(!identity)return!1;const result=Bun.spawnSync(["security","find-identity","-v"],{stdout:"pipe",stderr:"pipe"});return result.exitCode===0&&result.stdout.toString().includes(identity)}function provisioningProfileMatches(config){if(!config.provisioningProfile||!existsSync(config.provisioningProfile))return!1;const result=Bun.spawnSync(["security","cms","-D","-i",config.provisioningProfile],{stdout:"pipe",stderr:"pipe"});if(result.exitCode!==0)return!1;const profile=result.stdout.toString();return profile.includes(config.bundleId)&&profile.includes(config.teamId)}async function buildDesktop(){const{runAction}=await import("@stacksjs/actions"),{Action}=await import("@stacksjs/enums"),result=await runAction(Action.BuildDesktop);if(resultFailed(result))throw result.error}function sha256(path){return createHash("sha256").update(readFileSync(path)).digest("hex")}async function packageAppleDesktop(config,skipBuild=!1){const errors=validateAppleDesktopConfig(config,!1);if(!signingIdentityExists(config.appSigningIdentity))errors.push(`App signing identity is not installed: ${config.appSigningIdentity}`);if(!signingIdentityExists(config.installerSigningIdentity))errors.push(`Installer signing identity is not installed: ${config.installerSigningIdentity}`);if(!provisioningProfileMatches(config))errors.push(`Provisioning profile does not match ${config.teamId}.${config.bundleId}`);if(errors.length)throw Error(errors.join(`
97
+ `}function command(args,cwd=projectPath()){const result=Bun.spawnSync(args,{cwd,stdin:"inherit",stdout:"inherit",stderr:"inherit"});if(result.exitCode!==0)throw Error(`${args[0]} ${args.slice(1).join(" ")} exited with code ${result.exitCode}`)}export function signingPlan(input){const sign=(entitlements,target)=>["codesign","--force","--timestamp","--options","runtime","--entitlements",entitlements,...input.keychain?["--keychain",input.keychain]:[],"--sign",input.identity,target];return[sign(input.helperEntitlements,input.helperPath),sign(input.appEntitlements,input.appPath)]}export const captureCommand=(args)=>{const result=Bun.spawnSync(args,{cwd:projectPath(),stdin:"inherit",stdout:"pipe",stderr:"inherit"});if(result.exitCode!==0)throw Error(`${args[0]} ${args.slice(1).join(" ")} exited with code ${result.exitCode}`);return result.stdout.toString()},MACH_O_ARCHITECTURE={arm64:"arm64",x64:"x86_64"};export function parseLipoArchs(output){return output.trim().split(/\s+/).filter(Boolean).sort()}export function mergeUniversalBinary(input,run=captureCommand){for(const architecture of["arm64","x64"]){const expected=MACH_O_ARCHITECTURE[architecture],found=parseLipoArchs(run(["lipo","-archs",input[architecture]]));if(found.length!==1||found[0]!==expected)throw Error(`${input.name}: the ${architecture} input ${input[architecture]} contains ${found.join(" + ")||"no architectures"}, expected only ${expected}`)}run(["lipo","-create","-output",input.output,input.arm64,input.x64]);const merged=parseLipoArchs(run(["lipo","-archs",input.output])),expected=Object.values(MACH_O_ARCHITECTURE).sort();if(merged.join(" ")!==expected.join(" "))throw Error(`${input.name}: the universal binary ${input.output} contains ${merged.join(" + ")||"no architectures"}, expected ${expected.join(" + ")}`);return merged}export function buildUniversalPayload(input,run=captureCommand){const slice=(architecture)=>join(input.directory,architecture,"stacks-desktop");for(const architecture of["arm64","x64"]){mkdirSync(join(input.directory,architecture),{recursive:!0});run(input.launcherCompileArgs(architecture,slice(architecture)))}const launcher=join(input.directory,"stacks-desktop"),runtime=join(input.directory,"craft-runtime");mergeUniversalBinary({name:"stacks-desktop",arm64:slice("arm64"),x64:slice("x64"),output:launcher},run);const architectures=mergeUniversalBinary({name:"craft-runtime",arm64:input.craft.arm64,x64:input.craft.x64,output:runtime},run);return{launcher,runtime,architectures}}export function launcherSliceCompileArgs(base,architecture){return["bun",...base,`--target=bun-darwin-${architecture}`]}function signingIdentityExists(identity,keychain){if(!identity)return!1;const result=Bun.spawnSync(["security","find-identity","-v",...keychain?[keychain]:[]],{stdout:"pipe",stderr:"pipe"});return result.exitCode===0&&result.stdout.toString().includes(identity)}function provisioningProfileMatches(config){if(!config.provisioningProfile||!existsSync(config.provisioningProfile))return!1;const result=Bun.spawnSync(["security","cms","-D","-i",config.provisioningProfile],{stdout:"pipe",stderr:"pipe"});if(result.exitCode!==0)return!1;const profile=result.stdout.toString();return profile.includes(config.bundleId)&&profile.includes(config.teamId)}async function buildDesktop(){const{runAction}=await import("@stacksjs/actions"),{Action}=await import("@stacksjs/enums"),result=await runAction(Action.BuildDesktop);if(resultFailed(result))throw result.error}function sha256(path){return createHash("sha256").update(readFileSync(path)).digest("hex")}async function packageAppleDesktop(config,skipBuild=!1){const errors=validateAppleDesktopConfig(config,!1);if(config.keychain&&!existsSync(config.keychain))errors.push(`APPLE_KEYCHAIN does not exist: ${config.keychain}`);const where=config.keychain?` in ${config.keychain}`:"";if(!signingIdentityExists(config.appSigningIdentity,config.keychain))errors.push(`App signing identity is not installed${where}: ${config.appSigningIdentity}`);if(!signingIdentityExists(config.installerSigningIdentity,config.keychain))errors.push(`Installer signing identity is not installed${where}: ${config.installerSigningIdentity}`);if(!provisioningProfileMatches(config))errors.push(`Provisioning profile does not match ${config.teamId}.${config.bundleId}`);if(errors.length)throw Error(errors.join(`
98
98
  `));if(!skipBuild)await buildDesktop();const desktopDist=storagePath("framework/desktop-dist");let launcher=join(desktopDist,"stacks-desktop"),runtime=join(desktopDist,"craft-runtime");const manifest=join(desktopDist,"desktop.json");for(const path of[launcher,runtime,manifest])if(!existsSync(path))throw Error(`Desktop build artifact is missing: ${path}`);let architectures=[process.arch==="x64"?"x86_64":process.arch],craftSlices;if(config.universal){const universalDir=join(desktopDist,"universal");if(existsSync(universalDir))rmSync(universalDir,{recursive:!0});const{desktopLauncherCompileArgs,resolveDesktopLauncher}=await import("@stacksjs/desktop-build"),entry=resolveDesktopLauncher(projectPath()),minify=process.env.DESKTOP_MINIFY!=="false",payload=buildUniversalPayload({directory:universalDir,launcherCompileArgs:(architecture,outfile)=>launcherSliceCompileArgs(desktopLauncherCompileArgs({entry,outfile,minify}),architecture),craft:{arm64:config.craftArm64,x64:config.craftX64}});launcher=payload.launcher;runtime=payload.runtime;architectures=payload.architectures;craftSlices={arm64:config.craftArm64,x64:config.craftX64}}const appleDir=join(desktopDist,"apple"),appPath=join(appleDir,`${config.appName}.app`),contents=join(appPath,"Contents"),macosDir=join(contents,"MacOS"),resourcesDir=join(contents,"Resources");if(existsSync(appleDir))rmSync(appleDir,{recursive:!0});mkdirSync(macosDir,{recursive:!0});mkdirSync(resourcesDir,{recursive:!0});copyFileSync(launcher,join(macosDir,"stacks-desktop"));copyFileSync(runtime,join(macosDir,"craft-runtime"));if(config.universal){const parsed=JSON.parse(readFileSync(manifest,"utf8"));writeFileSync(join(resourcesDir,"desktop.json"),`${JSON.stringify({...parsed,architecture:"universal"},null,2)}
99
- `)}else copyFileSync(manifest,join(resourcesDir,"desktop.json"));copyFileSync(config.provisioningProfile,join(contents,"embedded.provisionprofile"));chmodSync(join(macosDir,"stacks-desktop"),493);chmodSync(join(macosDir,"craft-runtime"),493);if(config.icon)copyFileSync(resolve(config.icon),join(resourcesDir,"AppIcon.icns"));const infoPlist=join(contents,"Info.plist"),appEntitlements=join(appleDir,"app.entitlements"),helperEntitlements=join(appleDir,"helper.entitlements");writeFileSync(infoPlist,renderInfoPlist(config));writeFileSync(appEntitlements,renderAppEntitlements(config));writeFileSync(helperEntitlements,renderHelperEntitlements());command(["plutil","-lint",infoPlist,appEntitlements,helperEntitlements]);for(const args of signingPlan({identity:config.appSigningIdentity,appPath,helperPath:join(macosDir,"craft-runtime"),appEntitlements,helperEntitlements}))command(args);command(["codesign","--verify","--deep","--strict","--verbose=2",appPath]);command(["codesign","-d","--entitlements",":-",appPath]);const findings=storeRejectionFindings(bundleFiles(appPath));if(findings.length>0)throw Error(`The app bundle would be rejected by App Review:
99
+ `)}else copyFileSync(manifest,join(resourcesDir,"desktop.json"));copyFileSync(config.provisioningProfile,join(contents,"embedded.provisionprofile"));chmodSync(join(macosDir,"stacks-desktop"),493);chmodSync(join(macosDir,"craft-runtime"),493);if(config.icon)copyFileSync(resolve(config.icon),join(resourcesDir,"AppIcon.icns"));const infoPlist=join(contents,"Info.plist"),appEntitlements=join(appleDir,"app.entitlements"),helperEntitlements=join(appleDir,"helper.entitlements");writeFileSync(infoPlist,renderInfoPlist(config));writeFileSync(appEntitlements,renderAppEntitlements(config));writeFileSync(helperEntitlements,renderHelperEntitlements());command(["plutil","-lint",infoPlist,appEntitlements,helperEntitlements]);for(const args of signingPlan({identity:config.appSigningIdentity,appPath,helperPath:join(macosDir,"craft-runtime"),appEntitlements,helperEntitlements,keychain:config.keychain}))command(args);command(["codesign","--verify","--deep","--strict","--verbose=2",appPath]);command(["codesign","-d","--entitlements","-","--xml",appPath]);const findings=storeRejectionFindings(bundleFiles(appPath));if(findings.length>0)throw Error(`The app bundle would be rejected by App Review:
100
100
  ${findings.map((finding)=>` - ${finding}`).join(`
101
- `)}`);const packagePath=join(appleDir,`${config.appName}-${config.version}-${config.buildNumber}.pkg`);command(["productbuild","--component",appPath,"/Applications","--sign",config.installerSigningIdentity,packagePath]);command(["pkgutil","--check-signature",packagePath]);const packageHash=sha256(packagePath);writeFileSync(join(appleDir,"checksums.sha256"),`${packageHash} ${basename(packagePath)}
101
+ `)}`);const packagePath=join(appleDir,`${config.appName}-${config.version}-${config.buildNumber}.pkg`);command(["productbuild","--component",appPath,"/Applications",...config.keychain?["--keychain",config.keychain]:[],"--sign",config.installerSigningIdentity,packagePath]);command(["pkgutil","--check-signature",packagePath]);const packageHash=sha256(packagePath);writeFileSync(join(appleDir,"checksums.sha256"),`${packageHash} ${basename(packagePath)}
102
102
  `);writeFileSync(join(appleDir,"apple-provenance.json"),`${JSON.stringify({schemaVersion:"1.0.0",appName:config.appName,bundleId:config.bundleId,teamId:config.teamId,version:config.version,buildNumber:config.buildNumber,minimumMacos:config.minimumMacos,architectures,package:{name:basename(packagePath),sha256:packageHash},sourceRevision:Bun.spawnSync(["git","rev-parse","HEAD"],{cwd:projectPath()}).stdout.toString().trim(),craft:{sha256:sha256(join(macosDir,"craft-runtime")),...craftSlices&&{slices:{arm64:sha256(craftSlices.arm64),x64:sha256(craftSlices.x64)}}}},null,2)}
103
103
  `);return packagePath}function validateOrUpload(packagePath,config,validateOnly){const errors=validateAppleDesktopConfig(config,!0);if(errors.length)throw Error(errors.join(`
104
104
  `));const common=["--type","macos","--file",packagePath,"--apiKey",config.apiKeyId,"--apiIssuer",config.apiIssuerId];process.env.API_PRIVATE_KEYS_DIR=resolve(config.apiKeyPath,"..");command(["xcrun","altool","--validate-app",...common]);if(!validateOnly)command(["xcrun","altool","--upload-app",...common])}export function renderFailure(error){return`${error instanceof Error?error.message:String(error)}
105
105
  `}function fail(error){process.stderr.write(renderFailure(error));process.exit(1)}export function desktopApple(buddy){buddy.command("desktop:apple:csr","Generate local private keys and CSRs for Mac App Store distribution certificates").option("--common-name <name>","Certificate request common name").option("--output <path>","Directory for private keys and certificate requests").action(async(options)=>{try{const metadata=packageMetadata(),outputDirectory=resolve(options.output||storagePath("framework/desktop-dist/apple/provisioning")),{generateMacCertificateRequests}=await import("ts-pantry");generateMacCertificateRequests({outputDirectory,commonName:options.commonName||metadata.name});log.success(`Generated Apple certificate requests and private keys in ${outputDirectory}`)}catch(error){fail(error)}});buddy.command("desktop:apple:provision","Plan or reconcile Apple Bundle ID, capabilities, certificates, and profile").option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--capabilities <types>","Comma-separated Apple capability types").option("--app-certificate-csr <path>","CSR for a missing Mac App Distribution certificate").option("--installer-certificate-csr <path>","CSR for a missing Mac Installer Distribution certificate").option("--profile-name <name>","Provisioning profile name").option("--output <path>","Directory for the plan and downloaded Apple assets").option("--plan","Report the idempotent Apple resource diff without mutating it").option("--apply","Apply the Apple resource diff without revoking existing certificates").action(async(options)=>{try{if(options.plan&&options.apply)throw Error("Choose either --plan or --apply");const config=resolveAppleDesktopConfig(options);if(!config.bundleId)throw Error("APPLE_BUNDLE_ID or --bundle-id is required");if(!config.apiKeyId||!config.apiIssuerId||!config.apiKeyPath||!existsSync(config.apiKeyPath))throw Error("App Store Connect API key ID, issuer ID, and existing .p8 key path are required");const readCsr=(file)=>{if(!file)return;const resolved=resolve(file);if(!existsSync(resolved))throw Error(`Apple certificate CSR does not exist: ${resolved}`);return readFileSync(resolved,"utf8")},{exportAppleCertificateP12,provisionMacApp}=await import("ts-pantry"),result=await provisionMacApp({identifier:config.bundleId,name:config.appName,capabilities:options.capabilities?.split(",").map((value)=>value.trim()).filter(Boolean),appCertificateCsr:readCsr(options.appCertificateCsr),installerCertificateCsr:readCsr(options.installerCertificateCsr),profileName:options.profileName,keyId:config.apiKeyId,issuerId:config.apiIssuerId,keyPath:config.apiKeyPath,checkOnly:!options.apply}),outputDirectory=resolve(options.output||storagePath("framework/desktop-dist/apple/provisioning"));mkdirSync(outputDirectory,{recursive:!0});for(const certificate of result.certificates){if(!certificate.certificateContent)continue;const fileName=certificate.type==="MAC_APP_DISTRIBUTION"?"mac-app-distribution.cer":"mac-installer-distribution.cer";writeFileSync(join(outputDirectory,fileName),Buffer.from(certificate.certificateContent,"base64"),{mode:384})}if(result.profile.profileContent)writeFileSync(join(outputDirectory,"mac-app-store.provisionprofile"),Buffer.from(result.profile.profileContent,"base64"),{mode:384});const certificatePassword=env("APPLE_CERTIFICATE_PASSWORD"),certificateExports=[{type:"MAC_APP_DISTRIBUTION",csr:options.appCertificateCsr,certificate:"mac-app-distribution.cer",output:"mac-app-distribution.p12",name:`${config.appName} Mac App Distribution`},{type:"MAC_INSTALLER_DISTRIBUTION",csr:options.installerCertificateCsr,certificate:"mac-installer-distribution.cer",output:"mac-installer-distribution.p12",name:`${config.appName} Mac Installer Distribution`}];for(const certificateExport of certificateExports){if(!result.certificates.find((item)=>item.type===certificateExport.type)?.certificateContent||!certificateExport.csr||!certificatePassword)continue;exportAppleCertificateP12({certificatePath:join(outputDirectory,certificateExport.certificate),privateKeyPath:resolve(certificateExport.csr.replace(/\.csr$/i,".key")),outputPath:join(outputDirectory,certificateExport.output),password:certificatePassword,name:certificateExport.name})}const certificates=result.certificates.map((item)=>{const certificate={...item};delete certificate.certificateContent;return certificate}),profile={...result.profile};delete profile.profileContent;const report={...result,certificates,profile},reportPath=join(outputDirectory,"provisioning-plan.json");writeFileSync(reportPath,`${JSON.stringify(report,null,2)}
106
- `,{mode:384});log.success(`${options.apply?"Applied":"Planned"} Apple provisioning: ${reportPath}`);if(!result.appRecord.exists&&result.appRecord.manualAction)log.warn(result.appRecord.manualAction)}catch(error){fail(error)}});buddy.command("desktop:apple:doctor","Validate Mac App Store tooling, credentials, certificates, and project metadata").option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").action((options)=>{try{const config=resolveAppleDesktopConfig(options),errors=validateAppleDesktopConfig(config,!0);if(!signingIdentityExists(config.appSigningIdentity))errors.push(`App signing identity is not installed: ${config.appSigningIdentity}`);if(!signingIdentityExists(config.installerSigningIdentity))errors.push(`Installer signing identity is not installed: ${config.installerSigningIdentity}`);if(!provisioningProfileMatches(config))errors.push(`Provisioning profile does not match ${config.teamId}.${config.bundleId}`);if(errors.length)throw Error(errors.join(`
107
- `));log.success(`Mac App Store prerequisites are ready for ${config.bundleId}`)}catch(error){fail(error)}});buddy.command("desktop:apple:init","Create a GitHub Actions caller for the reusable Stacks Mac App Store workflow").option("--force","Replace an existing workflow").action((options)=>{try{const workflowPath=projectPath(".github/workflows/apple-app-store.yml");if(existsSync(workflowPath)&&!options.force)throw Error(`${workflowPath} already exists. Use --force to replace it.`);mkdirSync(resolve(workflowPath,".."),{recursive:!0});writeFileSync(workflowPath,renderAppleWorkflowCaller());log.success(`Created ${workflowPath}`)}catch(error){fail(error)}});const addSharedOptions=(commandBuilder)=>commandBuilder.option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-version <version>","Marketing version").option("--build-number <number>","Unique App Store build number").option("--minimum-macos <version>","Minimum supported macOS version").option("--category <category>","LSApplicationCategoryType value").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--icon <path>","Optional .icns app icon").option("--skip-build","Package existing storage/framework/desktop-dist artifacts").option("--universal","Ship one arm64 + x86_64 binary, merged with lipo").option("--craft-arm64 <path>","Thin arm64 Craft runtime for --universal (or CRAFT_BIN_ARM64)").option("--craft-x64 <path>","Thin x86_64 Craft runtime for --universal (or CRAFT_BIN_X64)");addSharedOptions(buddy.command("desktop:apple:package","Build, sandbox, sign, and package a Mac App Store desktop app")).action(async(options)=>{try{const packagePath=await packageAppleDesktop(resolveAppleDesktopConfig(options),Boolean(options.skipBuild));log.success(`Created signed Mac App Store package ${packagePath}`)}catch(error){fail(error)}});addSharedOptions(buddy.command("desktop:apple:publish","Build and validate or upload a signed Mac App Store package")).option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--validate-only","Validate with App Store Connect without uploading").option("--package-only","Create the signed package without contacting App Store Connect").action(async(options)=>{try{const config=resolveAppleDesktopConfig(options),packagePath=await packageAppleDesktop(config,Boolean(options.skipBuild));if(!options.packageOnly)validateOrUpload(packagePath,config,Boolean(options.validateOnly));log.success(options.packageOnly?`Created signed Mac App Store package ${packagePath}`:options.validateOnly?`Validated ${packagePath} with App Store Connect`:`Uploaded ${packagePath} to App Store Connect`)}catch(error){fail(error)}})}
106
+ `,{mode:384});log.success(`${options.apply?"Applied":"Planned"} Apple provisioning: ${reportPath}`);if(!result.appRecord.exists&&result.appRecord.manualAction)log.warn(result.appRecord.manualAction)}catch(error){fail(error)}});buddy.command("desktop:apple:doctor","Validate Mac App Store tooling, credentials, certificates, and project metadata").option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--keychain <path>","Look for the signing identities in this keychain file only (or APPLE_KEYCHAIN)").action((options)=>{try{const config=resolveAppleDesktopConfig(options),errors=validateAppleDesktopConfig(config,!0);if(!signingIdentityExists(config.appSigningIdentity,config.keychain))errors.push(`App signing identity is not installed: ${config.appSigningIdentity}`);if(!signingIdentityExists(config.installerSigningIdentity,config.keychain))errors.push(`Installer signing identity is not installed: ${config.installerSigningIdentity}`);if(!provisioningProfileMatches(config))errors.push(`Provisioning profile does not match ${config.teamId}.${config.bundleId}`);if(errors.length)throw Error(errors.join(`
107
+ `));log.success(`Mac App Store prerequisites are ready for ${config.bundleId}`)}catch(error){fail(error)}});buddy.command("desktop:apple:init","Create a GitHub Actions caller for the reusable Stacks Mac App Store workflow").option("--force","Replace an existing workflow").action((options)=>{try{const workflowPath=projectPath(".github/workflows/apple-app-store.yml");if(existsSync(workflowPath)&&!options.force)throw Error(`${workflowPath} already exists. Use --force to replace it.`);mkdirSync(resolve(workflowPath,".."),{recursive:!0});writeFileSync(workflowPath,renderAppleWorkflowCaller());log.success(`Created ${workflowPath}`)}catch(error){fail(error)}});const addSharedOptions=(commandBuilder)=>commandBuilder.option("--app-name <name>","Mac App Store display name").option("--bundle-id <id>","Reverse-DNS bundle identifier").option("--team-id <id>","Apple Developer team ID").option("--app-version <version>","Marketing version").option("--build-number <number>","Unique App Store build number").option("--minimum-macos <version>","Minimum supported macOS version").option("--category <category>","LSApplicationCategoryType value").option("--app-signing-identity <identity>","Mac App Distribution signing identity").option("--installer-signing-identity <identity>","Mac Installer Distribution signing identity").option("--provisioning-profile <path>","Mac App Store provisioning profile").option("--icon <path>","Optional .icns app icon").option("--skip-build","Package existing storage/framework/desktop-dist artifacts").option("--universal","Ship one arm64 + x86_64 binary, merged with lipo").option("--craft-arm64 <path>","Thin arm64 Craft runtime for --universal (or CRAFT_BIN_ARM64)").option("--craft-x64 <path>","Thin x86_64 Craft runtime for --universal (or CRAFT_BIN_X64)").option("--keychain <path>","Sign with identities from this keychain file only (or APPLE_KEYCHAIN)");addSharedOptions(buddy.command("desktop:apple:package","Build, sandbox, sign, and package a Mac App Store desktop app")).action(async(options)=>{try{const packagePath=await packageAppleDesktop(resolveAppleDesktopConfig(options),Boolean(options.skipBuild));log.success(`Created signed Mac App Store package ${packagePath}`)}catch(error){fail(error)}});addSharedOptions(buddy.command("desktop:apple:publish","Build and validate or upload a signed Mac App Store package")).option("--api-key-id <id>","App Store Connect API key ID").option("--api-issuer-id <id>","App Store Connect API issuer ID").option("--api-key-path <path>","App Store Connect AuthKey .p8 file").option("--validate-only","Validate with App Store Connect without uploading").option("--package-only","Create the signed package without contacting App Store Connect").action(async(options)=>{try{const config=resolveAppleDesktopConfig(options),packagePath=await packageAppleDesktop(config,Boolean(options.skipBuild));if(!options.packageOnly)validateOrUpload(packagePath,config,Boolean(options.validateOnly));log.success(options.packageOnly?`Created signed Mac App Store package ${packagePath}`:options.validateOnly?`Validated ${packagePath} with App Store Connect`:`Uploaded ${packagePath} to App Store Connect`)}catch(error){fail(error)}})}
@@ -0,0 +1,2 @@
1
+ import type { CLI } from '@stacksjs/types';
2
+ export declare function gdpr(buddy: CLI): void;
@@ -0,0 +1,11 @@
1
+ import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{dirname,resolve}from"node:path";import process from"node:process";import{confirm,log}from"@stacksjs/cli";import{hasTTY,isCI}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";const DEFAULT_REGISTER="database/processing-register";function printChanges(changes,dryRun){if(!changes.length){process.stdout.write(` Nothing declared for this request.
2
+ `);return}const verb=dryRun?"would change":"changed",width=Math.max(...changes.map((change)=>change.model.length));for(const change of changes){const fields=change.fields.length?` (${change.fields.join(", ")})`:"";process.stdout.write(` ${change.model.padEnd(width)} ${change.action.padEnd(9)} ${String(change.matched).padStart(5)} matched ${String(change.changed).padStart(5)} ${verb}${fields}
3
+ `)}}async function fail(message){await log.error(message);await log.flush();process.exit(ExitCode.FatalError)}function errorMessage(error){return error instanceof Error?error.message:String(error)}function registerPath(format,out){return resolve(process.cwd(),out||`${DEFAULT_REGISTER}.${format==="json"?"json":"md"}`)}async function renderRegister(format){const{buildProcessingRegister,loadGdprModels,renderProcessingRegister,resolveGdprPlan}=await import("@stacksjs/orm"),plan=resolveGdprPlan(await loadGdprModels());if(plan.problems.length)await fail(`GDPR declarations cannot be honoured:
4
+ ${plan.problems.map((p)=>` - ${p.model}: ${p.message}`).join(`
5
+ `)}`);return renderProcessingRegister(buildProcessingRegister(plan),format==="json"?"json":"markdown")}export function gdpr(buddy){buddy.command("gdpr:export <subject>","Export a data subject's personal data as JSON (user id, email or uuid)").option("--out <file>","Write the export to this file instead of stdout").example("buddy gdpr:export ada@example.com --out ada.json").action(async(subject,options)=>{const{exportSubjectData}=await import("@stacksjs/orm");let result;try{result=await exportSubjectData(subject,{actor:"cli"})}catch(error){return fail(errorMessage(error))}const json=`${JSON.stringify(result,null,2)}
6
+ `;if(options.out){const file=resolve(process.cwd(),options.out);mkdirSync(dirname(file),{recursive:!0});writeFileSync(file,json,{mode:384});log.success(`Exported ${Object.keys(result.data).length} model(s) for subject ${String(result.subject.id)} to ${file}`)}else process.stdout.write(json);await log.flush();process.exit(ExitCode.Success)});buddy.command("gdpr:erase <subject>","Erase a data subject: delete or anonymize their rows per each model's declaration").option("--dry-run","Print exactly what would change, and change nothing",{default:!1}).option("-y, --yes","Skip the confirmation prompt",{default:!1}).example("buddy gdpr:erase ada@example.com --dry-run").example("buddy gdpr:erase 42 --yes").action(async(subject,options)=>{const{eraseSubject}=await import("@stacksjs/orm");let preview;try{preview=await eraseSubject(subject,{dryRun:!0})}catch(error){return fail(errorMessage(error))}process.stdout.write(`
7
+ Erasure of subject ${String(preview.subject.id)}:
8
+ `);printChanges(preview.changes,!0);if(preview.skipped.length)process.stdout.write(` Not in this database: ${preview.skipped.join(", ")}
9
+ `);process.stdout.write(`
10
+ `);if(options.dryRun){log.info("Dry run: nothing was changed.");await log.flush();process.exit(ExitCode.Success)}if(!options.yes){if(isCI||!hasTTY)return fail("Refusing to erase without confirmation in a non-interactive environment. Re-run with --yes.");await log.flush();if(!await confirm({message:"Erase this subject? This cannot be undone.",initial:!1})){log.info("Cancelled. Nothing was changed.");await log.flush();process.exit(ExitCode.Success)}}let result;try{result=await eraseSubject(subject,{actor:"cli"})}catch(error){return fail(errorMessage(error))}printChanges(result.changes,!1);log.success(`Erased subject ${String(result.subject.id)} and recorded it in gdpr_requests.`);log.info(result.credentialsRevoked?"Their API tokens are revoked and their sessions destroyed.":"Credentials were not revoked: @stacksjs/auth is not available, or the subject key is not numeric.");await log.flush();process.exit(ExitCode.Success)});buddy.command("gdpr:prune","Apply every model's retention policy (the daily PruneRetainedDataJob does the same)").option("--dry-run","Print what would be pruned, and change nothing",{default:!1}).action(async(options)=>{const{pruneRetainedData}=await import("@stacksjs/orm");let result;try{result=await pruneRetainedData({dryRun:options.dryRun===!0,actor:"cli"})}catch(error){return fail(errorMessage(error))}if(!result.changes.length&&!result.skipped.length)log.info("No model declares a retention policy.");else{printChanges(result.changes,result.dryRun);if(result.skipped.length)process.stdout.write(` Not in this database: ${result.skipped.join(", ")}
11
+ `);log.info(result.dryRun?"Dry run: nothing was changed.":"Retention applied.")}await log.flush();process.exit(ExitCode.Success)});buddy.command("gdpr:register","Generate the processing register from the model declarations").option("--format <format>","markdown or json",{default:"markdown"}).option("--out <file>",`Where to write it. Defaults to ${DEFAULT_REGISTER}.md (or .json)`).option("--stdout","Print it instead of writing a file",{default:!1}).action(async(options)=>{const format=options.format==="json"?"json":"markdown",rendered=await renderRegister(format);if(options.stdout){process.stdout.write(rendered);process.exit(ExitCode.Success)}const file=registerPath(format,options.out);mkdirSync(dirname(file),{recursive:!0});writeFileSync(file,rendered);log.success(`Wrote ${file}`);await log.flush();process.exit(ExitCode.Success)});buddy.command("gdpr:register:check","Verify the committed processing register matches the model declarations").option("--format <format>","markdown or json",{default:"markdown"}).option("--out <file>",`The register to check. Defaults to ${DEFAULT_REGISTER}.md (or .json)`).action(async(options)=>{const format=options.format==="json"?"json":"markdown",file=registerPath(format,options.out);if(!existsSync(file))return fail(`${file} does not exist. Run \`buddy gdpr:register\` and commit it.`);const rendered=await renderRegister(format);if(readFileSync(file,"utf8")!==rendered)return fail(`${file} is out of date with the model declarations. Run \`buddy gdpr:register\` and commit the result.`);log.success(`${file} is current.`);await log.flush();process.exit(ExitCode.Success)})}
@@ -25,6 +25,7 @@ export * from './email';
25
25
  export * from './env';
26
26
  export * from './features';
27
27
  export * from './fresh';
28
+ export * from './gdpr';
28
29
  export * from './generate';
29
30
  export * from './http';
30
31
  export * from './install';
@@ -1 +1 @@
1
- export*from"./about";export*from"./auth";export*from"./build";export*from"./cd";export*from"./changelog";export*from"./clean";export*from"./cloud";export*from"./comments";export*from"./commerce-import";export*from"./commit";export*from"./completion";export*from"./config-migrate";export*from"./configure";export*from"./create";export*from"./db";export*from"./storage-backup";export*from"./deploy";export*from"./deploy-preview";export*from"./dev";export*from"./dns";export*from"./docs";export*from"./doctor";export*from"./domains";export*from"./email";export*from"./env";export*from"./features";export*from"./fresh";export*from"./generate";export*from"./http";export*from"./install";export*from"./key";export*from"./libs";export*from"./lint";export*from"./list";export*from"./mail";export*from"./make";export*from"./migrate";export*from"./migrate-project";export*from"./outdated";export*from"./phone";export*from"./ports";export*from"./server";export*from"./link";export*from"./user";export*from"./prepublish";export*from"./projects";export*from"./publish";export*from"./queue";export*from"./release";export*from"./route";export*from"./saas";export*from"./schedule";export*from"./search";export*from"./seed";export*from"./serve";export*from"./setup";export*from"./sms";export*from"./telemetry";export*from"./test";export*from"./tinker";export*from"./types";export*from"./upgrade";export*from"./version";
1
+ export*from"./about";export*from"./auth";export*from"./build";export*from"./cd";export*from"./changelog";export*from"./clean";export*from"./cloud";export*from"./comments";export*from"./commerce-import";export*from"./commit";export*from"./completion";export*from"./config-migrate";export*from"./configure";export*from"./create";export*from"./db";export*from"./storage-backup";export*from"./deploy";export*from"./deploy-preview";export*from"./dev";export*from"./dns";export*from"./docs";export*from"./doctor";export*from"./domains";export*from"./email";export*from"./env";export*from"./features";export*from"./fresh";export*from"./gdpr";export*from"./generate";export*from"./http";export*from"./install";export*from"./key";export*from"./libs";export*from"./lint";export*from"./list";export*from"./mail";export*from"./make";export*from"./migrate";export*from"./migrate-project";export*from"./outdated";export*from"./phone";export*from"./ports";export*from"./server";export*from"./link";export*from"./user";export*from"./prepublish";export*from"./projects";export*from"./publish";export*from"./queue";export*from"./release";export*from"./route";export*from"./saas";export*from"./schedule";export*from"./search";export*from"./seed";export*from"./serve";export*from"./setup";export*from"./sms";export*from"./telemetry";export*from"./test";export*from"./tinker";export*from"./types";export*from"./upgrade";export*from"./version";
@@ -1,4 +1,4 @@
1
- import{closeSync,existsSync,mkdirSync,openSync,readdirSync,readFileSync,rmSync}from"node:fs";import{relative}from"node:path";import process from"node:process";import{confirm,intro,log,onUnknownSubcommand,outro,text}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{hasTTY,isCI}from"@stacksjs/env";import{appPath,frameworkPath,frameworkRuntimePath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{preflightDatabase}from"../database-preflight";import{DDL_CONSTRAINT_OVERRIDE_ENV,DIALECT_OVERRIDE_ENV,auditDdlConstraints,auditMigrationCorpus,dialectCapabilities,formatDdlConstraintError,formatMigrationDialectError,relativeMigrationDirectory,resolveMigrationDirectory,stripSqlNoise}from"@stacksjs/database";import{resultFailed}from"../result";let _runAction;async function runAction(...args){if(!_runAction)_runAction=(await import("@stacksjs/actions")).runAction;return _runAction(...args)}function acquireMigrationLock(){const lockDir=frameworkRuntimePath(),lockFile=`${lockDir}/migrations.lock`;try{if(!existsSync(lockDir))mkdirSync(lockDir,{recursive:!0});const fd=openSync(lockFile,"wx");try{closeSync(fd)}catch{}return{acquired:!0,release:()=>{try{rmSync(lockFile,{force:!0})}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}async function ensureDatabaseOrExit(){try{const{ensureDatabaseReady}=await import("@stacksjs/database");await ensureDatabaseReady()}catch(error){log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}}function readMigrateMarker(){const file=frameworkRuntimePath("last-migrate-result.json");if(!existsSync(file))return null;try{const raw=readFileSync(file,"utf8"),parsed=JSON.parse(raw),n=typeof parsed.appliedCount==="number"?parsed.appliedCount:null;if(n===null||!Number.isFinite(n))return null;return{appliedCount:Math.max(0,Math.floor(n))}}catch{return null}finally{try{rmSync(file,{force:!0})}catch{}}}function countModelFiles(dir){if(!existsSync(dir))return 0;let count=0;const entries=readdirSync(dir,{withFileTypes:!0});for(const entry of entries)if(entry.isDirectory())count+=countModelFiles(`${dir}/${entry.name}`);else if(entry.name.endsWith(".ts")&&!entry.name.startsWith(".")&&!entry.name.startsWith("index"))count++;return count}function validateModelsExist(){const userModelsPath=appPath("Models"),defaultModelsPath=frameworkPath("defaults/app/Models"),userModelCount=countModelFiles(userModelsPath),defaultModelCount=countModelFiles(defaultModelsPath);if(userModelCount===0&&defaultModelCount===0)return{valid:!1,error:"No models found. Please create models in app/Models or ensure framework defaults exist."};return{valid:!0}}export function validateMigrationDialect(cwd=process.cwd(),options={}){const driver=String(options.driver||process.env.DB_CONNECTION||"sqlite").toLowerCase(),dir=resolveMigrationDirectory(driver,{cwd}),relativeDir=relativeMigrationDirectory(dir,cwd);if(process.env[DIALECT_OVERRIDE_ENV]!=="1"){const caps=dialectCapabilities(driver),target=caps.wire==="mysql"?"mysql":caps.wire==="postgres"?"postgres":"sqlite";if(driver==="sqlite"||driver==="postgres"||caps.wire==="mysql"){const audit=auditMigrationCorpus({dir,target});if(!audit.empty&&audit.incompatible.length>0)return{valid:!1,error:formatMigrationDialectError(audit,target,relativeDir)}}}if(process.env[DDL_CONSTRAINT_OVERRIDE_ENV]!=="1"){const constraints=auditDdlConstraints({dir,dialect:driver});if(!constraints.empty&&constraints.violations.length>0)return{valid:!1,error:formatDdlConstraintError(constraints,driver,relativeDir)}}return{valid:!0}}async function reportSchemaDrift(){try{const{auditSchemaDrift,formatSchemaDrift}=await import("@stacksjs/database"),drift=await auditSchemaDrift();if(drift.skipped||drift.clean)return!0;log.warn(await formatSchemaDrift(drift));return!1}catch(err){log.debug(`[migrate] schema drift check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportIgnoredMigrations(){try{const{findIgnoredMigrations,formatIgnoredMigrations}=await import("@stacksjs/database"),ignored=findIgnoredMigrations();if(!ignored.length)return!0;log.warn(formatIgnoredMigrations(ignored));return!1}catch(err){log.debug(`[migrate] ignored-migration check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}function strictMode(options){return options.strict===!0||process.env.STACKS_MIGRATE_STRICT==="1"}async function reportMissingForeignKeys(){try{const{auditForeignKeys}=await import("@stacksjs/database"),result=await auditForeignKeys();if(result.absentTable.length>0)log.debug(`[migrate] ${result.absentTable.length} declared foreign key(s) belong to tables that are not in this database (${[...new Set(result.absentTable.map((fk)=>fk.fromTable))].join(", ")}); not reported as missing.`);if(result.missing.length===0)return;const sample=result.missing.slice(0,5).map((fk)=>` \u2022 ${fk.fromTable}.${fk.fromColumn} \u2192 ${fk.toTable}.${fk.toColumn} (${fk.model})`).join(`
1
+ import{closeSync,existsSync,mkdirSync,openSync,readdirSync,readFileSync,rmSync}from"node:fs";import{relative}from"node:path";import process from"node:process";import{confirm,intro,log,onUnknownSubcommand,outro,text}from"@stacksjs/cli";import{Action}from"@stacksjs/enums";import{hasTTY,isCI}from"@stacksjs/env";import{appPath,frameworkPath,frameworkRuntimePath}from"@stacksjs/path";import{ExitCode}from"@stacksjs/types";import{preflightDatabase}from"../database-preflight";import{DDL_CONSTRAINT_OVERRIDE_ENV,DIALECT_OVERRIDE_ENV,auditDdlConstraints,auditMigrationCorpus,dialectCapabilities,formatDdlConstraintError,formatMigrationDialectError,isLibsqlDriver,relativeMigrationDirectory,resolveMigrationDirectory,stripSqlNoise}from"@stacksjs/database";import{resultFailed}from"../result";let _runAction;async function runAction(...args){if(!_runAction)_runAction=(await import("@stacksjs/actions")).runAction;return _runAction(...args)}function acquireMigrationLock(){const lockDir=frameworkRuntimePath(),lockFile=`${lockDir}/migrations.lock`;try{if(!existsSync(lockDir))mkdirSync(lockDir,{recursive:!0});const fd=openSync(lockFile,"wx");try{closeSync(fd)}catch{}return{acquired:!0,release:()=>{try{rmSync(lockFile,{force:!0})}catch{}}}}catch{return{acquired:!1,release:()=>{}}}}async function ensureDatabaseOrExit(){try{const{ensureDatabaseReady}=await import("@stacksjs/database");await ensureDatabaseReady()}catch(error){log.syncError(error instanceof Error?error.message:String(error));process.exit(ExitCode.FatalError)}}function readMigrateMarker(){const file=frameworkRuntimePath("last-migrate-result.json");if(!existsSync(file))return null;try{const raw=readFileSync(file,"utf8"),parsed=JSON.parse(raw),n=typeof parsed.appliedCount==="number"?parsed.appliedCount:null;if(n===null||!Number.isFinite(n))return null;return{appliedCount:Math.max(0,Math.floor(n))}}catch{return null}finally{try{rmSync(file,{force:!0})}catch{}}}function countModelFiles(dir){if(!existsSync(dir))return 0;let count=0;const entries=readdirSync(dir,{withFileTypes:!0});for(const entry of entries)if(entry.isDirectory())count+=countModelFiles(`${dir}/${entry.name}`);else if(entry.name.endsWith(".ts")&&!entry.name.startsWith(".")&&!entry.name.startsWith("index"))count++;return count}function validateModelsExist(){const userModelsPath=appPath("Models"),defaultModelsPath=frameworkPath("defaults/app/Models"),userModelCount=countModelFiles(userModelsPath),defaultModelCount=countModelFiles(defaultModelsPath);if(userModelCount===0&&defaultModelCount===0)return{valid:!1,error:"No models found. Please create models in app/Models or ensure framework defaults exist."};return{valid:!0}}export function validateMigrationDialect(cwd=process.cwd(),options={}){const driver=String(options.driver||process.env.DB_CONNECTION||"sqlite").toLowerCase(),dir=resolveMigrationDirectory(driver,{cwd}),relativeDir=relativeMigrationDirectory(dir,cwd);if(process.env[DIALECT_OVERRIDE_ENV]!=="1"){const caps=dialectCapabilities(driver),target=caps.wire==="mysql"?"mysql":caps.wire==="postgres"?"postgres":"sqlite";if(driver==="sqlite"||driver==="postgres"||caps.wire==="mysql"||isLibsqlDriver(driver)){const audit=auditMigrationCorpus({dir,target});if(!audit.empty&&audit.incompatible.length>0)return{valid:!1,error:formatMigrationDialectError(audit,target,relativeDir)}}}if(process.env[DDL_CONSTRAINT_OVERRIDE_ENV]!=="1"){const constraints=auditDdlConstraints({dir,dialect:driver});if(!constraints.empty&&constraints.violations.length>0)return{valid:!1,error:formatDdlConstraintError(constraints,driver,relativeDir)}}return{valid:!0}}async function reportSchemaDrift(){try{const{auditSchemaDrift,formatSchemaDrift}=await import("@stacksjs/database"),drift=await auditSchemaDrift();if(drift.skipped||drift.clean)return!0;log.warn(await formatSchemaDrift(drift));return!1}catch(err){log.debug(`[migrate] schema drift check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}async function reportIgnoredMigrations(){try{const{findIgnoredMigrations,formatIgnoredMigrations}=await import("@stacksjs/database"),ignored=findIgnoredMigrations();if(!ignored.length)return!0;log.warn(formatIgnoredMigrations(ignored));return!1}catch(err){log.debug(`[migrate] ignored-migration check skipped: ${err instanceof Error?err.message:String(err)}`);return!0}}function strictMode(options){return options.strict===!0||process.env.STACKS_MIGRATE_STRICT==="1"}async function reportMissingForeignKeys(){try{const{auditForeignKeys}=await import("@stacksjs/database"),result=await auditForeignKeys();if(result.absentTable.length>0)log.debug(`[migrate] ${result.absentTable.length} declared foreign key(s) belong to tables that are not in this database (${[...new Set(result.absentTable.map((fk)=>fk.fromTable))].join(", ")}); not reported as missing.`);if(result.missing.length===0)return;const sample=result.missing.slice(0,5).map((fk)=>` \u2022 ${fk.fromTable}.${fk.fromColumn} \u2192 ${fk.toTable}.${fk.toColumn} (${fk.model})`).join(`
2
2
  `),more=result.missing.length>5?`
3
3
  + ${result.missing.length-5} more - run \`./buddy doctor\` for the full list.`:"";log.warn(`${result.missing.length} of ${result.declared.length} declared foreign keys are missing from the live schema:
4
4
  ${sample}${more}
@@ -6,7 +6,7 @@ The model-backed create migrations may be stale for this database - run \`./budd
6
6
  `),more=result.orphans.length>5?`
7
7
  + ${result.orphans.length-5} more - run \`./buddy doctor\` for the full list.`:"",first=result.orphans[0];log.warn(`${result.total} row${result.total===1?"":"s"} violate foreign keys (orphaned parents), now that SQLite enforces \`foreign_keys = ON\`:
8
8
  ${sample}${more}
9
- These were written under the old \`foreign_keys = OFF\` default (#1951). Review and clean up manually - e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}). migrate never deletes data.`)}catch(err){log.debug(`[migrate] FK orphan scan skipped: ${err instanceof Error?err.message:String(err)}`)}}function describeOp(op){switch(op.kind){case"drop_table":return`drop table "${op.table}" (all rows lost)`;case"drop_column":return`drop column "${op.table}"."${op.column}" (column data lost)`;case"modify_column":return`change type of "${op.table}"."${op.column}" (possible data loss)`;case"rebuild_table":return`rebuild table "${op.table}" (SQLite rebuilds in place; compare the SQL below against the live schema)`;case"rename_column":return`rename "${op.table}"."${op.from}" \u2192 "${op.to}"`;case"rename_table":return`rename table "${op.from}" \u2192 "${op.to}"`;default:return`${op.kind} on "${op.table}"${op.column?`."${op.column}"`:""}`}}async function missingBaselineNote(){try{const{resolveSnapshotDirectory,snapshotDirectoryIsShared}=await import("@stacksjs/database"),dir=resolveSnapshotDirectory();if(existsSync(dir)&&readdirSync(dir).some((f)=>/^model-snapshot\.\w+\.json$/.test(f)))return;return`No model snapshot in ${dir}, so this change was derived without a baseline and will be proposed again on the next run.${snapshotDirectoryIsShared()?" DB_SNAPSHOT_PATH points there; check the directory exists and is writable.":" If each deploy runs from a new directory, point DB_SNAPSHOT_PATH at a shared one that survives the release."}`}catch(error){log.debug(`[migrate] baseline check skipped: ${error instanceof Error?error.message:String(error)}`);return}}async function confirmDestructiveMigrations(opts){let operations=[];try{const{previewPendingMigrations}=await import("@stacksjs/database");operations=await previewPendingMigrations({fromDb:opts.fromDb,applyRenames:opts.applyRenames})}catch(error){log.debug(`Migration preview unavailable: ${error instanceof Error?error.message:String(error)}`);return!0}const renames=operations.filter((o)=>o.kind==="rename_column"||o.kind==="rename_table");for(const r of renames)log.info(`Detected ${describeOp(r)} - applying as a rename (data preserved). Use --no-rename to drop + add instead.`);const destructive=operations.filter((o)=>o.destructive);if(destructive.length===0)return!0;log.warn(`This migration includes ${destructive.length} potentially destructive change${destructive.length===1?"":"s"}:`);for(const op of destructive)log.warn(` \u2022 ${describeOp(op)}`);const baseline=await missingBaselineNote();if(baseline)log.warn(baseline);if(opts.force)return!0;if(isCI||!hasTTY){log.error("Refusing to apply destructive changes in a non-interactive environment. Re-run with --force to proceed.");return!1}return confirm({message:"Apply these destructive changes?",initial:!1})}export function isMigratePreview(options,argv=process.argv){return options.diff===!0||options.dryRun===!0||options.pretend===!0||argv.includes("--dry-run")||argv.includes("--pretend")}function parseGuardBool(raw){if(raw==null||raw==="")return;const v=raw.toLowerCase().trim();if(v==="1"||v==="true"||v==="yes"||v==="on")return!0;if(v==="0"||v==="false"||v==="no"||v==="off")return!1;return}function parseFreshGuard(raw){const v=raw?.toLowerCase().trim();return v==="allow"||v==="confirm"||v==="disabled"?v:void 0}async function resolveMigrationGuards(){const isProd=/^prod/i.test(process.env.APP_ENV||"local");let cfg={};try{const{awaitConfig}=await import("@stacksjs/config");cfg=(await awaitConfig()).database?.safety??{}}catch(error){log.debug(`[migrate] safety config unavailable, using defaults: ${error instanceof Error?error.message:String(error)}`)}const confirmMigrate=parseGuardBool(process.env.DB_MIGRATE_CONFIRM)??cfg.confirmMigrate??!0,migrateFresh=parseFreshGuard(process.env.DB_MIGRATE_FRESH)??cfg.migrateFresh??(isProd?"disabled":"allow");return{confirmMigrate,migrateFresh}}function currentDatabaseLabel(){if((process.env.DB_CONNECTION||"sqlite").toLowerCase()==="sqlite")return process.env.DB_DATABASE_PATH||"database/stacks.sqlite";return process.env.DB_DATABASE||"stacks"}export function migrate(buddy){const descriptions={migrate:"Migrates your database",fresh:"Drop all tables and re-run every migration (destroys all data)",project:"Target a specific project",verbose:"Enable verbose output",auth:"Also migrate auth tables (oauth_clients, oauth_access_tokens, oauth_refresh_tokens, password_resets)",force:"Apply destructive changes (drop column/table, lossy type change) without confirmation",fromDb:"Diff against the live database schema instead of the snapshot (self-heal drift)",noRename:"Treat renamed columns as drop + add instead of a data-preserving rename",noGenerate:"Apply committed migration files only; do not generate new ones from your models"};buddy.command("migrate",descriptions.migrate).alias("db:migrate").option("-d, --diff","Show the SQL that would be run",{default:!1}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("-a, --auth",descriptions.auth,{default:!0}).option("--no-auth","Skip auth/oauth table migrations").option("-f, --force",descriptions.force,{default:!1}).option("--create-database","Create the database if it does not exist, without asking",{default:!1}).option("--from-db",descriptions.fromDb,{default:!1}).option("--no-rename",descriptions.noRename).option("--no-generate",descriptions.noGenerate).option("--strict","Fail when the schema has drifted from the models or a migration is git-ignored (for CI)",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy migrate` ...",options);const perf=await intro("buddy migrate"),validation=validateModelsExist();if(!validation.valid){console.error(`
9
+ These were written under the old \`foreign_keys = OFF\` default (#1951). Review and clean up manually - e.g. DELETE FROM ${first.table} WHERE ${first.column} IS NOT NULL AND ${first.column} NOT IN (SELECT id FROM ${first.parent}). migrate never deletes data.`)}catch(err){log.debug(`[migrate] FK orphan scan skipped: ${err instanceof Error?err.message:String(err)}`)}}function describeOp(op){switch(op.kind){case"drop_table":return`drop table "${op.table}" (all rows lost)`;case"drop_column":return`drop column "${op.table}"."${op.column}" (column data lost)`;case"modify_column":return`change type of "${op.table}"."${op.column}" (possible data loss)`;case"rebuild_table":return`rebuild table "${op.table}" (SQLite rebuilds in place; compare the SQL below against the live schema)`;case"rename_column":return`rename "${op.table}"."${op.from}" \u2192 "${op.to}"`;case"rename_table":return`rename table "${op.from}" \u2192 "${op.to}"`;default:return`${op.kind} on "${op.table}"${op.column?`."${op.column}"`:""}`}}async function missingBaselineNote(){try{const{resolveSnapshotDirectory,snapshotDirectoryIsShared}=await import("@stacksjs/database"),dir=resolveSnapshotDirectory();if(existsSync(dir)&&readdirSync(dir).some((f)=>/^model-snapshot\.\w+\.json$/.test(f)))return;return`No model snapshot in ${dir}, so this change was derived without a baseline and will be proposed again on the next run.${snapshotDirectoryIsShared()?" DB_SNAPSHOT_PATH points there; check the directory exists and is writable.":" If each deploy runs from a new directory, point DB_SNAPSHOT_PATH at a shared one that survives the release."}`}catch(error){log.debug(`[migrate] baseline check skipped: ${error instanceof Error?error.message:String(error)}`);return}}async function confirmDestructiveMigrations(opts){let operations=[];try{const{previewPendingMigrations}=await import("@stacksjs/database");operations=await previewPendingMigrations({fromDb:opts.fromDb,applyRenames:opts.applyRenames})}catch(error){log.debug(`Migration preview unavailable: ${error instanceof Error?error.message:String(error)}`);return!0}const renames=operations.filter((o)=>o.kind==="rename_column"||o.kind==="rename_table");for(const r of renames)log.info(`Detected ${describeOp(r)} - applying as a rename (data preserved). Use --no-rename to drop + add instead.`);const destructive=operations.filter((o)=>o.destructive);if(destructive.length===0)return!0;log.warn(`This migration includes ${destructive.length} potentially destructive change${destructive.length===1?"":"s"}:`);for(const op of destructive)log.warn(` \u2022 ${describeOp(op)}`);const baseline=await missingBaselineNote();if(baseline)log.warn(baseline);if(opts.force)return!0;if(isCI||!hasTTY){log.error("Refusing to apply destructive changes in a non-interactive environment. Re-run with --force to proceed.");return!1}return confirm({message:"Apply these destructive changes?",initial:!1})}export function isMigratePreview(options,argv=process.argv){return options.diff===!0||options.dryRun===!0||options.pretend===!0||argv.includes("--dry-run")||argv.includes("--pretend")}function parseGuardBool(raw){if(raw==null||raw==="")return;const v=raw.toLowerCase().trim();if(v==="1"||v==="true"||v==="yes"||v==="on")return!0;if(v==="0"||v==="false"||v==="no"||v==="off")return!1;return}function parseFreshGuard(raw){const v=raw?.toLowerCase().trim();return v==="allow"||v==="confirm"||v==="disabled"?v:void 0}async function resolveMigrationGuards(){const isProd=/^prod/i.test(process.env.APP_ENV||"local");let cfg={};try{const{awaitConfig}=await import("@stacksjs/config");cfg=(await awaitConfig()).database?.safety??{}}catch(error){log.debug(`[migrate] safety config unavailable, using defaults: ${error instanceof Error?error.message:String(error)}`)}const confirmMigrate=parseGuardBool(process.env.DB_MIGRATE_CONFIRM)??cfg.confirmMigrate??!0,migrateFresh=parseFreshGuard(process.env.DB_MIGRATE_FRESH)??cfg.migrateFresh??(isProd?"disabled":"allow");return{confirmMigrate,migrateFresh}}function currentDatabaseLabel(){const driver=(process.env.DB_CONNECTION||"sqlite").toLowerCase();if(driver==="sqlite")return process.env.DB_DATABASE_PATH||"database/stacks.sqlite";if(isLibsqlDriver(driver))return process.env.TURSO_DATABASE_URL||"the Turso database";return process.env.DB_DATABASE||"stacks"}export function migrate(buddy){const descriptions={migrate:"Migrates your database",fresh:"Drop all tables and re-run every migration (destroys all data)",project:"Target a specific project",verbose:"Enable verbose output",auth:"Also migrate auth tables (oauth_clients, oauth_access_tokens, oauth_refresh_tokens, password_resets)",force:"Apply destructive changes (drop column/table, lossy type change) without confirmation",fromDb:"Diff against the live database schema instead of the snapshot (self-heal drift)",noRename:"Treat renamed columns as drop + add instead of a data-preserving rename",noGenerate:"Apply committed migration files only; do not generate new ones from your models"};buddy.command("migrate",descriptions.migrate).alias("db:migrate").option("-d, --diff","Show the SQL that would be run",{default:!1}).option("--pretend","Same as --diff (and --dry-run): preview, change nothing",{default:!1}).option("-p, --project [project]",descriptions.project,{default:!1}).option("-a, --auth",descriptions.auth,{default:!0}).option("--no-auth","Skip auth/oauth table migrations").option("-f, --force",descriptions.force,{default:!1}).option("--create-database","Create the database if it does not exist, without asking",{default:!1}).option("--from-db",descriptions.fromDb,{default:!1}).option("--no-rename",descriptions.noRename).option("--no-generate",descriptions.noGenerate).option("--strict","Fail when the schema has drifted from the models or a migration is git-ignored (for CI)",{default:!1}).option("--verbose",descriptions.verbose,{default:!1}).action(async(options)=>{log.debug("Running `buddy migrate` ...",options);const perf=await intro("buddy migrate"),validation=validateModelsExist();if(!validation.valid){console.error(`
10
10
  \u274C Error: ${validation.error}
11
11
  `);process.exit(ExitCode.FatalError)}const dialectCheck=validateMigrationDialect();if(!dialectCheck.valid){console.error(`
12
12
  \u274C Error: ${dialectCheck.error}
@@ -23,7 +23,7 @@ These were written under the old \`foreign_keys = OFF\` default (#1951). Review
23
23
  Unknown target driver "${driver}". Allowed: sqlite, mysql, vitess, postgres.
24
24
  `);await outro("Aborted.",{startTime:perf,useSeconds:!0,type:"warning"});process.exit(ExitCode.FatalError)}const current=(process.env.DB_CONNECTION||"sqlite").toLowerCase();if(current===target){console.log(`
25
25
  DB_CONNECTION is already "${target}". Nothing to switch.
26
- `);await outro("No-op.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const missingEnv=({sqlite:["DB_DATABASE"],mysql:["DB_HOST","DB_PORT","DB_USERNAME","DB_PASSWORD","DB_DATABASE"],vitess:["DB_HOST","DB_PORT","DB_USERNAME","DB_PASSWORD","DB_DATABASE"],postgres:["DB_HOST","DB_PORT","DB_USERNAME","DB_PASSWORD","DB_DATABASE"]}[target]??[]).filter((k)=>!process.env[k]);let alterCount=0,uniqueIdxCount=0;try{const migrationsDir=resolveMigrationDirectory(target);if(existsSync(migrationsDir)){const files=readdirSync(migrationsDir).filter((f)=>f.endsWith(".sql"));for(const f of files){const content=stripSqlNoise(readFileSync(`${migrationsDir}/${f}`,"utf-8")).toLowerCase();if(/alter\s+table[\s\S]*add\s+constraint/.test(content))alterCount++;if(/^\s*create\s+unique\s+index/m.test(content))uniqueIdxCount++}}}catch{}const auditTarget=target==="vitess"?"mysql":target,switchAudit=auditMigrationCorpus({dir:resolveMigrationDirectory(target),target:auditTarget}),switchBlocked=switchAudit.incompatible.length>0,blockedFiles=new Set(switchAudit.incompatible.map((m)=>m.file)).size,dialectNote=switchBlocked?`
26
+ `);await outro("No-op.",{startTime:perf,useSeconds:!0});process.exit(ExitCode.Success)}const missingEnv=({sqlite:["DB_DATABASE"],mysql:["DB_HOST","DB_PORT","DB_USERNAME","DB_PASSWORD","DB_DATABASE"],vitess:["DB_HOST","DB_PORT","DB_USERNAME","DB_PASSWORD","DB_DATABASE"],postgres:["DB_HOST","DB_PORT","DB_USERNAME","DB_PASSWORD","DB_DATABASE"],turso:["TURSO_DATABASE_URL"]}[target]??[]).filter((k)=>!process.env[k]);let alterCount=0,uniqueIdxCount=0;try{const migrationsDir=resolveMigrationDirectory(target);if(existsSync(migrationsDir)){const files=readdirSync(migrationsDir).filter((f)=>f.endsWith(".sql"));for(const f of files){const content=stripSqlNoise(readFileSync(`${migrationsDir}/${f}`,"utf-8")).toLowerCase();if(/alter\s+table[\s\S]*add\s+constraint/.test(content))alterCount++;if(/^\s*create\s+unique\s+index/m.test(content))uniqueIdxCount++}}}catch{}const auditTarget=target==="vitess"?"mysql":target,switchAudit=auditMigrationCorpus({dir:resolveMigrationDirectory(target),target:auditTarget}),switchBlocked=switchAudit.incompatible.length>0,blockedFiles=new Set(switchAudit.incompatible.map((m)=>m.file)).size,dialectNote=switchBlocked?`
27
27
  \u26D4 ${blockedFiles} of ${switchAudit.total} migration files are ${switchAudit.inferred??"another dialect"}-flavoured and will NOT run on ${target}.
28
28
  Regenerate them against ${target} before migrating, or this switch will fail on the first file.`:"",sqliteFkNote=current==="sqlite"&&alterCount>0?`
29
29
  (These were skipped on SQLite per stacksjs/stacks#1916 and survive on disk for replay.)`:"",boolNote=current==="sqlite"&&(target==="postgres"||target==="mysql"||target==="vitess")?`
@@ -1 +1 @@
1
- export async function withTimeout(work,ms){let timeoutId;const deadline=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("timeout")),ms)});try{return await Promise.race([work,deadline])}finally{if(timeoutId!==void 0)clearTimeout(timeoutId)}}const commandRegistry={about:{path:"./commands/about.js",exportName:"about"},add:{path:"./commands/add.js",exportName:"add"},"ai:context":{path:"./commands/ai-context.js",exportName:"aiContext"},auth:{path:"./commands/auth.js",exportName:"auth"},build:{path:"./commands/build.js",exportName:"build"},cd:{path:"./commands/cd.js",exportName:"cd"},changelog:{path:"./commands/changelog.js",exportName:"changelog"},clean:{path:"./commands/clean.js",exportName:"clean"},cloud:{path:"./commands/cloud.js",exportName:"cloud"},commit:{path:"./commands/commit.js",exportName:"commit"},completion:{path:"./commands/completion.js",exportName:"completion"},"config:migrate":{path:"./commands/config-migrate.js",exportName:"configMigrate"},configure:{path:"./commands/configure.js",exportName:"configure"},create:{path:"./commands/create.js",exportName:"create"},new:{path:"./commands/create.js",exportName:"create"},deploy:{path:"./commands/deploy.js",exportName:"deploy"},"deploy:rollback":{path:"./commands/deploy.js",exportName:"deploy"},dev:{path:"./commands/dev.js",exportName:"dev"},"desktop:apple:doctor":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:apple:csr":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:apple:init":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:apple:package":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:apple:provision":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:apple:publish":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:probe":{path:"./commands/desktop-probe.js",exportName:"desktopProbe"},dns:{path:"./commands/dns.js",exportName:"dns"},"dns:pull":{path:"./commands/dns.js",exportName:"dns"},"dns:diff":{path:"./commands/dns.js",exportName:"dns"},"dns:sync":{path:"./commands/dns.js",exportName:"dns"},doctor:{path:"./commands/doctor.js",exportName:"doctor"},domains:{path:"./commands/domains.js",exportName:"domains"},email:{path:"./commands/email.js",exportName:"email"},env:{path:"./commands/env.js",exportName:"env"},"extension:init":{path:"./commands/extension.js",exportName:"extension"},"extension:build":{path:"./commands/extension.js",exportName:"extension"},"extension:package":{path:"./commands/extension.js",exportName:"extension"},"extension:chrome:publish":{path:"./commands/extension.js",exportName:"extension"},"extension:chrome:status":{path:"./commands/extension.js",exportName:"extension"},"extension:firefox:publish":{path:"./commands/extension.js",exportName:"extension"},"extension:safari:init":{path:"./commands/extension.js",exportName:"extension"},"extension:safari:provision":{path:"./commands/extension.js",exportName:"extension"},"extension:safari:app":{path:"./commands/extension.js",exportName:"extension"},"extension:safari:publish":{path:"./commands/extension.js",exportName:"extension"},"dashboard:install":{path:"./commands/features.js",exportName:"features"},"dashboard:uninstall":{path:"./commands/features.js",exportName:"features"},"commerce:install":{path:"./commands/features.js",exportName:"features"},"commerce:uninstall":{path:"./commands/features.js",exportName:"features"},"commerce:import":{path:"./commands/commerce-import.js",exportName:"commerceImport"},"cms:install":{path:"./commands/features.js",exportName:"features"},"cms:uninstall":{path:"./commands/features.js",exportName:"features"},"marketing:install":{path:"./commands/features.js",exportName:"features"},"marketing:uninstall":{path:"./commands/features.js",exportName:"features"},"monitoring:install":{path:"./commands/features.js",exportName:"features"},"monitoring:uninstall":{path:"./commands/features.js",exportName:"features"},"realtime:install":{path:"./commands/features.js",exportName:"features"},"realtime:uninstall":{path:"./commands/features.js",exportName:"features"},"queue:install":{path:"./commands/features.js",exportName:"features"},"queue:uninstall":{path:"./commands/features.js",exportName:"features"},"db:backup":{path:"./commands/db.js",exportName:"db"},"db:backups":{path:"./commands/db.js",exportName:"db"},"db:restore":{path:"./commands/db.js",exportName:"db"},"storage:backup":{path:"./commands/storage-backup.js",exportName:"storageBackup"},"storage:backups":{path:"./commands/storage-backup.js",exportName:"storageBackup"},"storage:restore":{path:"./commands/storage-backup.js",exportName:"storageBackup"},fresh:{path:"./commands/fresh.js",exportName:"fresh"},generate:{path:"./commands/generate.js",exportName:"generate"},http:{path:"./commands/http.js",exportName:"http"},install:{path:"./commands/install.js",exportName:"install"},key:{path:"./commands/key.js",exportName:"key"},lint:{path:"./commands/lint.js",exportName:"lint"},format:{path:"./commands/lint.js",exportName:"lint"},"format:check":{path:"./commands/lint.js",exportName:"lint"},libs:{path:"./commands/libs.js",exportName:"libs"},libraries:{path:"./commands/libs.js",exportName:"libs"},list:{path:"./commands/list.js",exportName:"list"},mail:{path:"./commands/mail.js",exportName:"mailCommands"},"mail:preview":{path:"./commands/mail.js",exportName:"mailCommands"},maintenance:{path:"./commands/maintenance.js",exportName:"maintenance"},down:{path:"./commands/maintenance.js",exportName:"maintenance"},up:{path:"./commands/maintenance.js",exportName:"maintenance"},status:{path:"./commands/maintenance.js",exportName:"maintenance"},"coming-soon":{path:"./commands/maintenance.js",exportName:"maintenance"},"coming-soon:status":{path:"./commands/maintenance.js",exportName:"maintenance"},launch:{path:"./commands/maintenance.js",exportName:"maintenance"},make:{path:"./commands/make.js",exportName:"make"},"scaffold:crud":{path:"./commands/make.js",exportName:"make"},migrate:{path:"./commands/migrate.js",exportName:"migrate"},"migrate:fresh":{path:"./commands/migrate.js",exportName:"migrate"},"migrate:switch":{path:"./commands/migrate.js",exportName:"migrate"},"migrate:project":{path:"./commands/migrate-project.js",exportName:"migrateProject"},outdated:{path:"./commands/outdated.js",exportName:"outdated"},package:{path:"./commands/package.js",exportName:"packageCommands"},phone:{path:"./commands/phone.js",exportName:"phone"},ports:{path:"./commands/ports.js",exportName:"ports"},"server:flash":{path:"./commands/server.js",exportName:"server"},"server:first-boot":{path:"./commands/server.js",exportName:"server"},"server:doctor":{path:"./commands/server.js",exportName:"server"},"server:setup":{path:"./commands/server.js",exportName:"server"},"server:trust":{path:"./commands/server.js",exportName:"server"},"link:core":{path:"./commands/link.js",exportName:"link"},"comments:list":{path:"./commands/comments.js",exportName:"commentsCommands"},"comments:approve":{path:"./commands/comments.js",exportName:"commentsCommands"},"comments:reject":{path:"./commands/comments.js",exportName:"commentsCommands"},"comments:delete":{path:"./commands/comments.js",exportName:"commentsCommands"},"user:add":{path:"./commands/user.js",exportName:"user"},"user:list":{path:"./commands/user.js",exportName:"user"},"unlink:core":{path:"./commands/link.js",exportName:"link"},prepublish:{path:"./commands/prepublish.js",exportName:"prepublish"},projects:{path:"./commands/projects.js",exportName:"projects"},publish:{path:"./commands/publish.js",exportName:"publish"},"publish:model":{path:"./commands/publish.js",exportName:"publish"},"publish:controller":{path:"./commands/publish.js",exportName:"publish"},"publish:middleware":{path:"./commands/publish.js",exportName:"publish"},"publish:action":{path:"./commands/publish.js",exportName:"publish"},"publish:core":{path:"./commands/publish.js",exportName:"publish"},"core:status":{path:"./commands/publish.js",exportName:"publish"},queue:{path:"./commands/queue.js",exportName:"queue"},release:{path:"./commands/release.js",exportName:"release"},route:{path:"./commands/route.js",exportName:"route"},saas:{path:"./commands/saas.js",exportName:"saas"},"stripe:setup":{path:"./commands/saas.js",exportName:"saas"},schedule:{path:"./commands/schedule.js",exportName:"schedule"},search:{path:"./commands/search.js",exportName:"search"},"search-engine:update":{path:"./commands/search.js",exportName:"search"},"search-engine:settings":{path:"./commands/search.js",exportName:"search"},seed:{path:"./commands/seed.js",exportName:"seed"},"seed:roles":{path:"./commands/seed.js",exportName:"seed"},"roles:seed":{path:"./commands/seed.js",exportName:"seed"},preview:{path:"./commands/serve.js",exportName:"preview"},serve:{path:"./commands/serve.js",exportName:"serve"},"serve:api":{path:"./commands/serve.js",exportName:"serveApi"},setup:{path:"./commands/setup.js",exportName:"setup"},"setup:ai":{path:"./commands/setup.js",exportName:"setup"},"setup:ssl":{path:"./commands/setup.js",exportName:"setup"},"setup:oh-my-zsh":{path:"./commands/setup.js",exportName:"setup"},"ai:setup":{path:"./commands/setup.js",exportName:"setup"},share:{path:"./commands/share.js",exportName:"share"},"simulator:doctor":{path:"./commands/simulator.js",exportName:"simulator"},"simulator:open":{path:"./commands/simulator.js",exportName:"simulator"},stack:{path:"./commands/stacks.js",exportName:"stacks"},sms:{path:"./commands/sms.js",exportName:"sms"},telemetry:{path:"./commands/telemetry.js",exportName:"telemetryCommand"},test:{path:"./commands/test.js",exportName:"test"},tinker:{path:"./commands/tinker.js",exportName:"tinker"},types:{path:"./commands/types.js",exportName:"types"},undeploy:{path:"./commands/cloud.js",exportName:"cloud"},upgrade:{path:"./commands/upgrade.js",exportName:"upgrade"},version:{path:"./commands/version.js",exportName:"version"},"docs:buddy":{path:"./commands/docs.js",exportName:"docs"},"docs:buddy:check":{path:"./commands/docs.js",exportName:"docs"},"docs:artifacts":{path:"./commands/docs.js",exportName:"docs"},"docs:artifacts:check":{path:"./commands/docs.js",exportName:"docs"},"docs:links":{path:"./commands/docs.js",exportName:"docs"},"docs:links:check":{path:"./commands/docs.js",exportName:"docs"}},commandGroups={minimal:["version","help"],development:["dev","build","test","lint"],database:["migrate","seed","fresh"],scaffolding:["make","generate"],deployment:["deploy","release","cloud","server"],info:["about","doctor","list"]},loadedRegistrars=new WeakMap;function loaderKey(loader){return`${loader.path}#${loader.exportName}`}export function markLoaded(buddy,commandName){const loader=commandRegistry[commandName];if(!loader)return;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}set.add(loaderKey(loader))}export async function loadCommand(commandName,buddy){const loader=commandRegistry[commandName];if(!loader)return!1;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}const key=loaderKey(loader);if(set.has(key))return!0;set.add(key);try{const commandFunction=(await import(loader.path))[loader.exportName];if(typeof commandFunction==="function"){commandFunction(buddy);return!0}else return!1}catch{return!1}}export async function loadCommands(commandNames,buddy){const seen=new Set,unique=[];for(const name of commandNames){const loader=commandRegistry[name],key=loader?`${loader.path}#${loader.exportName}`:`name:${name}`;if(seen.has(key))continue;seen.add(key);unique.push(name)}await Promise.all(unique.map(async(name)=>{try{await withTimeout(loadCommand(name,buddy),5000)}catch{}}))}export async function loadCommandGroup(groupName,buddy){const commands=commandGroups[groupName];if(commands)await loadCommands(commands,buddy)}export async function loadAllCommands(buddy){const allCommands=Object.keys(commandRegistry);await loadCommands(allCommands,buddy)}export function getCommandNames(){return Object.keys(commandRegistry)}export function getCommandsToLoad(args){const requestedCommand=args[0],isVersionFlag=requestedCommand==="--version"||requestedCommand==="-v",isHelpFlag=requestedCommand==="--help"||requestedCommand==="-h",isHelpWord=requestedCommand==="help";if(isVersionFlag)return["version"];if(!requestedCommand||isHelpFlag||isHelpWord)return Object.keys(commandRegistry);const baseCommand=requestedCommand.split(":")[0];if(baseCommand==="list")return["list",...Object.keys(commandRegistry).filter((k)=>k!=="list")];if(commandRegistry[requestedCommand])return[requestedCommand];if(commandRegistry[baseCommand])return[baseCommand];return Object.keys(commandRegistry)}
1
+ export async function withTimeout(work,ms){let timeoutId;const deadline=new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("timeout")),ms)});try{return await Promise.race([work,deadline])}finally{if(timeoutId!==void 0)clearTimeout(timeoutId)}}const commandRegistry={about:{path:"./commands/about.js",exportName:"about"},add:{path:"./commands/add.js",exportName:"add"},"ai:context":{path:"./commands/ai-context.js",exportName:"aiContext"},auth:{path:"./commands/auth.js",exportName:"auth"},build:{path:"./commands/build.js",exportName:"build"},cd:{path:"./commands/cd.js",exportName:"cd"},changelog:{path:"./commands/changelog.js",exportName:"changelog"},clean:{path:"./commands/clean.js",exportName:"clean"},cloud:{path:"./commands/cloud.js",exportName:"cloud"},commit:{path:"./commands/commit.js",exportName:"commit"},completion:{path:"./commands/completion.js",exportName:"completion"},"config:migrate":{path:"./commands/config-migrate.js",exportName:"configMigrate"},configure:{path:"./commands/configure.js",exportName:"configure"},create:{path:"./commands/create.js",exportName:"create"},new:{path:"./commands/create.js",exportName:"create"},deploy:{path:"./commands/deploy.js",exportName:"deploy"},"deploy:rollback":{path:"./commands/deploy.js",exportName:"deploy"},dev:{path:"./commands/dev.js",exportName:"dev"},"desktop:apple:doctor":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:apple:csr":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:apple:init":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:apple:package":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:apple:provision":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:apple:publish":{path:"./commands/desktop-apple.js",exportName:"desktopApple"},"desktop:probe":{path:"./commands/desktop-probe.js",exportName:"desktopProbe"},dns:{path:"./commands/dns.js",exportName:"dns"},"dns:pull":{path:"./commands/dns.js",exportName:"dns"},"dns:diff":{path:"./commands/dns.js",exportName:"dns"},"dns:sync":{path:"./commands/dns.js",exportName:"dns"},doctor:{path:"./commands/doctor.js",exportName:"doctor"},domains:{path:"./commands/domains.js",exportName:"domains"},email:{path:"./commands/email.js",exportName:"email"},env:{path:"./commands/env.js",exportName:"env"},"extension:init":{path:"./commands/extension.js",exportName:"extension"},"extension:build":{path:"./commands/extension.js",exportName:"extension"},"extension:package":{path:"./commands/extension.js",exportName:"extension"},"extension:chrome:publish":{path:"./commands/extension.js",exportName:"extension"},"extension:chrome:status":{path:"./commands/extension.js",exportName:"extension"},"extension:firefox:publish":{path:"./commands/extension.js",exportName:"extension"},"extension:safari:init":{path:"./commands/extension.js",exportName:"extension"},"extension:safari:provision":{path:"./commands/extension.js",exportName:"extension"},"extension:safari:app":{path:"./commands/extension.js",exportName:"extension"},"extension:safari:publish":{path:"./commands/extension.js",exportName:"extension"},"dashboard:install":{path:"./commands/features.js",exportName:"features"},"dashboard:uninstall":{path:"./commands/features.js",exportName:"features"},"commerce:install":{path:"./commands/features.js",exportName:"features"},"commerce:uninstall":{path:"./commands/features.js",exportName:"features"},"commerce:import":{path:"./commands/commerce-import.js",exportName:"commerceImport"},"cms:install":{path:"./commands/features.js",exportName:"features"},"cms:uninstall":{path:"./commands/features.js",exportName:"features"},"marketing:install":{path:"./commands/features.js",exportName:"features"},"marketing:uninstall":{path:"./commands/features.js",exportName:"features"},"monitoring:install":{path:"./commands/features.js",exportName:"features"},"monitoring:uninstall":{path:"./commands/features.js",exportName:"features"},"realtime:install":{path:"./commands/features.js",exportName:"features"},"realtime:uninstall":{path:"./commands/features.js",exportName:"features"},"queue:install":{path:"./commands/features.js",exportName:"features"},"queue:uninstall":{path:"./commands/features.js",exportName:"features"},"db:backup":{path:"./commands/db.js",exportName:"db"},"db:backups":{path:"./commands/db.js",exportName:"db"},"db:restore":{path:"./commands/db.js",exportName:"db"},"storage:backup":{path:"./commands/storage-backup.js",exportName:"storageBackup"},"storage:backups":{path:"./commands/storage-backup.js",exportName:"storageBackup"},"storage:restore":{path:"./commands/storage-backup.js",exportName:"storageBackup"},fresh:{path:"./commands/fresh.js",exportName:"fresh"},generate:{path:"./commands/generate.js",exportName:"generate"},"gdpr:export":{path:"./commands/gdpr.js",exportName:"gdpr"},"gdpr:erase":{path:"./commands/gdpr.js",exportName:"gdpr"},"gdpr:prune":{path:"./commands/gdpr.js",exportName:"gdpr"},"gdpr:register":{path:"./commands/gdpr.js",exportName:"gdpr"},"gdpr:register:check":{path:"./commands/gdpr.js",exportName:"gdpr"},http:{path:"./commands/http.js",exportName:"http"},install:{path:"./commands/install.js",exportName:"install"},key:{path:"./commands/key.js",exportName:"key"},lint:{path:"./commands/lint.js",exportName:"lint"},format:{path:"./commands/lint.js",exportName:"lint"},"format:check":{path:"./commands/lint.js",exportName:"lint"},libs:{path:"./commands/libs.js",exportName:"libs"},libraries:{path:"./commands/libs.js",exportName:"libs"},list:{path:"./commands/list.js",exportName:"list"},mail:{path:"./commands/mail.js",exportName:"mailCommands"},"mail:preview":{path:"./commands/mail.js",exportName:"mailCommands"},maintenance:{path:"./commands/maintenance.js",exportName:"maintenance"},down:{path:"./commands/maintenance.js",exportName:"maintenance"},up:{path:"./commands/maintenance.js",exportName:"maintenance"},status:{path:"./commands/maintenance.js",exportName:"maintenance"},"coming-soon":{path:"./commands/maintenance.js",exportName:"maintenance"},"coming-soon:status":{path:"./commands/maintenance.js",exportName:"maintenance"},launch:{path:"./commands/maintenance.js",exportName:"maintenance"},make:{path:"./commands/make.js",exportName:"make"},"scaffold:crud":{path:"./commands/make.js",exportName:"make"},migrate:{path:"./commands/migrate.js",exportName:"migrate"},"migrate:fresh":{path:"./commands/migrate.js",exportName:"migrate"},"migrate:switch":{path:"./commands/migrate.js",exportName:"migrate"},"migrate:project":{path:"./commands/migrate-project.js",exportName:"migrateProject"},outdated:{path:"./commands/outdated.js",exportName:"outdated"},package:{path:"./commands/package.js",exportName:"packageCommands"},phone:{path:"./commands/phone.js",exportName:"phone"},ports:{path:"./commands/ports.js",exportName:"ports"},"server:flash":{path:"./commands/server.js",exportName:"server"},"server:first-boot":{path:"./commands/server.js",exportName:"server"},"server:doctor":{path:"./commands/server.js",exportName:"server"},"server:setup":{path:"./commands/server.js",exportName:"server"},"server:trust":{path:"./commands/server.js",exportName:"server"},"link:core":{path:"./commands/link.js",exportName:"link"},"comments:list":{path:"./commands/comments.js",exportName:"commentsCommands"},"comments:approve":{path:"./commands/comments.js",exportName:"commentsCommands"},"comments:reject":{path:"./commands/comments.js",exportName:"commentsCommands"},"comments:delete":{path:"./commands/comments.js",exportName:"commentsCommands"},"user:add":{path:"./commands/user.js",exportName:"user"},"user:list":{path:"./commands/user.js",exportName:"user"},"unlink:core":{path:"./commands/link.js",exportName:"link"},prepublish:{path:"./commands/prepublish.js",exportName:"prepublish"},projects:{path:"./commands/projects.js",exportName:"projects"},publish:{path:"./commands/publish.js",exportName:"publish"},"publish:model":{path:"./commands/publish.js",exportName:"publish"},"publish:controller":{path:"./commands/publish.js",exportName:"publish"},"publish:middleware":{path:"./commands/publish.js",exportName:"publish"},"publish:action":{path:"./commands/publish.js",exportName:"publish"},"publish:core":{path:"./commands/publish.js",exportName:"publish"},"core:status":{path:"./commands/publish.js",exportName:"publish"},queue:{path:"./commands/queue.js",exportName:"queue"},release:{path:"./commands/release.js",exportName:"release"},route:{path:"./commands/route.js",exportName:"route"},saas:{path:"./commands/saas.js",exportName:"saas"},"stripe:setup":{path:"./commands/saas.js",exportName:"saas"},schedule:{path:"./commands/schedule.js",exportName:"schedule"},search:{path:"./commands/search.js",exportName:"search"},"search-engine:update":{path:"./commands/search.js",exportName:"search"},"search-engine:settings":{path:"./commands/search.js",exportName:"search"},seed:{path:"./commands/seed.js",exportName:"seed"},"seed:roles":{path:"./commands/seed.js",exportName:"seed"},"roles:seed":{path:"./commands/seed.js",exportName:"seed"},preview:{path:"./commands/serve.js",exportName:"preview"},serve:{path:"./commands/serve.js",exportName:"serve"},"serve:api":{path:"./commands/serve.js",exportName:"serveApi"},setup:{path:"./commands/setup.js",exportName:"setup"},"setup:ai":{path:"./commands/setup.js",exportName:"setup"},"setup:ssl":{path:"./commands/setup.js",exportName:"setup"},"setup:oh-my-zsh":{path:"./commands/setup.js",exportName:"setup"},"ai:setup":{path:"./commands/setup.js",exportName:"setup"},share:{path:"./commands/share.js",exportName:"share"},"simulator:doctor":{path:"./commands/simulator.js",exportName:"simulator"},"simulator:open":{path:"./commands/simulator.js",exportName:"simulator"},stack:{path:"./commands/stacks.js",exportName:"stacks"},sms:{path:"./commands/sms.js",exportName:"sms"},telemetry:{path:"./commands/telemetry.js",exportName:"telemetryCommand"},test:{path:"./commands/test.js",exportName:"test"},tinker:{path:"./commands/tinker.js",exportName:"tinker"},types:{path:"./commands/types.js",exportName:"types"},undeploy:{path:"./commands/cloud.js",exportName:"cloud"},upgrade:{path:"./commands/upgrade.js",exportName:"upgrade"},version:{path:"./commands/version.js",exportName:"version"},"docs:buddy":{path:"./commands/docs.js",exportName:"docs"},"docs:buddy:check":{path:"./commands/docs.js",exportName:"docs"},"docs:artifacts":{path:"./commands/docs.js",exportName:"docs"},"docs:artifacts:check":{path:"./commands/docs.js",exportName:"docs"},"docs:links":{path:"./commands/docs.js",exportName:"docs"},"docs:links:check":{path:"./commands/docs.js",exportName:"docs"}},commandGroups={minimal:["version","help"],development:["dev","build","test","lint"],database:["migrate","seed","fresh"],scaffolding:["make","generate"],deployment:["deploy","release","cloud","server"],info:["about","doctor","list"]},loadedRegistrars=new WeakMap;function loaderKey(loader){return`${loader.path}#${loader.exportName}`}export function markLoaded(buddy,commandName){const loader=commandRegistry[commandName];if(!loader)return;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}set.add(loaderKey(loader))}export async function loadCommand(commandName,buddy){const loader=commandRegistry[commandName];if(!loader)return!1;let set=loadedRegistrars.get(buddy);if(!set){set=new Set;loadedRegistrars.set(buddy,set)}const key=loaderKey(loader);if(set.has(key))return!0;set.add(key);try{const commandFunction=(await import(loader.path))[loader.exportName];if(typeof commandFunction==="function"){commandFunction(buddy);return!0}else return!1}catch{return!1}}export async function loadCommands(commandNames,buddy){const seen=new Set,unique=[];for(const name of commandNames){const loader=commandRegistry[name],key=loader?`${loader.path}#${loader.exportName}`:`name:${name}`;if(seen.has(key))continue;seen.add(key);unique.push(name)}await Promise.all(unique.map(async(name)=>{try{await withTimeout(loadCommand(name,buddy),5000)}catch{}}))}export async function loadCommandGroup(groupName,buddy){const commands=commandGroups[groupName];if(commands)await loadCommands(commands,buddy)}export async function loadAllCommands(buddy){const allCommands=Object.keys(commandRegistry);await loadCommands(allCommands,buddy)}export function getCommandNames(){return Object.keys(commandRegistry)}export function getCommandsToLoad(args){const requestedCommand=args[0],isVersionFlag=requestedCommand==="--version"||requestedCommand==="-v",isHelpFlag=requestedCommand==="--help"||requestedCommand==="-h",isHelpWord=requestedCommand==="help";if(isVersionFlag)return["version"];if(!requestedCommand||isHelpFlag||isHelpWord)return Object.keys(commandRegistry);const baseCommand=requestedCommand.split(":")[0];if(baseCommand==="list")return["list",...Object.keys(commandRegistry).filter((k)=>k!=="list")];if(commandRegistry[requestedCommand])return[requestedCommand];if(commandRegistry[baseCommand])return[baseCommand];return Object.keys(commandRegistry)}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/buddy",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.41",
5
+ "version": "0.75.42",
6
6
  "description": "Meet Buddy. The Stacks runtime.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -95,71 +95,71 @@
95
95
  "prepublishOnly": "bun run build"
96
96
  },
97
97
  "dependencies": {
98
- "@stacksjs/actions": "^0.75.41",
99
- "@stacksjs/ai": "^0.75.41",
100
- "@stacksjs/alias": "^0.75.41",
101
- "@stacksjs/analytics": "^0.75.41",
102
- "@stacksjs/api": "^0.75.41",
103
- "@stacksjs/arrays": "^0.75.41",
104
- "@stacksjs/auth": "^0.75.41",
105
- "@stacksjs/browser-extension": "^0.75.41",
106
- "@stacksjs/build": "^0.75.41",
107
- "@stacksjs/cache": "^0.75.41",
108
- "@stacksjs/chat": "^0.75.41",
98
+ "@stacksjs/actions": "^0.75.42",
99
+ "@stacksjs/ai": "^0.75.42",
100
+ "@stacksjs/alias": "^0.75.42",
101
+ "@stacksjs/analytics": "^0.75.42",
102
+ "@stacksjs/api": "^0.75.42",
103
+ "@stacksjs/arrays": "^0.75.42",
104
+ "@stacksjs/auth": "^0.75.42",
105
+ "@stacksjs/browser-extension": "^0.75.42",
106
+ "@stacksjs/build": "^0.75.42",
107
+ "@stacksjs/cache": "^0.75.42",
108
+ "@stacksjs/chat": "^0.75.42",
109
109
  "@stacksjs/clapp": "^0.2.16",
110
- "@stacksjs/cli": "^0.75.41",
111
- "@stacksjs/cloud": "^0.75.41",
112
- "@stacksjs/cms": "^0.75.41",
113
- "@stacksjs/collections": "^0.75.41",
114
- "@stacksjs/commerce": "^0.75.41",
115
- "@stacksjs/config": "^0.75.41",
116
- "@stacksjs/database": "^0.75.41",
117
- "@stacksjs/desktop-build": "^0.75.41",
118
- "@stacksjs/dns": "^0.75.41",
110
+ "@stacksjs/cli": "^0.75.42",
111
+ "@stacksjs/cloud": "^0.75.42",
112
+ "@stacksjs/cms": "^0.75.42",
113
+ "@stacksjs/collections": "^0.75.42",
114
+ "@stacksjs/commerce": "^0.75.42",
115
+ "@stacksjs/config": "^0.75.42",
116
+ "@stacksjs/database": "^0.75.42",
117
+ "@stacksjs/desktop-build": "^0.75.42",
118
+ "@stacksjs/dns": "^0.75.42",
119
119
  "@stacksjs/dnsx": "^0.2.3",
120
- "@stacksjs/email": "^0.75.41",
121
- "@stacksjs/enums": "^0.75.41",
122
- "@stacksjs/env": "^0.75.41",
123
- "@stacksjs/error-handling": "^0.75.41",
124
- "@stacksjs/events": "^0.75.41",
125
- "@stacksjs/features": "^0.75.41",
126
- "@stacksjs/git": "^0.75.41",
120
+ "@stacksjs/email": "^0.75.42",
121
+ "@stacksjs/enums": "^0.75.42",
122
+ "@stacksjs/env": "^0.75.42",
123
+ "@stacksjs/error-handling": "^0.75.42",
124
+ "@stacksjs/events": "^0.75.42",
125
+ "@stacksjs/features": "^0.75.42",
126
+ "@stacksjs/git": "^0.75.42",
127
127
  "@stacksjs/gitit": "^0.2.5",
128
- "@stacksjs/health": "^0.75.41",
128
+ "@stacksjs/health": "^0.75.42",
129
129
  "@stacksjs/httx": "^0.1.10",
130
- "@stacksjs/image": "^0.75.41",
131
- "@stacksjs/lint": "^0.75.41",
132
- "@stacksjs/logging": "^0.75.41",
133
- "@stacksjs/notifications": "^0.75.41",
134
- "@stacksjs/objects": "^0.75.41",
135
- "@stacksjs/orm": "^0.75.41",
136
- "@stacksjs/path": "^0.75.41",
137
- "@stacksjs/payments": "^0.75.41",
138
- "@stacksjs/realtime": "^0.75.41",
139
- "@stacksjs/router": "^0.75.41",
130
+ "@stacksjs/image": "^0.75.42",
131
+ "@stacksjs/lint": "^0.75.42",
132
+ "@stacksjs/logging": "^0.75.42",
133
+ "@stacksjs/notifications": "^0.75.42",
134
+ "@stacksjs/objects": "^0.75.42",
135
+ "@stacksjs/orm": "^0.75.42",
136
+ "@stacksjs/path": "^0.75.42",
137
+ "@stacksjs/payments": "^0.75.42",
138
+ "@stacksjs/realtime": "^0.75.42",
139
+ "@stacksjs/router": "^0.75.42",
140
140
  "@stacksjs/rpx": "^0.11.54",
141
- "@stacksjs/scheduler": "^0.75.41",
142
- "@stacksjs/search-engine": "^0.75.41",
143
- "@stacksjs/security": "^0.75.41",
144
- "@stacksjs/server": "^0.75.41",
145
- "@stacksjs/sites": "^0.75.41",
146
- "@stacksjs/skills": "^0.75.41",
147
- "@stacksjs/storage": "^0.75.41",
148
- "@stacksjs/strings": "^0.75.41",
149
- "@stacksjs/stx": "^0.2.348",
150
- "@stacksjs/testing": "^0.75.41",
151
- "@stacksjs/tinker": "^0.75.41",
141
+ "@stacksjs/scheduler": "^0.75.42",
142
+ "@stacksjs/search-engine": "^0.75.42",
143
+ "@stacksjs/security": "^0.75.42",
144
+ "@stacksjs/server": "^0.75.42",
145
+ "@stacksjs/sites": "^0.75.42",
146
+ "@stacksjs/skills": "^0.75.42",
147
+ "@stacksjs/storage": "^0.75.42",
148
+ "@stacksjs/strings": "^0.75.42",
149
+ "@stacksjs/stx": "^0.2.350",
150
+ "@stacksjs/testing": "^0.75.42",
151
+ "@stacksjs/tinker": "^0.75.42",
152
152
  "@stacksjs/tlsx": "^0.13.19",
153
- "@stacksjs/ts-cloud": "^0.16.15",
154
- "@stacksjs/tunnel": "^0.75.41",
155
- "@stacksjs/types": "^0.75.41",
156
- "@stacksjs/ui": "^0.75.41",
157
- "@stacksjs/utils": "^0.75.41",
158
- "@stacksjs/validation": "^0.75.41",
153
+ "@stacksjs/ts-cloud": "^0.16.23",
154
+ "@stacksjs/tunnel": "^0.75.42",
155
+ "@stacksjs/types": "^0.75.42",
156
+ "@stacksjs/ui": "^0.75.42",
157
+ "@stacksjs/utils": "^0.75.42",
158
+ "@stacksjs/validation": "^0.75.42",
159
159
  "ajv": "^8.20.0",
160
160
  "ajv-formats": "^3.0.1",
161
- "bun-plugin-stx": "^0.2.348",
162
- "ts-pantry": "^0.11.35"
161
+ "bun-plugin-stx": "^0.2.350",
162
+ "ts-pantry": "^0.11.68"
163
163
  },
164
164
  "devDependencies": {
165
165
  "better-dx": "^0.2.24"