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

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.
Files changed (51) hide show
  1. package/README.md +30 -9
  2. package/package.json +4 -2
  3. package/src/adapters.mjs +83 -0
  4. package/src/add-macos.mjs +386 -0
  5. package/src/add-target.mjs +1 -1
  6. package/src/capabilities.mjs +647 -0
  7. package/src/cli.mjs +129 -16
  8. package/src/doctor.mjs +159 -36
  9. package/src/macos-capabilities.generated.mjs +4190 -0
  10. package/src/macos.mjs +343 -58
  11. package/src/migrate-directory.mjs +121 -0
  12. package/src/package-manager.mjs +12 -4
  13. package/src/portability.mjs +110 -6
  14. package/src/presets.mjs +15 -108
  15. package/src/scaffold.mjs +32 -5
  16. package/src/ui.mjs +124 -82
  17. package/templates/directory/host/directory-storage.ts +78 -0
  18. package/templates/directory/macos/DirectoryStorage.swift +68 -0
  19. package/templates/directory/mobile/src/app.ts +11 -8
  20. package/templates/directory/nuxt/app/plugins/mavis.ts +11 -8
  21. package/templates/directory/shared/Edit.vue +8 -5
  22. package/templates/directory/shared/directory-store.ts +42 -46
  23. package/templates/directory/vite/src/main.ts +11 -8
  24. package/templates/macos/examples/tasks/shared/TaskDetail.lite.tsx +57 -0
  25. package/templates/macos/examples/tasks/shared/TaskRow.lite.tsx +33 -0
  26. package/templates/macos/examples/tasks/shared/Tasks.lite.tsx +251 -0
  27. package/templates/macos/examples/tasks/shared/types.ts +10 -0
  28. package/templates/macos/mobile/src/App.vue +14 -0
  29. package/templates/macos/mobile/src/app.ts +7 -0
  30. package/templates/macos/native/Package.swift +11 -1
  31. package/templates/macos/native/Sources/MavisDesktop/App.swift +27 -12
  32. package/templates/macos/native/Sources/MavisDesktop/Fonts/LICENSE +45 -0
  33. package/templates/macos/native/Sources/MavisDesktop/Fonts/lucide.ttf +0 -0
  34. package/templates/macos/root/tsconfig.json +14 -0
  35. package/templates/macos/scripts/generate.mjs +12 -16
  36. package/templates/macos/scripts/macos-manifest.mjs +33 -0
  37. package/templates/macos/scripts/macos.mjs +26 -19
  38. package/templates/macos/shared/Welcome.lite.tsx +8 -6
  39. package/templates/macos/{index.html → web/index.html} +2 -2
  40. package/templates/macos/web/src/main.js +212 -0
  41. package/templates/macos/web/src/mavis.js +2 -0
  42. package/templates/macos/web/{style.css → src/style.css} +3 -2
  43. package/templates/macos/web/vite.config.mjs +14 -0
  44. package/templates/migrations/directory-rc13.json +36 -0
  45. package/templates/mobile/src/mavis.ts +2 -82
  46. package/templates/mobile/webpack.config.js +4 -0
  47. package/templates/nuxt/app/mavis.ts +2 -84
  48. package/templates/vite/src/mavis.ts +2 -84
  49. package/templates/macos/scripts/portable.mjs +0 -395
  50. package/templates/macos/vite.config.mjs +0 -3
  51. package/templates/macos/web/main.js +0 -15
@@ -1,395 +0,0 @@
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
- }
@@ -1,3 +0,0 @@
1
- import { defineConfig } from 'vite'
2
- import vue from '@vitejs/plugin-vue'
3
- export default defineConfig({ plugins: [vue()], build: { outDir: 'dist/web' } })
@@ -1,15 +0,0 @@
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')