@getcortexlabs/create-mavis 0.1.0-rc.12 → 0.1.0-rc.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,7 +31,7 @@ The wizard, package-manager selection and both examples are included in RC.12.
31
31
 
32
32
  Node.js 22.16+ is required. Native projects also need the NativeScript CLI and the platform SDK. iOS requires macOS and Xcode. A shared project keeps native dependencies separate from its Web workspace so each renderer loads the correct Vue runtime.
33
33
 
34
- Templates pin **Mavis 0.1.0-rc.12** and **Jolt 0.1.0-rc.11.1**. The CLI and its generated projects use the same Mavis release. Commit the generated lockfile (both lockfiles for a shared project).
34
+ Templates pin **Mavis 0.1.0-rc.12.2** and **Jolt 0.1.0-rc.12.1**. The CLI and its generated projects use the same Mavis release. Commit the generated lockfile (both lockfiles for a shared project).
35
35
 
36
36
  pnpm requires **10.26+**. Its generated workspace files keep the mobile installation separate, use a hoisted layout for Vite deduplication, shared imports and NativeScript, and allow only the starter's required dependency build scripts. Yarn Classic and modern Yarn use `node_modules`; initial empty `yarn.lock` files mark separate projects before installation. The starter declares its dependency build scripts explicitly; other package-manager policies remain in effect. If modern Yarn reports a fresh dependency as quarantined, retry after its configured minimum package age. Do not add `apps/mobile` to the Web workspace.
37
37
 
@@ -47,4 +47,8 @@ MIT · [Mavis UI](https://github.com/getcortexlabs/mavis-ui)
47
47
 
48
48
  ## Add a host to an existing Mavis application (RC.12)
49
49
 
50
- Run `create-mavis --add-native` in a Vue + Vite/Nuxt package, or `create-mavis --add-web [--web nuxt]` in a NativeScript-Vue package. Use `--dry-run` to inspect the plan and `--screen path/to/Screen.vue` to reuse an existing screen without moving it. The command creates an isolated host under `apps`, adds root launch/install scripts and preserves existing source/configuration/lockfiles. Dependencies install only with `--install`; npm, pnpm and Yarn are supported. Conflicts and unsupported workspaces/version baselines are reported before writing. The selected screen's services, aliases and router remain application-owned; portability diagnostics are not automatic conversion. Upgrade the existing Mavis renderer to RC.12 before adding a host.
50
+ Run `create-mavis --add-native` in a Vue + Vite/Nuxt package, or `create-mavis --add-web [--web nuxt]` in a NativeScript-Vue package. Use `--dry-run` to inspect the plan and `--screen path/to/Screen.vue` to reuse an existing screen without moving it. The command creates an isolated host under `apps`, adds root launch/install scripts and preserves existing source/configuration/lockfiles. Dependencies install only with `--install`; npm, pnpm and Yarn are supported. Conflicts and unsupported workspaces/version baselines are reported before writing. The selected screen's services, aliases and router remain application-owned; portability diagnostics are not automatic conversion. Upgrade the existing Mavis renderer to RC.12.2 before adding a host.
51
+
52
+ ## Experimental macOS starter (RC.12.2)
53
+
54
+ `create-mavis first-light --target macos --yes` creates a bounded Mitosis 0.14.2 → SwiftUI and Vue/Vite starter. Run the generated `macos` script on macOS 14+ with Xcode. Four primitives and simple local state are supported; existing Vue screens and the full Mavis component catalog are not converted. Mitosis is installed only in this experimental project. See the [scope and commands](https://mavis-ui.getcortexlabs.com/guide/macos-experimental).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getcortexlabs/create-mavis",
3
- "version": "0.1.0-rc.12",
3
+ "version": "0.1.0-rc.12.2",
4
4
  "description": "Create Vue Web, Nuxt and NativeScript projects with Mavis UI.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -38,6 +38,11 @@ export async function planTarget(options, cwd = process.cwd()) {
38
38
  const packageFile = await safePath(root, 'package.json')
39
39
  const original = await readFile(packageFile, 'utf8'),
40
40
  pkg = JSON.parse(original)
41
+ const config = await optional(join(root, 'mavis.config.json'))
42
+ if (config && JSON.parse(config).authoring === 'mitosis')
43
+ throw new Error(
44
+ 'Add-target migrations do not support the experimental Mitosis macOS starter. Its Vue and SwiftUI hosts are already generated from shared/Welcome.lite.tsx.',
45
+ )
41
46
  const deps = { ...pkg.devDependencies, ...pkg.dependencies }
42
47
  const target = options.target
43
48
  if (!['mobile', 'web'].includes(target)) throw new Error('Choose --add-native or --add-web.')
package/src/cli.mjs CHANGED
@@ -22,7 +22,7 @@ const help = `Create Mavis — Vue Web, Nuxt and NativeScript
22
22
  npm create @getcortexlabs/mavis@latest
23
23
  create-mavis my-app --target both --web nuxt --package-manager pnpm --no-install
24
24
 
25
- --target mobile|web|both Default: web
25
+ --target mobile|web|both|macos Default: web; macos is experimental Mitosis + SwiftUI
26
26
  --add-native Add apps/mobile to an existing Vue/Vite or Nuxt app
27
27
  --add-web Add apps/web to an existing NativeScript-Vue app
28
28
  --screen path.vue Reuse an existing screen without moving it
@@ -39,7 +39,7 @@ const help = `Create Mavis — Vue Web, Nuxt and NativeScript
39
39
  --package-manager npm|pnpm|yarn
40
40
  Default: the invoking manager, or npm
41
41
  --framework vue Vue is currently supported
42
- --authoring vue Vue templates are currently supported
42
+ --authoring vue|mitosis Mitosis only for the experimental macos starter
43
43
  --yes, -y Use defaults without prompts (skip installation)
44
44
  --install / --no-install Install dependencies now or later
45
45
  --dry-run Show the complete file plan without writing
@@ -262,7 +262,11 @@ try {
262
262
  })
263
263
  ui.note(nextSteps(plan.preset, options.install), 'Next steps')
264
264
  ui.message(`Make it yours: ${sharedEntry(plan.preset)}`)
265
- if (plan.preset.target !== 'web')
265
+ if (plan.preset.target === 'macos')
266
+ ui.message(
267
+ 'Experimental: four starter primitives; macOS 14+ and Xcode required. See the generated README for the supported subset.',
268
+ )
269
+ else if (plan.preset.target !== 'web')
266
270
  ui.message(
267
271
  'Mobile needs the NativeScript CLI and platform SDKs. Check your setup with --doctor.',
268
272
  )
package/src/doctor.mjs CHANGED
@@ -20,6 +20,32 @@ export async function doctor(cwd = process.cwd()) {
20
20
  },
21
21
  checkPackageManager(config.packageManager ?? 'npm'),
22
22
  ]
23
+ if (config.target === 'macos') {
24
+ const result =
25
+ process.platform === 'darwin'
26
+ ? spawnSync('xcrun', ['swift', '--version'], { encoding: 'utf8', timeout: 10000 })
27
+ : null
28
+ results.push({
29
+ name: 'SwiftUI build host',
30
+ ok: result?.status === 0,
31
+ detail: result
32
+ ? (result.error?.message ?? (result.stdout || result.stderr)).trim().split('\n')[0]
33
+ : 'macOS 14+ and Xcode are required for the native app. Web remains available.',
34
+ })
35
+ const { validateSource } = await import('../templates/macos/scripts/portable.mjs')
36
+ try {
37
+ validateSource(await readFile(join(cwd, 'shared/Welcome.lite.tsx'), 'utf8'))
38
+ results.push({
39
+ name: 'Experimental source grammar',
40
+ ok: true,
41
+ detail:
42
+ 'Grammar accepted. Run generate to validate tokens and both outputs; this does not prove a native build.',
43
+ })
44
+ } catch (error) {
45
+ results.push({ name: 'Experimental source grammar', ok: false, detail: error.message })
46
+ }
47
+ return results
48
+ }
23
49
  if (config.target !== 'web') {
24
50
  const probe = (name, command, args) => {
25
51
  const result = spawnSync(command, args, { encoding: 'utf8', timeout: 10000 })
package/src/macos.mjs ADDED
@@ -0,0 +1,109 @@
1
+ import { versions as v } from './presets.mjs'
2
+ import { packageCommands } from './package-manager.mjs'
3
+
4
+ /** Opt-in build-time compiler; never installed by ordinary Vue/NativeScript starters. */
5
+ export async function macosFiles(preset, files, copyTemplate) {
6
+ const commands = packageCommands(preset.packageManager)
7
+ await copyTemplate(files, 'macos', '', {
8
+ NAME: preset.name,
9
+ APPID: preset.name.replaceAll('-', ''),
10
+ THEME: preset.theme,
11
+ APPEARANCE: preset.theme === 'midnight' ? 'dark' : 'light',
12
+ BACKGROUND: preset.theme === 'midnight' ? '#15121C' : '#FAF7FA',
13
+ })
14
+ files.set(
15
+ 'package.json',
16
+ JSON.stringify(
17
+ {
18
+ name: preset.name,
19
+ private: true,
20
+ version: '0.0.0',
21
+ type: 'module',
22
+ engines: { node: '>=22.16' },
23
+ scripts: {
24
+ generate: 'node scripts/generate.mjs',
25
+ 'dev:web': 'node scripts/generate.mjs && vite',
26
+ 'build:web': 'node scripts/generate.mjs && vite build',
27
+ 'build:macos': 'node scripts/macos.mjs build',
28
+ macos: 'node scripts/macos.mjs run',
29
+ },
30
+ dependencies: {
31
+ '@getcortexlabs/mavis-core': v.mavis,
32
+ '@getcortexlabs/mavis-web': v.mavis,
33
+ '@rafaelaugusto/jolt': v.jolt,
34
+ vue: v.vue,
35
+ },
36
+ devDependencies: {
37
+ '@builder.io/mitosis': v.mitosis,
38
+ typescript: v.typescript,
39
+ vite: v.vite,
40
+ '@vitejs/plugin-vue': v.vuePlugin,
41
+ },
42
+ ...(preset.packageManager === 'yarn'
43
+ ? { resolutions: { vue: v.vue }, dependenciesMeta: { esbuild: { built: true } } }
44
+ : {}),
45
+ },
46
+ null,
47
+ 2,
48
+ ) + '\n',
49
+ )
50
+ files.set(
51
+ 'mavis.config.json',
52
+ JSON.stringify(
53
+ { ...preset, portability: { roots: ['shared'], mode: 'mitosis-swiftui-experimental' } },
54
+ null,
55
+ 2,
56
+ ) + '\n',
57
+ )
58
+ files.set(
59
+ '.gitignore',
60
+ 'node_modules/\ndist/\nnative/.build/\n.yarn/\n.DS_Store\n*.log\n*.generated.vue\n*.generated.swift\n',
61
+ )
62
+ if (preset.packageManager === 'pnpm')
63
+ files.set(
64
+ 'pnpm-workspace.yaml',
65
+ 'packages: []\nnodeLinker: hoisted\nallowBuilds:\n esbuild: true\n',
66
+ )
67
+ if (preset.packageManager === 'yarn') {
68
+ files.set('.yarnrc.yml', 'nodeLinker: node-modules\n')
69
+ files.set('yarn.lock', '')
70
+ }
71
+ files.set(
72
+ 'README.md',
73
+ `# ${preset.name}
74
+
75
+ Experimental Mavis macOS + Web starter. **One shared source, two compiled interfaces.**
76
+ This is a small compiler experiment, not the complete Mavis SwiftUI renderer.
77
+
78
+ ## Start
79
+
80
+ \`\`\`sh
81
+ ${commands.install}
82
+ ${commands.run('macos')}
83
+ # Or open the same screen on the Web:
84
+ ${commands.run('dev:web')}
85
+ \`\`\`
86
+
87
+ The native app requires macOS 14+ and Xcode with command-line tools. It uses SwiftUI, not a WebView, NativeScript or a JavaScript runtime. Web/code generation also work on other operating systems. The generated app is unsigned for local development; signing/notarization and distribution are outside this experiment.
88
+
89
+ ## Edit once
90
+
91
+ Edit **shared/Welcome.lite.tsx**, then run \`${commands.run('generate')}\`. The build and startup commands also generate automatically. When the Web dev server is already running, run generate after editing the shared source; Vite then reloads the generated Vue file. Rebuild/reopen the native app to see edits.
92
+
93
+ Mitosis ${v.mitosis} parses the source and generates Vue and SwiftUI. The local build adapter maps four Mavis primitives and reads the selected theme tokens from mavis-core. Generated files in web/ and native/Sources/MavisDesktop/ are replaceable outputs, not sources to edit. native/Package.swift and App.swift own the Mac window. Each host has its own local state; state is not synchronized between processes.
94
+
95
+ Supported subset:
96
+ - MColumn/MRow: gap and padding spacing tokens.
97
+ - MText: one text literal or state binding, typography variant and color tone.
98
+ - MButton: text, primary/secondary variant, and onClick with one local state assignment.
99
+ - useStore: string, boolean or non-negative integer literals; actions assign same-type literals or increment an integer.
100
+
101
+ Unsupported syntax/properties fail generation with a diagnostic. Existing .vue files, all other Mavis components, Nuxt, iOS/Android output, arbitrary TypeScript, props, loops, effects, async services, navigation and persistence are not included. The general Vue portability auditor and add-target migrations are not this compiler. Run \`${commands.run('generate')}\` to check both outputs.
102
+
103
+ Web buttons use Mavis/Jolt. Native button feedback uses SwiftUI and respects Reduce Motion; **Jolt has no macOS adapter in this release**. macOS uses the selected fixed starter theme; automatic appearance switching and exact typography parity are not promised.
104
+
105
+ Build Web: \`${commands.run('build:web')}\`. Build the local Mac app without opening it: \`${commands.run('build:macos')}\`. Output: dist/${preset.name}.app. Stop the app normally from its menu or with Cmd+Q. Commit the generated ${commands.lockfile} after installation.
106
+ `,
107
+ )
108
+ return { preset, files: new Map([...files].sort(([a], [b]) => a.localeCompare(b))) }
109
+ }
@@ -304,6 +304,10 @@ async function projectConfig(root) {
304
304
  export async function checkPortability(root = process.cwd(), options = {}) {
305
305
  root = resolve(root)
306
306
  const config = await projectConfig(root)
307
+ if (config.authoring === 'mitosis')
308
+ throw new Error(
309
+ 'The Vue portability auditor does not validate SwiftUI. Run your package manager’s generate script to check the experimental Mitosis source; import migrations are not supported for this target.',
310
+ )
307
311
  const roots = options.path
308
312
  ? [options.path]
309
313
  : (config.portability?.roots ?? [
package/src/presets.mjs CHANGED
@@ -2,8 +2,9 @@ import { packageManagers } from './package-manager.mjs'
2
2
 
3
3
  /** Baseline pins; coordinated releases update Mavis after validating source templates with matching tarballs. */
4
4
  export const versions = Object.freeze({
5
- mavis: '0.1.0-rc.12',
6
- jolt: '0.1.0-rc.11.1',
5
+ mavis: '0.1.0-rc.12.2',
6
+ mitosis: '0.14.2',
7
+ jolt: '0.1.0-rc.12.1',
7
8
  vue: '3.5.44',
8
9
  nuxt: '4.6.3',
9
10
  vite: '6.4.5',
@@ -35,7 +36,7 @@ export function resolvePreset(options) {
35
36
  rendering = web === 'nuxt' ? 'ssr' : 'client',
36
37
  theme = 'mavis',
37
38
  framework = 'vue',
38
- authoring = 'vue',
39
+ authoring = target === 'macos' ? 'mitosis' : 'vue',
39
40
  example = 'welcome',
40
41
  packageManager = 'npm',
41
42
  } = options
@@ -49,12 +50,38 @@ export function resolvePreset(options) {
49
50
  throw new Error(
50
51
  'This creator currently supports Vue. Other framework adapters are tracked in Mavis #145 and #35–39.',
51
52
  )
53
+ if (target === 'macos') {
54
+ if (
55
+ authoring !== 'mitosis' ||
56
+ web !== 'vite' ||
57
+ rendering !== 'client' ||
58
+ example !== 'welcome'
59
+ )
60
+ throw new Error(
61
+ 'Experimental macOS supports Mitosis authoring, Vue + Vite and the basic welcome example only. Existing Vue screens, Nuxt and directory are not converted.',
62
+ )
63
+ if (!['mavis', 'midnight'].includes(theme)) throw new Error('Theme must be mavis or midnight.')
64
+ return Object.freeze({
65
+ schemaVersion: 1,
66
+ name,
67
+ target,
68
+ framework,
69
+ authoring,
70
+ example,
71
+ web,
72
+ rendering,
73
+ theme,
74
+ packageManager,
75
+ experimental: 'mitosis-swiftui',
76
+ versions,
77
+ })
78
+ }
52
79
  if (authoring !== 'vue')
53
80
  throw new Error(
54
81
  'Portable JSX/React-style authoring for Vue is planned in Mavis #167; use Vue templates in this version.',
55
82
  )
56
83
  if (!['mobile', 'web', 'both'].includes(target))
57
- throw new Error('Target must be mobile, web or both.')
84
+ throw new Error('Target must be mobile, web, both or macos (experimental).')
58
85
  if (!['vite', 'nuxt'].includes(web))
59
86
  throw new Error('Web host must be vite or nuxt. React/Next are not available yet.')
60
87
  if (!['mavis', 'midnight'].includes(theme)) throw new Error('Theme must be mavis or midnight.')
package/src/scaffold.mjs CHANGED
@@ -26,6 +26,10 @@ async function copyTemplate(files, source, destination, replacements) {
26
26
  export async function projectFiles(options) {
27
27
  const preset = resolvePreset(options)
28
28
  const files = new Map()
29
+ if (preset.target === 'macos') {
30
+ const { macosFiles } = await import('./macos.mjs')
31
+ return macosFiles(preset, files, copyTemplate)
32
+ }
29
33
  const shared = preset.target === 'both'
30
34
  const directory = preset.example === 'directory'
31
35
  const commands = packageCommands(preset.packageManager)
@@ -1,5 +1,11 @@
1
1
  /** Shared renderer exports, also used by the conservative import migration. */
2
2
  export const components = [
3
+ 'MTreeSelect',
4
+ 'MMasonry',
5
+ 'MHeatmap',
6
+ 'MImageCropper',
7
+ 'MScheduler',
8
+ 'MNotificationCenter',
3
9
  'MKanban',
4
10
  'MDonutChart',
5
11
  'MSparkline',
package/src/ui.mjs CHANGED
@@ -21,6 +21,15 @@ export function validateDestination(name, cwd = process.cwd()) {
21
21
  }
22
22
 
23
23
  export function projectSummary(preset, install) {
24
+ if (preset.target === 'macos')
25
+ return [
26
+ `Project ${preset.name}`,
27
+ 'Platform macOS SwiftUI + Vue/Vite · EXPERIMENTAL',
28
+ 'Authoring Mitosis · four starter primitives, limited local state',
29
+ 'Example Basic welcome · shared/Welcome.lite.tsx',
30
+ `Theme ${preset.theme}`,
31
+ `Packages ${preset.packageManager} · ${install ? 'install now' : 'install later'}`,
32
+ ].join('\n')
24
33
  const web = preset.web === 'nuxt' ? `Nuxt · ${preset.rendering.toUpperCase()}` : 'Vue + Vite'
25
34
  return [
26
35
  `Project ${preset.name}`,
@@ -32,6 +41,7 @@ export function projectSummary(preset, install) {
32
41
  }
33
42
 
34
43
  export function sharedEntry(preset) {
44
+ if (preset.target === 'macos') return 'shared/Welcome.lite.tsx'
35
45
  const directory =
36
46
  preset.target === 'both' ? 'shared' : preset.web === 'nuxt' ? 'app/shared' : 'src/shared'
37
47
  return `${directory}/${preset.example === 'directory' ? 'Directory' : 'Welcome'}.vue`
@@ -39,6 +49,14 @@ export function sharedEntry(preset) {
39
49
 
40
50
  export function nextSteps(preset, installed = false) {
41
51
  const commands = packageCommands(preset.packageManager)
52
+ if (preset.target === 'macos')
53
+ return [
54
+ `cd ${preset.name}`,
55
+ ...(!installed ? [commands.install] : []),
56
+ commands.run('macos'),
57
+ `${commands.run('dev:web')} # same source, in the browser`,
58
+ 'macOS 14+ and Xcode required for the native app.',
59
+ ].join('\n')
42
60
  return [
43
61
  `cd ${preset.name}`,
44
62
  ...(!installed ? [commands.setup(preset.target === 'both')] : []),
@@ -124,12 +142,22 @@ export async function wizard(initial, signal, io = prompts, check = checkPackage
124
142
  disabled: initial.web === 'nuxt' || ['ssr', 'ssg'].includes(initial.rendering),
125
143
  },
126
144
  { value: 'both', label: 'Web + Mobile', hint: 'One shared screen, three platforms' },
145
+ {
146
+ value: 'macos',
147
+ label: 'macOS + Web · experimental',
148
+ hint: 'Mitosis → SwiftUI and Vue · basic starter only',
149
+ disabled:
150
+ initial.web === 'nuxt' ||
151
+ ['ssr', 'ssg'].includes(initial.rendering) ||
152
+ initial.example === 'directory' ||
153
+ (initial.authoring && initial.authoring !== 'mitosis'),
154
+ },
127
155
  ],
128
156
  },
129
157
  {
130
158
  key: 'web',
131
159
  message: 'Choose your web setup',
132
- when: () => answers.target !== 'mobile',
160
+ when: () => !['mobile', 'macos'].includes(answers.target),
133
161
  options: [
134
162
  {
135
163
  value: 'vite',
@@ -156,6 +184,7 @@ export async function wizard(initial, signal, io = prompts, check = checkPackage
156
184
  },
157
185
  {
158
186
  key: 'example',
187
+ when: () => answers.target !== 'macos',
159
188
  message: 'Choose a starting example',
160
189
  fallback: 'welcome',
161
190
  options: [
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>__MAVIS_NAME__ · Mavis</title>
7
+ </head>
8
+ <body>
9
+ <main id="app"></main>
10
+ <script type="module" src="/web/main.js"></script>
11
+ </body>
12
+ </html>
@@ -0,0 +1,9 @@
1
+ // swift-tools-version: 5.9
2
+ import PackageDescription
3
+
4
+ let package = Package(
5
+ name: "MavisDesktop",
6
+ platforms: [.macOS(.v14)],
7
+ products: [.executable(name: "MavisDesktop", targets: ["MavisDesktop"])],
8
+ targets: [.executableTarget(name: "MavisDesktop")]
9
+ )
@@ -0,0 +1,20 @@
1
+ import SwiftUI
2
+
3
+ @main
4
+ struct MavisDesktopApp: App {
5
+ var body: some Scene {
6
+ WindowGroup("__MAVIS_NAME__") {
7
+ ScrollView {
8
+ Welcome()
9
+ .padding(48)
10
+ .frame(maxWidth: 820, alignment: .leading)
11
+ .frame(maxWidth: .infinity, alignment: .center)
12
+ }
13
+ .background(MavisTokens.background)
14
+ .tint(MavisTokens.primary)
15
+ .preferredColorScheme(.__MAVIS_APPEARANCE__)
16
+ .frame(minWidth: 640, minHeight: 640)
17
+ }
18
+ .defaultSize(width: 860, height: 760)
19
+ }
20
+ }
@@ -0,0 +1,17 @@
1
+ import { readFile, writeFile } from 'node:fs/promises'
2
+ import { createHash } from 'node:crypto'
3
+ import { compileWelcome } from './portable.mjs'
4
+
5
+ const source = await readFile(new URL('../shared/Welcome.lite.tsx', import.meta.url), 'utf8')
6
+ const { swift, vue, tokens } = await compileWelcome(source, '__MAVIS_THEME__')
7
+ // Validate both targets before replacing generated files. Never edit these outputs.
8
+ const header = `Generated by Mitosis 0.14.2 + Mavis experimental adapters; source SHA256 ${createHash('sha256').update(source).digest('hex')}`
9
+ await writeFile(
10
+ new URL('../native/Sources/MavisDesktop/Welcome.generated.swift', import.meta.url),
11
+ `// ${header}\n${swift}\n${tokens}\n`,
12
+ )
13
+ await writeFile(
14
+ new URL('../web/Welcome.generated.vue', import.meta.url),
15
+ `<!-- ${header} -->\n${vue}\n`,
16
+ )
17
+ console.log('Generated Vue and SwiftUI from shared/Welcome.lite.tsx.')
@@ -0,0 +1,51 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import { mkdir, copyFile, writeFile } from 'node:fs/promises'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { join } from 'node:path'
5
+
6
+ if (process.platform !== 'darwin')
7
+ throw new Error(
8
+ 'The macOS app needs macOS 14+ and Xcode. Web and code generation work on other hosts.',
9
+ )
10
+ const action = process.argv[2] ?? 'build'
11
+ if (!['build', 'run'].includes(action)) throw new Error('Expected build or run.')
12
+ const root = fileURLToPath(new URL('../', import.meta.url))
13
+ function run(command, args, capture = false) {
14
+ const result = spawnSync(command, args, {
15
+ cwd: root,
16
+ encoding: 'utf8',
17
+ stdio: capture ? 'pipe' : 'inherit',
18
+ })
19
+ if (result.error) throw result.error
20
+ if (result.status !== 0)
21
+ throw new Error(
22
+ `${command} failed (${result.status}). Check Xcode installation and command-line tools.`,
23
+ )
24
+ return result.stdout?.trim()
25
+ }
26
+ run(process.execPath, ['scripts/generate.mjs'])
27
+ run('swift', ['build', '--package-path', 'native', '-c', 'release'])
28
+ const bin = run(
29
+ 'swift',
30
+ ['build', '--package-path', 'native', '-c', 'release', '--show-bin-path'],
31
+ true,
32
+ )
33
+ const app = join(root, 'dist', '__MAVIS_NAME__.app')
34
+ await mkdir(join(app, 'Contents', 'MacOS'), { recursive: true })
35
+ await copyFile(join(bin, 'MavisDesktop'), join(app, 'Contents', 'MacOS', 'MavisDesktop'))
36
+ await writeFile(
37
+ join(app, 'Contents', 'Info.plist'),
38
+ `<?xml version="1.0" encoding="UTF-8"?>
39
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
40
+ <plist version="1.0"><dict>
41
+ <key>CFBundleExecutable</key><string>MavisDesktop</string>
42
+ <key>CFBundleIdentifier</key><string>com.mavis.experimental.__MAVIS_APPID__</string>
43
+ <key>CFBundleName</key><string>__MAVIS_NAME__</string>
44
+ <key>CFBundlePackageType</key><string>APPL</string>
45
+ <key>CFBundleShortVersionString</key><string>0.0.0</string>
46
+ <key>LSMinimumSystemVersion</key><string>14.0</string>
47
+ <key>NSHighResolutionCapable</key><true/>
48
+ </dict></plist>`,
49
+ )
50
+ console.log(`Built ${app}. Local unsigned development app; distribution/signing is not configured.`)
51
+ if (action === 'run') run('open', ['-n', app])
@@ -0,0 +1,395 @@
1
+ import ts from 'typescript'
2
+
3
+ const allowed = {
4
+ MColumn: ['gap', 'padding'],
5
+ MRow: ['gap', 'padding'],
6
+ MText: ['variant', 'tone'],
7
+ MButton: ['text', 'variant', 'onClick'],
8
+ }
9
+ const reserved = new Set(
10
+ 'self body description init let var func class struct enum protocol extension import return true false nil default switch case if else for while repeat break continue throw throws try catch await async in is as some any private public internal static typealias defer guard do super associatedtype deinit fileprivate inout operator rethrows subscript where'.split(
11
+ ' ',
12
+ ),
13
+ )
14
+
15
+ /** A deliberately bounded grammar, checked before Mitosis can drop unsupported code. */
16
+ export function validateSource(source) {
17
+ const file = ts.createSourceFile(
18
+ 'shared/Welcome.lite.tsx',
19
+ source,
20
+ ts.ScriptTarget.Latest,
21
+ true,
22
+ ts.ScriptKind.TSX,
23
+ )
24
+ const fail = (node, message) => {
25
+ const { line, character } = file.getLineAndCharacterOfPosition(node.getStart(file))
26
+ throw new Error(`${file.fileName}:${line + 1}:${character + 1}: ${message}`)
27
+ }
28
+ if (file.parseDiagnostics.length) fail(file, 'Invalid TSX syntax.')
29
+ const statements = file.statements
30
+ const imp = statements[0]
31
+ if (
32
+ statements.length !== 2 ||
33
+ !imp ||
34
+ !ts.isImportDeclaration(imp) ||
35
+ imp.moduleSpecifier.text !== '@builder.io/mitosis' ||
36
+ imp.importClause?.name ||
37
+ imp.importClause?.isTypeOnly ||
38
+ imp.attributes ||
39
+ !imp.importClause?.namedBindings ||
40
+ !ts.isNamedImports(imp.importClause.namedBindings) ||
41
+ imp.importClause.namedBindings.elements.length !== 1 ||
42
+ imp.importClause.namedBindings.elements[0].name.text !== 'useStore' ||
43
+ imp.importClause.namedBindings.elements[0].propertyName
44
+ )
45
+ fail(
46
+ file,
47
+ 'Import only { useStore } from @builder.io/mitosis, followed by export default function Welcome().',
48
+ )
49
+ const fn = statements[1]
50
+ if (
51
+ !ts.isFunctionDeclaration(fn) ||
52
+ fn.name?.text !== 'Welcome' ||
53
+ fn.parameters.length ||
54
+ fn.typeParameters ||
55
+ fn.asteriskToken ||
56
+ fn.type ||
57
+ fn.modifiers?.map((m) => m.kind).join(',') !==
58
+ [ts.SyntaxKind.ExportKeyword, ts.SyntaxKind.DefaultKeyword].join(',') ||
59
+ fn.body?.statements.length !== 2
60
+ )
61
+ fail(
62
+ fn,
63
+ 'Use export default function Welcome() with one state declaration and one JSX return. Hooks, props and arbitrary functions are not supported yet.',
64
+ )
65
+ const declaration = fn.body.statements[0]
66
+ if (
67
+ !ts.isVariableStatement(declaration) ||
68
+ declaration.declarationList.flags !== ts.NodeFlags.Const ||
69
+ declaration.declarationList.declarations.length !== 1
70
+ )
71
+ fail(declaration, 'Declare const state = useStore({ ... }).')
72
+ const store = declaration.declarationList.declarations[0]
73
+ if (
74
+ !ts.isIdentifier(store.name) ||
75
+ store.name.text !== 'state' ||
76
+ store.type ||
77
+ !store.initializer ||
78
+ !ts.isCallExpression(store.initializer) ||
79
+ store.initializer.expression.getText(file) !== 'useStore' ||
80
+ store.initializer.typeArguments ||
81
+ store.initializer.arguments.length !== 1 ||
82
+ !ts.isObjectLiteralExpression(store.initializer.arguments[0])
83
+ )
84
+ fail(store, 'Declare const state = useStore({ ... }) without type arguments.')
85
+ const state = new Map()
86
+ const literal = (node) => {
87
+ if (ts.isStringLiteral(node)) return { kind: 'string', value: node.text }
88
+ if (ts.isNumericLiteral(node) && /^\d+$/.test(node.text) && Number(node.text) <= 2147483647)
89
+ return { kind: 'number', value: Number(node.text) }
90
+ if ([ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword].includes(node.kind))
91
+ return { kind: 'boolean', value: node.kind === ts.SyntaxKind.TrueKeyword }
92
+ return null
93
+ }
94
+ for (const prop of store.initializer.arguments[0].properties) {
95
+ if (
96
+ !ts.isPropertyAssignment(prop) ||
97
+ !ts.isIdentifier(prop.name) ||
98
+ reserved.has(prop.name.text) ||
99
+ !/^[a-z][a-zA-Z0-9]*$/.test(prop.name.text) ||
100
+ state.has(prop.name.text)
101
+ )
102
+ fail(prop, 'State needs unique, simple names (not Swift keywords) and literal values.')
103
+ const value = literal(prop.initializer)
104
+ if (!value)
105
+ fail(prop, 'State supports strings, booleans and non-negative 32-bit integer literals only.')
106
+ state.set(prop.name.text, value)
107
+ }
108
+ const reference = (node) =>
109
+ ts.isPropertyAccessExpression(node) &&
110
+ ts.isIdentifier(node.expression) &&
111
+ node.expression.text === 'state' &&
112
+ state.has(node.name.text)
113
+ ? node.name.text
114
+ : null
115
+ const action = (node) => {
116
+ if (
117
+ !ts.isArrowFunction(node) ||
118
+ node.parameters.length ||
119
+ node.modifiers ||
120
+ node.typeParameters ||
121
+ node.type
122
+ )
123
+ fail(node, 'onClick supports a zero-argument arrow with one state assignment.')
124
+ let body = node.body
125
+ while (ts.isParenthesizedExpression(body)) body = body.expression
126
+ if (
127
+ !ts.isBinaryExpression(body) ||
128
+ body.operatorToken.kind !== ts.SyntaxKind.EqualsToken ||
129
+ !reference(body.left)
130
+ )
131
+ fail(body, 'Assign one declared state property, for example state.sparks = state.sparks + 1.')
132
+ const key = reference(body.left),
133
+ value = literal(body.right)
134
+ if (value?.kind === state.get(key).kind) return
135
+ if (
136
+ state.get(key).kind === 'number' &&
137
+ ts.isBinaryExpression(body.right) &&
138
+ reference(body.right.left) === key &&
139
+ body.right.operatorToken.kind === ts.SyntaxKind.PlusToken &&
140
+ literal(body.right.right)?.kind === 'number'
141
+ )
142
+ return
143
+ fail(
144
+ body.right,
145
+ 'Only same-type literal assignments or integer increments are supported. Calls, effects and other expressions need a future compiler contract.',
146
+ )
147
+ }
148
+ const jsx = (node, parent) => {
149
+ if (ts.isParenthesizedExpression(node)) return jsx(node.expression, parent)
150
+ if (ts.isJsxText(node)) {
151
+ if (node.text.trim() && parent !== 'MText') fail(node, 'Put text inside MText.')
152
+ return
153
+ }
154
+ if (ts.isJsxExpression(node)) {
155
+ if (parent !== 'MText' || !node.expression || !reference(node.expression))
156
+ fail(node, 'Text bindings must reference one declared state property.')
157
+ return
158
+ }
159
+ if (!ts.isJsxElement(node) && !ts.isJsxSelfClosingElement(node))
160
+ fail(
161
+ node,
162
+ 'Use MColumn, MRow, MText and MButton. HTML, loops, conditionals and other components are not supported yet.',
163
+ )
164
+ const tag = ts.isJsxElement(node) ? node.openingElement : node
165
+ const name = tag.tagName.getText(file)
166
+ if (!allowed[name]) fail(tag, `${name} is not part of the experimental macOS subset.`)
167
+ const names = new Set()
168
+ for (const attr of tag.attributes.properties) {
169
+ if (
170
+ !ts.isJsxAttribute(attr) ||
171
+ !allowed[name].includes(attr.name.text) ||
172
+ names.has(attr.name.text)
173
+ )
174
+ fail(
175
+ attr,
176
+ `Unsupported or duplicate ${name} property. Supported: ${allowed[name].join(', ')}.`,
177
+ )
178
+ names.add(attr.name.text)
179
+ if (attr.name.text === 'onClick') {
180
+ if (
181
+ !attr.initializer ||
182
+ !ts.isJsxExpression(attr.initializer) ||
183
+ !attr.initializer.expression
184
+ )
185
+ fail(attr, 'onClick needs an arrow function.')
186
+ action(attr.initializer.expression)
187
+ } else if (!attr.initializer || !ts.isStringLiteral(attr.initializer))
188
+ fail(attr, 'Use literal string properties; dynamic styling is not supported yet.')
189
+ }
190
+ if (name === 'MButton' && (!names.has('text') || !names.has('onClick')))
191
+ fail(tag, 'MButton requires text and onClick.')
192
+ const children = ts.isJsxElement(node)
193
+ ? node.children.filter((c) => !ts.isJsxText(c) || c.text.trim())
194
+ : []
195
+ if (
196
+ name === 'MText' &&
197
+ (children.length !== 1 || !(ts.isJsxText(children[0]) || ts.isJsxExpression(children[0])))
198
+ )
199
+ fail(node, 'MText needs one literal text or state binding, without nested markup.')
200
+ if (name === 'MButton' && children.length) fail(node, 'Use the text property on MButton.')
201
+ children.forEach((child) => jsx(child, name))
202
+ }
203
+ const ret = fn.body.statements[1]
204
+ if (!ts.isReturnStatement(ret) || !ret.expression) fail(ret, 'Return the shared screen as JSX.')
205
+ jsx(ret.expression)
206
+ return state
207
+ }
208
+
209
+ const binding = (code) => ({ code, type: 'single', bindingType: 'expression' })
210
+ const nativeString = (text) => {
211
+ if (!text.isWellFormed()) throw new Error('Text must contain well-formed Unicode.')
212
+ return (
213
+ '"' +
214
+ Array.from(text, (char) => {
215
+ if (char === '\\') return '\\\\'
216
+ if (char === '"') return '\\"'
217
+ return char.codePointAt(0) < 32 ? `\\u{${char.codePointAt(0).toString(16)}}` : char
218
+ }).join('') +
219
+ '"'
220
+ )
221
+ }
222
+ const node = (name, properties = {}, bindings = {}, children = []) => ({
223
+ '@type': '@builder.io/mitosis/node',
224
+ name,
225
+ properties,
226
+ bindings,
227
+ children,
228
+ meta: {},
229
+ scope: {},
230
+ })
231
+
232
+ export async function compileWelcome(source, themeName = 'mavis') {
233
+ const state = validateSource(source)
234
+ const [{ parseJsx, componentToSwift, componentToVue }, core] = await Promise.all([
235
+ import('@builder.io/mitosis'),
236
+ import('@getcortexlabs/mavis-core'),
237
+ ])
238
+ if (!['mavis', 'midnight'].includes(themeName)) throw new Error('Unknown starter theme.')
239
+ const theme = core[themeName]
240
+ const parsed = parseJsx(source)
241
+ const wrappers = []
242
+ // Keep string literals outside Mitosis's generic formatter: it decodes \\n.
243
+ // Its Swift generator still owns state, actions and the view tree.
244
+ const literals = []
245
+ const textLiteral = (value) => {
246
+ const key = `text${literals.length}`
247
+ literals.push(`static let ${key} = ${nativeString(value)}`)
248
+ return `MavisLiterals.${key}`
249
+ }
250
+ const nativeAction = (code) => {
251
+ const file = ts.createSourceFile('action.ts', code, ts.ScriptTarget.Latest, true)
252
+ const result = ts.transform(file, [
253
+ (context) => {
254
+ const visit = (node) =>
255
+ ts.isStringLiteral(node)
256
+ ? ts.factory.createPropertyAccessExpression(
257
+ ts.factory.createIdentifier('MavisLiterals'),
258
+ textLiteral(node.text).split('.')[1],
259
+ )
260
+ : ts.visitEachChild(node, visit, context)
261
+ return (node) => ts.visitNode(node, visit)
262
+ },
263
+ ])
264
+ try {
265
+ return ts.createPrinter().printFile(result.transformed[0]).trim()
266
+ } finally {
267
+ result.dispose()
268
+ }
269
+ }
270
+ const colors = Object.entries(theme.colors)
271
+ .map(([key, value]) => {
272
+ if (!/^#[0-9a-f]{6}$/i.test(value)) throw new Error(`Unsupported color token ${key}.`)
273
+ const hex = Number.parseInt(value.slice(1), 16)
274
+ return `static let ${key} = Color(red: ${((hex >> 16) & 255) / 255}, green: ${((hex >> 8) & 255) / 255}, blue: ${(hex & 255) / 255})`
275
+ })
276
+ .join('\n')
277
+ const token = (family, value, fallback) => {
278
+ const key = value ?? fallback
279
+ if (!Object.hasOwn(family, key))
280
+ throw new Error(`shared/Welcome.lite.tsx: Unsupported token ${key}.`)
281
+ return family[key]
282
+ }
283
+ const lower = (input) => {
284
+ const p = input.properties
285
+ let output,
286
+ modifiers = []
287
+ if (input.name === 'MColumn' || input.name === 'MRow') {
288
+ output = node(
289
+ input.name === 'MColumn' ? 'div' : 'HStack',
290
+ {
291
+ spacing: String(token(theme.space, p.gap, 'none')),
292
+ alignment: input.name === 'MColumn' ? 'leading' : 'center',
293
+ },
294
+ {},
295
+ input.children.map(lower),
296
+ )
297
+ if (Object.hasOwn(p, 'padding')) modifiers.push(`.padding(${token(theme.space, p.padding)})`)
298
+ } else if (input.name === 'MText') {
299
+ const child = input.children[0]
300
+ const ref = child.bindings._text?.code
301
+ const content = ref
302
+ ? state.get(ref.slice(6)).kind === 'string'
303
+ ? ref
304
+ : `String(${ref})`
305
+ : textLiteral(child.properties._text.replace(/\s*\n\s*/g, ' ').trim())
306
+ output = node('p', {}, { innerHTML: binding(content) })
307
+ const typo = token(theme.typography, p.variant, 'body')
308
+ const weights = {
309
+ normal: 'regular',
310
+ bold: 'bold',
311
+ 100: 'ultraLight',
312
+ 200: 'thin',
313
+ 300: 'light',
314
+ 400: 'regular',
315
+ 500: 'medium',
316
+ 600: 'semibold',
317
+ 700: 'bold',
318
+ 800: 'heavy',
319
+ 900: 'black',
320
+ }
321
+ token(theme.colors, p.tone, 'text')
322
+ modifiers.push(
323
+ `.font(.system(size: ${typo.fontSize}, weight: .${weights[typo.fontWeight]}))`,
324
+ `.foregroundStyle(MavisTokens.${p.tone ?? 'text'})`,
325
+ '.fixedSize(horizontal: false, vertical: true)',
326
+ )
327
+ if (['title', 'heading', 'display'].includes(p.variant))
328
+ modifiers.push('.accessibilityAddTraits(.isHeader)')
329
+ } else {
330
+ if (!['primary', 'secondary'].includes(p.variant ?? 'primary'))
331
+ throw new Error(
332
+ 'shared/Welcome.lite.tsx: MButton supports primary and secondary variants in this experiment.',
333
+ )
334
+ output = node(
335
+ 'button',
336
+ {},
337
+ { onClick: { ...input.bindings.onClick, code: nativeAction(input.bindings.onClick.code) } },
338
+ [node('p', {}, { innerHTML: binding(textLiteral(p.text)) })],
339
+ )
340
+ modifiers.push(
341
+ `.buttonStyle(MavisStarterButtonStyle(secondary: ${p.variant === 'secondary'}))`,
342
+ )
343
+ }
344
+ const name = `MavisStyle${wrappers.length}`
345
+ wrappers.push(`private struct ${name}<Content: View>: View {
346
+ let content: Content
347
+ init(@ViewBuilder content: () -> Content) { self.content = content() }
348
+ var body: some View { content\n${modifiers.join('\n')} }
349
+ }`)
350
+ return node(name, {}, {}, [output])
351
+ }
352
+ const plugin = () => ({
353
+ json: {
354
+ pre(json) {
355
+ for (const [key, value] of state) {
356
+ json.state[key].typeParameter = { number: 'Int', string: 'String', boolean: 'Bool' }[
357
+ value.kind
358
+ ]
359
+ json.state[key].code =
360
+ value.kind === 'string' ? textLiteral(value.value) : String(value.value)
361
+ }
362
+ json.children = json.children.map(lower)
363
+ return json
364
+ },
365
+ },
366
+ code: {
367
+ post(code, _json) {
368
+ return `${code}\nprivate enum MavisLiterals {\n${literals.join('\n')}\n}\n${wrappers.join('\n')}`
369
+ },
370
+ },
371
+ })
372
+ const swift = componentToSwift({ includePreview: false, plugins: [plugin] })({
373
+ component: parsed,
374
+ })
375
+ const vue = componentToVue({ api: 'composition' })({ component: parsed })
376
+ return {
377
+ swift,
378
+ vue,
379
+ tokens: `enum MavisTokens {\n${colors}\n}
380
+ private struct MavisStarterButtonStyle: ButtonStyle {
381
+ let secondary: Bool
382
+ @Environment(\\.accessibilityReduceMotion) private var reduceMotion
383
+ func makeBody(configuration: Configuration) -> some View {
384
+ configuration.label
385
+ .font(.system(size: 15, weight: .semibold))
386
+ .padding(.horizontal, 20).padding(.vertical, 12)
387
+ .foregroundStyle(secondary ? MavisTokens.text : MavisTokens.onPrimary)
388
+ .background(secondary ? MavisTokens.elevated : MavisTokens.primary, in: RoundedRectangle(cornerRadius: 12))
389
+ .opacity(configuration.isPressed ? 0.8 : 1)
390
+ .scaleEffect(configuration.isPressed && !reduceMotion ? 0.98 : 1)
391
+ .animation(reduceMotion ? nil : .easeOut(duration: 0.15), value: configuration.isPressed)
392
+ }
393
+ }`,
394
+ }
395
+ }
@@ -0,0 +1,40 @@
1
+ import { useStore } from '@builder.io/mitosis'
2
+
3
+ // This small, checked subset generates both Vue and SwiftUI.
4
+ // Edit this source, then run the generate command before rebuilding either host.
5
+ export default function Welcome() {
6
+ const state = useStore({ sparks: 0 })
7
+ return (
8
+ <MColumn gap="xl">
9
+ <MRow gap="sm">
10
+ <MText variant="overline" tone="primary">
11
+ MAVIS / FIRST LIGHT
12
+ </MText>
13
+ <MText variant="caption" tone="muted">
14
+ Experimental · macOS + Web
15
+ </MText>
16
+ </MRow>
17
+ <MColumn gap="sm">
18
+ <MText variant="display">One idea.</MText>
19
+ <MText variant="display" tone="primary">
20
+ A new window.
21
+ </MText>
22
+ <MText tone="muted">Your first shared screen, now at home on the Mac.</MText>
23
+ </MColumn>
24
+ <MColumn gap="md" padding="lg">
25
+ <MText variant="overline" tone="muted">
26
+ MAKE A LITTLE MAGIC
27
+ </MText>
28
+ <MText variant="title">{state.sparks}</MText>
29
+ <MText tone="muted">Sparks collected in this window.</MText>
30
+ <MRow gap="sm">
31
+ <MButton text="Add a spark" onClick={() => (state.sparks = state.sparks + 1)} />
32
+ <MButton text="Start again" variant="secondary" onClick={() => (state.sparks = 0)} />
33
+ </MRow>
34
+ </MColumn>
35
+ <MText variant="caption" tone="muted">
36
+ One Welcome.lite.tsx · Vue on the Web · SwiftUI on macOS
37
+ </MText>
38
+ </MColumn>
39
+ )
40
+ }
@@ -0,0 +1,3 @@
1
+ import { defineConfig } from 'vite'
2
+ import vue from '@vitejs/plugin-vue'
3
+ export default defineConfig({ plugins: [vue()], build: { outDir: 'dist/web' } })
@@ -0,0 +1,15 @@
1
+ import { createApp } from 'vue'
2
+ import { createMavisServices } from '@getcortexlabs/mavis-web/services'
3
+ import { MColumn, MRow, MText, MButton, mavis, midnight } from '@getcortexlabs/mavis-web'
4
+ import Welcome from './Welcome.generated.vue'
5
+ import '@getcortexlabs/mavis-web/style.css'
6
+ import './style.css'
7
+
8
+ const app = createApp(Welcome)
9
+ for (const [name, component] of Object.entries({ MColumn, MRow, MText, MButton }))
10
+ app.component(name, component)
11
+ app
12
+ .use(
13
+ createMavisServices({ theme: mavis, darkTheme: midnight, appearance: '__MAVIS_APPEARANCE__' }),
14
+ )
15
+ .mount('#app')
@@ -0,0 +1,13 @@
1
+ html {
2
+ color-scheme: __MAVIS_APPEARANCE__;
3
+ background: __MAVIS_BACKGROUND__;
4
+ }
5
+ body {
6
+ margin: 0;
7
+ font-family: system-ui, sans-serif;
8
+ }
9
+ #app {
10
+ max-width: 760px;
11
+ margin: 0 auto;
12
+ padding: clamp(24px, 6vw, 64px);
13
+ }