@nstudio/nativescript-compiler-vue 0.0.0-stage → 9.2.0-alpha.9

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/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright OpenJS Foundation and other contributors, https://openjsf.org
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # @nstudio/nativescript-compiler-vue
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Vue adapter for [`@nstudio/nativescript-compiler`](https://www.npmjs.com/package/@nstudio/nativescript-compiler), enabling NativeScript Vue apps (`nativescript-vue`) to compile directly to Swift (iOS) and Kotlin (Android) with no JavaScript runtime.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ ns extension install @nstudio/nativescript-compiler
9
+ npm install --save-dev @nstudio/nativescript-compiler-vue
10
+ ```
11
+
12
+ Install the adapter at the same version as `@nstudio/nativescript-compiler`.
13
+
14
+ ## Usage
15
+
16
+ ```bash
17
+ ns compile ios
18
+ ns compile android
19
+ ```
20
+
21
+ ## Supported Versions
22
+
23
+ - `nativescript-vue`: `>=3.1.0 <4.0.0`
24
+
25
+ ## License
26
+
27
+ MIT
@@ -0,0 +1,8 @@
1
+ /** The compiler's own functions and state, from the compiler that loaded the adapter: set by its entry before any front end runs. */
2
+ export let core;
3
+ /** The compiler's TypeScript (`core.ts`), set with `core`: the adapter reads and makes the compiler's syntax trees with it, never with a TypeScript of its own. */
4
+ export let ts;
5
+ export function useCore(api) {
6
+ core = api;
7
+ ts = api.ts;
8
+ }
package/dist/hooks.js ADDED
@@ -0,0 +1,25 @@
1
+ const model = {
2
+ signalTypes: { Ref: 'value' },
3
+ signalConstructors: { ref: 'deep' },
4
+ pure: ['ref', 'computed'],
5
+ typeMap: { OutputEmitterRef: 'Emitter<$0>' },
6
+ };
7
+ /** `nextTick()`, and `output()`: the emitter of an event the component's `emits` declares. */
8
+ function globalCall(t, name, e, _decl, lib) {
9
+ if (name === 'nextTick' && !e.arguments.length && lib)
10
+ return 'Reactivity.nextTick()';
11
+ if (name === 'output' && lib)
12
+ return `${t.typeOf(e)}()`;
13
+ return undefined;
14
+ }
15
+ /** `emit(value)` of an event's emitter. */
16
+ function methodCall(t, owner, method, e) {
17
+ if (owner !== 'OutputEmitterRef' || (method !== 'emit' && method !== 'next'))
18
+ return undefined;
19
+ const target = e.expression.expression;
20
+ const value = /^(?:OutputEmitterRef|EventEmitter|Emitter)<(.*)>[?!]?$/.exec(t.typeOf(target))?.[1];
21
+ const a = e.arguments[0];
22
+ return `${t.expr(target)}.emit(${a ? (value && value !== 'Void' && value !== 'Unit' ? t.coerce(a, value) : t.expr(a)) : ''})`;
23
+ }
24
+ export const swiftHooks = { ...model, globalCall, methodCall };
25
+ export const kotlinHooks = { ...model, globalCall, methodCall };
package/dist/index.js ADDED
@@ -0,0 +1,27 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { basename } from 'node:path';
3
+ import { useCore } from "./core-api.js";
4
+ import { kotlinHooks, swiftHooks } from "./hooks.js";
5
+ import { modules } from "./modules.js";
6
+ import { vueComponent } from "./vue.js";
7
+ export default function adapter(core) {
8
+ useCore(core);
9
+ return {
10
+ apiVersion: 1,
11
+ name: 'vue',
12
+ packages: ['nativescript-vue', 'vue'],
13
+ behaviour: { schedule: 'microtask', eventScope: 'none', propsOrder: 'post', deferBindings: false, insertion: 'built', listenersAfterBindings: false, effectScope: 'component', checkEveryBinding: 'off', slots: false, rowSignals: 'off', fragments: false, kit: { scope: { template: 'EffectOrder.component' } } },
14
+ reach: 'project',
15
+ swift: swiftHooks,
16
+ kotlin: kotlinHooks,
17
+ modules,
18
+ frontEnd(app) {
19
+ const components = app.files.filter((f) => f.endsWith('.vue')).map((f) => vueComponent(f, readFileSync(f, 'utf8')));
20
+ const rootImport = /createApp\(\s*(\w+)\s*\)/.exec(app.entryText)?.[1];
21
+ const rootFile = rootImport && new RegExp(`import\\s+${rootImport}\\s+from\\s+['"]([^'"]+)['"]`).exec(app.entryText)?.[1];
22
+ if (!rootFile)
23
+ throw new Error(`${app.entry}: no createApp(Component)`);
24
+ return { components, modules: app.sources, root: basename(rootFile, '.vue') };
25
+ },
26
+ };
27
+ }
@@ -0,0 +1,20 @@
1
+ export const modules = {
2
+ shims: {
3
+ 'nativescript-vue': `
4
+ import type { DeepRef } from '@nativescript/release';
5
+ export type Ref<T> = DeepRef<T>;
6
+ export declare function ref<T>(value: T): DeepRef<T>;
7
+ export declare function computed<T>(fn: () => T): { readonly value: T };
8
+ export declare function nextTick(): Promise<void>;
9
+ export declare function $navigateTo(component: any, options?: { props?: Record<string, any> }): void;
10
+ export interface ModalOptions { props?: Record<string, any>; fullscreen?: boolean; animated?: boolean; cancelable?: boolean; closeCallback?: (result?: any) => void }
11
+ export declare function $showModal(component: any, options?: ModalOptions): { then(fn: (result?: any) => void): void };
12
+ export declare function $closeModal(result?: any): void;
13
+ export declare function createApp(component: any): { start(): void };
14
+ export interface ListItem<T = any> { item: T; index: number; even: boolean; odd: boolean }
15
+ import type { ItemEventData } from '@nativescript/core';
16
+ export interface ListViewItemTapEvent<T = any> extends ItemEventData { item: T; value: any }
17
+ `,
18
+ },
19
+ componentExtensions: ['.vue'],
20
+ };
package/dist/vue.js ADDED
@@ -0,0 +1,604 @@
1
+ import { compileStyle, parse } from '@vue/compiler-sfc';
2
+ import { createHash } from 'node:crypto';
3
+ import { createRequire } from 'node:module';
4
+ import { basename } from 'node:path';
5
+ import { core, ts } from "./core-api.js";
6
+ const VUE_KEPT = new Set(['$navigateTo', '$navigateBack', '$showModal', '$closeModal', 'nextTick', 'ListItem', 'ListViewItemTapEvent']);
7
+ function bindings(path) {
8
+ return { path, imports: [], fields: [], props: [], components: new Set(), inScript: { names: new Map(), unwrapValue: new Map() }, inTemplate: { names: new Map() }, arity: new Map(), later: [], propsName: '' };
9
+ }
10
+ /**
11
+ * A NativeScript-Vue single-file component (`<script setup lang="ts">`, or the
12
+ * Options API in `<script lang="ts">`, and a template of @nativescript/core
13
+ * elements) as a virtual class and a template.
14
+ */
15
+ export function vueComponent(path, text) {
16
+ const { descriptor, errors } = parse(text, { filename: path });
17
+ if (errors.length)
18
+ throw new Error(`${path}: ${errors[0]}`);
19
+ if (!descriptor.scriptSetup && descriptor.script)
20
+ return vueOptions(path, descriptor);
21
+ const name = basename(path, '.vue');
22
+ const script = descriptor.scriptSetup?.content ?? '';
23
+ const sf = ts.createSourceFile(path + '.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
24
+ const b = bindings(path);
25
+ for (const st of sf.statements) {
26
+ if (ts.isImportDeclaration(st)) {
27
+ importOf(b, st);
28
+ continue;
29
+ }
30
+ if (binding(b, st))
31
+ continue;
32
+ throw new Error(`${path}: unsupported top-level statement in <script setup>: ${st.getText().slice(0, 60)}`);
33
+ }
34
+ if (b.propsName)
35
+ b.inScript.names.set(b.propsName, 'this');
36
+ for (const f of b.later)
37
+ f();
38
+ const { members, template } = vueTemplate(path, descriptor, b);
39
+ const { styles, scope } = vueStyles(path, descriptor);
40
+ return { name, file: path + '.ts', source: classSource(name, descriptor, b, members), props: b.props, template: scope ? core.scopeTemplate(template, scope) : template, styles };
41
+ }
42
+ /**
43
+ * The component's `<style>` blocks as vue-loader hands them to the app's CSS chain: preprocessed (`lang="scss"`) and, where
44
+ * `scoped`, each selector limited to elements carrying the component's `data-v-` attribute, which nativescript-vue sets on
45
+ * every element of the component's template (`setScopeId`).
46
+ */
47
+ function vueStyles(path, descriptor) {
48
+ if (!descriptor.styles.length)
49
+ return { styles: [], scope: null };
50
+ const scope = descriptor.styles.some((s) => s.scoped) ? `data-v-${createHash('sha256').update(path).digest('hex').slice(0, 8)}` : null;
51
+ const appRequire = createRequire(path);
52
+ const styles = descriptor.styles.map((block, k) => {
53
+ if (block.module)
54
+ throw new Error(`${path}: <style module> (CSS modules) is not supported in a compiled release yet`);
55
+ if (block.src)
56
+ throw new Error(`${path}: <style src> is not supported in a compiled release yet`);
57
+ const lang = block.lang && block.lang !== 'css' ? block.lang : undefined;
58
+ const result = compileStyle({
59
+ source: block.content, filename: path, id: scope ?? 'data-v-unscoped', scoped: !!block.scoped,
60
+ preprocessLang: lang, preprocessCustomRequire: (id) => appRequire(id),
61
+ });
62
+ if (result.errors.length)
63
+ throw new Error(`${path}: <style> ${result.errors[0]}`);
64
+ return { file: `${path}.style${k}.css`, css: result.code };
65
+ });
66
+ return { styles, scope };
67
+ }
68
+ function importOf(b, st) {
69
+ const from = st.moduleSpecifier.text;
70
+ if (from.endsWith('.vue')) {
71
+ const local = st.importClause?.name?.text;
72
+ if (local)
73
+ b.components.add(local);
74
+ b.imports.push(`import ${local} from '${from}';`);
75
+ }
76
+ else if (from !== 'nativescript-vue') {
77
+ b.imports.push(st.getText());
78
+ }
79
+ else {
80
+ const navigation = st.importClause?.namedBindings;
81
+ // Vue's own API is read by the front end; navigation, modals and types reach the class.
82
+ const kept = navigation && ts.isNamedImports(navigation) ? navigation.elements.filter((e) => VUE_KEPT.has(e.name.text)).map((e) => e.getText()) : [];
83
+ if (kept.length)
84
+ b.imports.push(`import { ${kept.join(', ')} } from 'nativescript-vue';`);
85
+ }
86
+ }
87
+ /** A `<script setup>` (or `setup()`) statement declaring a function, a ref, a computed, the props or a constant; false for anything else. */
88
+ function binding(b, st) {
89
+ const { path, fields, props, inScript, inTemplate, arity, later } = b;
90
+ if (ts.isFunctionDeclaration(st) && st.name) {
91
+ const fn = st.name.text;
92
+ arity.set(fn, st.parameters.length);
93
+ inScript.names.set(fn, `this.${fn}`);
94
+ inTemplate.names.set(fn, `this.${fn}`);
95
+ later.push(() => {
96
+ const params = st.parameters.map((p) => p.getText()).join(', ');
97
+ const ret = st.type ? `: ${st.type.getText()}` : '';
98
+ fields.push(` ${(ts.getModifiers(st)?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword) ? 'async ' : '')}${fn}(${params})${ret} ${core.rewrite(st.body.getText(), inScript, 'statements')}`);
99
+ });
100
+ return true;
101
+ }
102
+ if (!ts.isVariableStatement(st))
103
+ return false;
104
+ const mutable = !!(st.declarationList.flags & ts.NodeFlags.Let);
105
+ for (const d of st.declarationList.declarations) {
106
+ if (mutable && ts.isIdentifier(d.name) && !(d.initializer && ts.isCallExpression(d.initializer) && ts.isIdentifier(d.initializer.expression) && ['ref', 'computed', 'defineProps'].includes(d.initializer.expression.text))) {
107
+ // A plain `let`: per-instance state no template reads reactively.
108
+ const id = d.name.text;
109
+ const init = d.initializer;
110
+ inScript.names.set(id, `this.${id}`);
111
+ inTemplate.names.set(id, `this.${id}`);
112
+ later.push(() => fields.push(` ${id}${d.type ? `: ${d.type.getText()}` : ''} = ${init ? core.rewrite(init.getText(), inScript) : 'undefined'};`));
113
+ continue;
114
+ }
115
+ if (!ts.isIdentifier(d.name) || !d.initializer)
116
+ continue;
117
+ const id = d.name.text;
118
+ const init = d.initializer;
119
+ const callee = ts.isCallExpression(init) && ts.isIdentifier(init.expression) ? init.expression.text : '';
120
+ if (callee === 'defineProps' && ts.isCallExpression(init)) {
121
+ b.propsName = id;
122
+ const literal = init.typeArguments?.[0];
123
+ if (!literal || !ts.isTypeLiteralNode(literal))
124
+ throw new Error(`${path}: defineProps needs a type literal`);
125
+ for (const m of literal.members) {
126
+ if (!ts.isPropertySignature(m) || !m.type)
127
+ continue;
128
+ const p = m.name.text;
129
+ props.push(p);
130
+ fields.push(` ${p}!: ${m.type.getText()};`);
131
+ inTemplate.names.set(p, `this.${p}`);
132
+ }
133
+ continue;
134
+ }
135
+ if (callee === 'ref' && ts.isCallExpression(init)) {
136
+ inScript.names.set(id, `this.${id}`);
137
+ inTemplate.names.set(id, `this.${id}.value`);
138
+ const typeArgs = init.typeArguments ? `<${init.typeArguments.map((t) => t.getText()).join(', ')}>` : '';
139
+ later.push(() => fields.push(` ${id} = $ref${typeArgs}(${init.arguments[0] ? core.rewrite(init.arguments[0].getText(), inScript) : 'undefined'});`));
140
+ continue;
141
+ }
142
+ if (callee === 'computed' && ts.isCallExpression(init)) {
143
+ inScript.unwrapValue.set(id, `this.${id}`);
144
+ inTemplate.names.set(id, `this.${id}`);
145
+ later.push(() => {
146
+ const fn = init.arguments[0];
147
+ if (!fn || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)))
148
+ throw new Error(`${path}: computed(${id}) needs a function`);
149
+ const body = ts.isBlock(fn.body) ? core.rewrite(fn.body.getText(), inScript, 'statements') : `{ return ${core.rewrite(fn.body.getText(), inScript)}; }`;
150
+ fields.push(` get ${id}()${fn.type ? `: ${fn.type.getText()}` : ''} ${body}`);
151
+ });
152
+ continue;
153
+ }
154
+ inScript.names.set(id, `this.${id}`);
155
+ inTemplate.names.set(id, `this.${id}`);
156
+ later.push(() => fields.push(` readonly ${id} = ${core.rewrite(init.getText(), inScript)};`));
157
+ }
158
+ return true;
159
+ }
160
+ function classSource(name, descriptor, b, members, preamble = []) {
161
+ // nativescript-vue's global properties, which templates use without importing.
162
+ for (const global of ['$closeModal', '$showModal']) {
163
+ if (descriptor.template?.content.includes(global) && !b.imports.some((i) => i.includes(global))) {
164
+ b.imports.push(`import { ${global} } from 'nativescript-vue';`);
165
+ }
166
+ }
167
+ return [
168
+ `import { $ref, type EventData as $EventData } from '@nativescript/release';`,
169
+ ...preamble,
170
+ ...b.imports,
171
+ ``,
172
+ `export default class ${name} {`,
173
+ ...b.fields,
174
+ ...members,
175
+ `}`,
176
+ ``,
177
+ ].join('\n');
178
+ }
179
+ /** The template's expressions as methods (loop variables as typed parameters) and its tree. */
180
+ function vueTemplate(path, descriptor, b, preprocess = (code) => code) {
181
+ const { components, inTemplate, arity } = b;
182
+ const members = [];
183
+ let next = 0;
184
+ const params = (loops) => loops.map((l) => l.param).join(', ');
185
+ const args = (loops) => loops.flatMap((l) => [l.item, l.index]);
186
+ const expr = (code, loops) => {
187
+ const scope = withLoops(inTemplate, loops);
188
+ const m = `$b${next++}`;
189
+ members.push(` ${m}(${params(loops)}) { return ${core.rewrite(preprocess(code), scope)}; }`);
190
+ return m;
191
+ };
192
+ const handler = (code, loops) => {
193
+ const scope = withLoops(inTemplate, loops);
194
+ const m = `$e${next++}`;
195
+ const p = [params(loops), '$event: $EventData'].filter(Boolean).join(', ');
196
+ code = preprocess(code);
197
+ // A method path (`onPlan`, `store.save`) is called with the event; anything else is a statement.
198
+ const isPath = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/.test(code.trim());
199
+ const takesEvent = arity.get(code.trim()) !== 0;
200
+ const body = isPath ? `${core.rewrite(code, scope).slice(1, -1)}(${takesEvent ? '$event' : ''});` : core.rewrite(code, scope, 'statements');
201
+ members.push(` ${m}(${p}) { ${body} }`);
202
+ return m;
203
+ };
204
+ const nodes = (children, loops) => {
205
+ const out = [];
206
+ let chain = null;
207
+ for (const c of children) {
208
+ if (c.type !== 1)
209
+ continue; // elements only: NativeScript has no text nodes or comments
210
+ const dirs = c.props.filter((p) => p.type === 7);
211
+ const vFor = dirs.find((d) => d.name === 'for');
212
+ const vIf = dirs.find((d) => d.name === 'if' || d.name === 'else-if' || d.name === 'else');
213
+ const build = (inner) => element(c, inner);
214
+ let node;
215
+ if (vFor) {
216
+ const m = /^\s*(?:\(\s*([\w$]+)\s*(?:,\s*([\w$]+)\s*)?\)|([\w$]+))\s+(?:in|of)\s+([\s\S]+)$/.exec(vFor.exp.content);
217
+ if (!m)
218
+ throw new Error(`${path}: v-for "${vFor.exp.content}"`);
219
+ const item = m[1] ?? m[3];
220
+ const index = m[2] ?? `$i${loops.length}`;
221
+ const items = expr(m[4], loops);
222
+ const loop = { item, index, param: `${item} = this.${items}(${args(loops).join(', ')})[0], ${index} = 0` };
223
+ const inner = [...loops, loop];
224
+ const keyDir = c.props.find((p) => p.type === 7 && p.name === 'bind' && p.arg?.content === 'key');
225
+ node = { kind: 'for', items, key: keyDir ? expr(keyDir.exp.content, inner) : null, item, index, body: [build(inner)] };
226
+ }
227
+ else
228
+ node = build(loops);
229
+ if (vIf && !vFor) {
230
+ if (vIf.name === 'if') {
231
+ chain = { kind: 'if', branches: [{ cond: expr(vIf.exp.content, loops), body: [node] }] };
232
+ out.push(chain);
233
+ }
234
+ else if (chain) {
235
+ chain.branches.push({ cond: vIf.name === 'else' ? null : expr(vIf.exp.content, loops), body: [node] });
236
+ if (vIf.name === 'else')
237
+ chain = null;
238
+ }
239
+ continue;
240
+ }
241
+ chain = null;
242
+ out.push(node);
243
+ }
244
+ return out;
245
+ };
246
+ const element = (c, loops) => {
247
+ const attrs = [];
248
+ const events = [];
249
+ for (const p of c.props) {
250
+ if (p.type === 6) {
251
+ if (p.name !== 'key')
252
+ attrs.push({ name: p.name, value: p.value?.content ?? '' });
253
+ continue;
254
+ }
255
+ if (p.name === 'bind' && p.arg) {
256
+ if (p.arg.content !== 'key')
257
+ attrs.push({ name: p.arg.content, method: expr(p.exp.content, loops) });
258
+ continue;
259
+ }
260
+ if (p.name === 'on' && p.arg) {
261
+ events.push({ name: p.arg.content, method: handler(p.exp.content, loops) });
262
+ continue;
263
+ }
264
+ if (p.name === 'model') {
265
+ const model = core.MODELS[c.tag];
266
+ if (!model)
267
+ throw new Error(`${path}: v-model on <${c.tag}>`);
268
+ attrs.push({ name: model.prop, method: expr(p.exp.content, loops) });
269
+ events.push({ name: model.event, method: handler(`${p.exp.content} = $event.value as ${model.type}`, loops) });
270
+ }
271
+ }
272
+ if (components.has(c.tag))
273
+ return { kind: 'component', name: c.tag, props: attrs, events };
274
+ // Vue's mountElement sets `value` after the other props (a maximum before the value it bounds).
275
+ const value = attrs.findIndex((a) => a.name === 'value');
276
+ if (value >= 0)
277
+ attrs.push(...attrs.splice(value, 1));
278
+ if (!core.ELEMENTS.has(c.tag))
279
+ throw new Error(`${path}: <${c.tag}> is not a @nativescript/core element the release build knows`);
280
+ if (c.tag === 'ListView')
281
+ return { kind: 'element', tag: c.tag, attrs, events, children: listTemplates(c, attrs, loops) };
282
+ return { kind: 'element', tag: c.tag, attrs, events, children: nodes(c.children, loops) };
283
+ };
284
+ /**
285
+ * `<ListView :items>` with `<template #name="{ item, index }">` slots, as nativescript-vue renders them.
286
+ * Its `itemTemplateSelector` is called with the row's `{ item, index, even, odd }` and returns a slot name.
287
+ */
288
+ const listTemplates = (c, attrs, loops) => {
289
+ const items = attrs.find((a) => a.name === 'items');
290
+ if (!items || !('method' in items))
291
+ throw new Error(`${path}: <ListView> needs :items`);
292
+ const row = `${items.method}(${args(loops).join(', ')})[0]`;
293
+ const at = attrs.findIndex((a) => a.name === 'itemTemplateSelector');
294
+ if (at >= 0) {
295
+ const selector = c.props.find((p) => p.type === 7 && p.name === 'bind' && p.arg?.content === 'itemTemplateSelector');
296
+ const m = `$b${next++}`;
297
+ const p = [params(loops), `$item = this.${row}`, '$index = 0'].filter(Boolean).join(', ');
298
+ members.push(` ${m}(${p}): string { return ${core.rewrite(preprocess(selector.exp.content), withLoops(inTemplate, loops))}({ item: $item, index: $index, even: $index % 2 === 0, odd: $index % 2 !== 0 }); }`);
299
+ attrs[at] = { name: 'itemTemplateSelector', method: m };
300
+ }
301
+ const out = [];
302
+ for (const t of c.children) {
303
+ if (t.type !== 1)
304
+ continue;
305
+ const slot = t.props.find((p) => p.type === 7 && p.name === 'slot');
306
+ if (t.tag !== 'template' || !slot)
307
+ throw new Error(`${path}: a ListView's children are <template #name="{ item }"> slots`);
308
+ const vars = new Map();
309
+ for (const part of (slot.exp?.content ?? '').replace(/^\s*\{|\}\s*$/g, '').split(',')) {
310
+ const [k, alias] = part.split(':').map((x) => x.trim());
311
+ if (k)
312
+ vars.set(k, alias || k);
313
+ }
314
+ for (const k of vars.keys())
315
+ if (k !== 'item' && k !== 'index')
316
+ throw new Error(`${path}: a ListView slot's "${k}" is not supported in a release build yet`);
317
+ const item = vars.get('item') ?? `$item${loops.length}`;
318
+ const index = vars.get('index') ?? `$i${loops.length}`;
319
+ const loop = { item, index, param: `${item} = this.${row}, ${index} = 0` };
320
+ out.push({ kind: 'template', key: slot.arg?.content ?? 'default', item, index, body: nodes(t.children, [...loops, loop]) });
321
+ }
322
+ return out;
323
+ };
324
+ const template = nodes(descriptor.template?.ast?.children ?? [], []);
325
+ return { members, template };
326
+ }
327
+ function withLoops(scope, loops) {
328
+ const names = new Map(scope.names);
329
+ // A loop variable shadows a binding of the same name.
330
+ for (const l of loops) {
331
+ names.delete(l.item);
332
+ names.delete(l.index);
333
+ }
334
+ return { names, unwrapValue: scope.unwrapValue };
335
+ }
336
+ const PROP_TYPES = { String: 'string', Number: 'number', Boolean: 'boolean' };
337
+ /** nativescript-vue's instance methods, called on `this` in the Options API. */
338
+ const INSTANCE_GLOBALS = new Set(['$navigateTo', '$navigateBack', '$showModal', '$closeModal']);
339
+ /**
340
+ * A component written with the Options API (`export default defineComponent({ props, emits, data,
341
+ * computed, methods, watch })`, or `setup()` returning its bindings) as a virtual class: data are
342
+ * refs, computed properties getters, and `this.x` reads a ref's value, as Vue's instance proxy does.
343
+ */
344
+ function vueOptions(path, descriptor) {
345
+ const name = basename(path, '.vue');
346
+ const script = descriptor.script.content;
347
+ const sf = ts.createSourceFile(path + '.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
348
+ const b = bindings(path);
349
+ let options;
350
+ for (const st of sf.statements) {
351
+ if (ts.isImportDeclaration(st))
352
+ continue;
353
+ if (ts.isExportAssignment(st) && !st.isExportEquals) {
354
+ const e = st.expression;
355
+ if (ts.isObjectLiteralExpression(e))
356
+ options = e;
357
+ else if (ts.isCallExpression(e) && ts.isIdentifier(e.expression) && e.expression.text === 'defineComponent' && e.arguments[0] && ts.isObjectLiteralExpression(e.arguments[0]))
358
+ options = e.arguments[0];
359
+ else
360
+ throw new Error(`${path}: export default needs an options object or defineComponent({ … })`);
361
+ continue;
362
+ }
363
+ throw new Error(`${path}: unsupported top-level statement in <script>: ${st.getText().slice(0, 60)}`);
364
+ }
365
+ if (!options)
366
+ throw new Error(`${path}: no export default component`);
367
+ for (const st of sf.statements)
368
+ if (ts.isImportDeclaration(st))
369
+ importOf(b, st);
370
+ const option = (key) => options.properties.find((p) => p.name && ts.isIdentifier(p.name) && p.name.text === key);
371
+ for (const p of options.properties) {
372
+ const key = p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) ? p.name.text : '';
373
+ if (!['name', 'components', 'props', 'emits', 'data', 'computed', 'methods', 'watch', 'setup'].includes(key))
374
+ throw new Error(`${path}: the "${key || p.getText().slice(0, 30)}" option is not supported in a release build yet`);
375
+ }
376
+ const object = (key) => {
377
+ const p = option(key);
378
+ if (!p)
379
+ return undefined;
380
+ if (ts.isPropertyAssignment(p) && ts.isObjectLiteralExpression(p.initializer))
381
+ return p.initializer;
382
+ throw new Error(`${path}: the ${key} option needs an object`);
383
+ };
384
+ const methodOf = (p, what) => {
385
+ if (ts.isMethodDeclaration(p) && p.body)
386
+ return p;
387
+ throw new Error(`${path}: ${what} "${p.name?.getText()}" needs to be a method`);
388
+ };
389
+ // Props: `{ recipe: { type: Object as PropType<Recipe>, required: true }, size: Number }`.
390
+ const optional = [];
391
+ for (const p of object('props')?.properties ?? []) {
392
+ if (!ts.isPropertyAssignment(p))
393
+ throw new Error(`${path}: prop ${p.getText().slice(0, 40)}`);
394
+ const prop = p.name.getText();
395
+ const spec = p.initializer;
396
+ const field = (k) => ts.isObjectLiteralExpression(spec) ? spec.properties.find((q) => ts.isPropertyAssignment(q) && q.name.getText() === k)?.initializer : undefined;
397
+ const typeOf = (e) => {
398
+ if (!e)
399
+ throw new Error(`${path}: prop "${prop}" needs a type`);
400
+ if (ts.isAsExpression(e) && ts.isTypeReferenceNode(e.type) && e.type.typeName.getText() === 'PropType' && e.type.typeArguments?.[0])
401
+ return e.type.typeArguments[0].getText();
402
+ if (ts.isIdentifier(e) && PROP_TYPES[e.text])
403
+ return PROP_TYPES[e.text];
404
+ throw new Error(`${path}: prop "${prop}" needs a type a release build can read (String, Number, Boolean or X as PropType<T>)`);
405
+ };
406
+ const type = typeOf(ts.isObjectLiteralExpression(spec) ? field('type') : spec);
407
+ const required = field('required')?.kind === ts.SyntaxKind.TrueKeyword;
408
+ if (field('default'))
409
+ throw new Error(`${path}: a default for prop "${prop}" is not supported in a release build yet`);
410
+ // An absent Boolean prop is false in Vue, not undefined.
411
+ if (!required && type === 'boolean')
412
+ throw new Error(`${path}: Boolean prop "${prop}" needs required: true in a release build`);
413
+ b.props.push(prop);
414
+ if (!required)
415
+ optional.push(prop);
416
+ b.fields.push(` ${prop}${required ? '!' : '?'}: ${type};`);
417
+ b.inTemplate.names.set(prop, `this.${prop}`);
418
+ }
419
+ // Emits: `['select']`, or `{ select: null, change: (value: number) => true }` whose validators type the payload.
420
+ const emits = new Map();
421
+ const emitsOption = option('emits');
422
+ if (emitsOption) {
423
+ if (!ts.isPropertyAssignment(emitsOption))
424
+ throw new Error(`${path}: emits`);
425
+ const e = emitsOption.initializer;
426
+ if (ts.isArrayLiteralExpression(e))
427
+ for (const n of e.elements)
428
+ emits.set(n.text, '');
429
+ else if (ts.isObjectLiteralExpression(e)) {
430
+ for (const q of e.properties) {
431
+ const v = ts.isPropertyAssignment(q) ? q.initializer : undefined;
432
+ const param = v && (ts.isArrowFunction(v) || ts.isFunctionExpression(v)) ? v.parameters[0] : undefined;
433
+ emits.set(q.name.getText(), param ? param.type?.getText() ?? 'any' : '');
434
+ }
435
+ }
436
+ else
437
+ throw new Error(`${path}: emits needs an array or an object`);
438
+ }
439
+ const allCode = script + (descriptor.template?.content ?? '');
440
+ const outputFields = {};
441
+ for (const [event, declared] of emits) {
442
+ // An event emitted with a payload passes it on; one emitted bare is `void`.
443
+ const payload = declared || (new RegExp(`emit\\(\\s*['"]${event}['"]\\s*,`).test(allCode) ? 'any' : 'void');
444
+ outputFields[event] = `$emit_${event}`;
445
+ b.fields.push(` readonly $emit_${event} = output<${payload}>();`);
446
+ }
447
+ /** `$emit('select', x)` and `emit('select', x)`: the event's emitter. */
448
+ const emitCall = (code, emitName) => code.replace(new RegExp(`(?<![\\w.$])(?:this\\.)?${emitName.replace(/\$/g, '\\$')}\\(\\s*['"]([\\w-]+)['"]\\s*(,\\s*)?`, 'g'), (_, event) => {
449
+ if (!emits.has(event))
450
+ throw new Error(`${path}: emits "${event}", which the emits option does not declare`);
451
+ return `this.$emit_${event}.emit(`;
452
+ });
453
+ // `this.x` reads a data property or a ref `setup()` returned by its value.
454
+ const refs = new Set();
455
+ const thisCode = (code, kind) => {
456
+ const wrapped = kind === 'expression' ? `(${code})` : code;
457
+ const file = ts.createSourceFile('snippet.ts', wrapped, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
458
+ const edits = [];
459
+ const visit = (n) => {
460
+ if (ts.isPropertyAccessExpression(n) && n.expression.kind === ts.SyntaxKind.ThisKeyword) {
461
+ const k = n.name.text;
462
+ if (refs.has(k))
463
+ edits.push({ start: n.getStart(), end: n.getEnd(), text: `this.${k}.value` });
464
+ else if (INSTANCE_GLOBALS.has(k)) {
465
+ edits.push({ start: n.getStart(), end: n.getEnd(), text: k });
466
+ globals.add(k);
467
+ }
468
+ else if (k.startsWith('$') && k !== '$emit')
469
+ throw new Error(`${path}: this.${k} is not supported in a release build yet`);
470
+ return;
471
+ }
472
+ ts.forEachChild(n, visit);
473
+ };
474
+ visit(file);
475
+ let out = wrapped;
476
+ for (const e of edits.sort((x, y) => y.start - x.start))
477
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
478
+ return emitCall(out, '$emit');
479
+ };
480
+ const globals = new Set();
481
+ // setup(props, { emit }): its statements are bindings, as in <script setup>; what it returns, the template reads.
482
+ const setup = option('setup');
483
+ let setupEmit = '';
484
+ if (setup) {
485
+ const m = methodOf(setup, 'setup');
486
+ const [propsParam, context] = m.parameters;
487
+ if (propsParam)
488
+ b.propsName = propsParam.name.text;
489
+ if (context) {
490
+ if (!ts.isObjectBindingPattern(context.name))
491
+ throw new Error(`${path}: setup's context needs destructuring ({ emit })`);
492
+ for (const e of context.name.elements) {
493
+ if ((e.propertyName ?? e.name).getText() !== 'emit')
494
+ throw new Error(`${path}: setup's ${e.getText()} is not supported in a release build yet`);
495
+ setupEmit = e.name.getText();
496
+ }
497
+ }
498
+ const statements = m.body.statements;
499
+ for (const st of statements) {
500
+ if (ts.isReturnStatement(st)) {
501
+ if (st !== statements.at(-1) || !st.expression || !ts.isObjectLiteralExpression(st.expression))
502
+ throw new Error(`${path}: setup() needs to end returning an object of its bindings`);
503
+ for (const r of st.expression.properties)
504
+ if (!ts.isShorthandPropertyAssignment(r))
505
+ throw new Error(`${path}: setup() returns ${r.getText()}; return bindings by name ({ color, select })`);
506
+ continue;
507
+ }
508
+ const source = setupEmit ? ts.createSourceFile('st.ts', emitCall(st.getText(), setupEmit), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS).statements[0] : st;
509
+ if (!binding(b, source))
510
+ throw new Error(`${path}: unsupported statement in setup(): ${st.getText().slice(0, 60)}`);
511
+ }
512
+ for (const [k, v] of b.inTemplate.names)
513
+ if (v === `this.${k}.value`)
514
+ refs.add(k);
515
+ }
516
+ const data = option('data');
517
+ const dataFields = [];
518
+ if (data) {
519
+ const fn = ts.isMethodDeclaration(data) ? data : ts.isPropertyAssignment(data) && (ts.isArrowFunction(data.initializer) || ts.isFunctionExpression(data.initializer)) ? data.initializer : undefined;
520
+ const body = fn?.body;
521
+ const returned = body && (ts.isBlock(body) ? body.statements.length === 1 && ts.isReturnStatement(body.statements[0]) ? body.statements[0].expression : undefined : ts.isParenthesizedExpression(body) ? body.expression : body);
522
+ if (!returned || !ts.isObjectLiteralExpression(returned))
523
+ throw new Error(`${path}: data() needs to return an object literal`);
524
+ for (const q of returned.properties) {
525
+ if (!ts.isPropertyAssignment(q))
526
+ throw new Error(`${path}: data property ${q.getText()}`);
527
+ const key = q.name.getText();
528
+ refs.add(key);
529
+ b.inTemplate.names.set(key, `this.${key}.value`);
530
+ dataFields.push({ key, init: q.initializer.getText() });
531
+ }
532
+ }
533
+ for (const p of object('computed')?.properties ?? []) {
534
+ const k = p.name.getText();
535
+ b.inTemplate.names.set(k, `this.${k}`);
536
+ }
537
+ for (const p of object('methods')?.properties ?? []) {
538
+ const m = methodOf(p, 'method');
539
+ const k = m.name.getText();
540
+ b.arity.set(k, m.parameters.length);
541
+ b.inTemplate.names.set(k, `this.${k}`);
542
+ }
543
+ if (b.propsName)
544
+ b.inScript.names.set(b.propsName, 'this');
545
+ for (const f of b.later)
546
+ f();
547
+ for (const d of dataFields)
548
+ b.fields.push(` ${d.key} = $ref(${thisCode(d.init, 'expression')});`);
549
+ const method = (m, name = m.name.getText()) => {
550
+ const async = ts.getModifiers(m)?.some((x) => x.kind === ts.SyntaxKind.AsyncKeyword) ? 'async ' : '';
551
+ return ` ${async}${name}(${m.parameters.map((p) => p.getText()).join(', ')})${m.type ? `: ${m.type.getText()}` : ''} ${thisCode(m.body.getText(), 'statements')}`;
552
+ };
553
+ for (const p of object('computed')?.properties ?? []) {
554
+ const m = methodOf(p, 'computed property');
555
+ b.fields.push(` get ${m.name.getText()}()${m.type ? `: ${m.type.getText()}` : ''} ${thisCode(m.body.getText(), 'statements')}`);
556
+ }
557
+ for (const p of object('methods')?.properties ?? [])
558
+ b.fields.push(method(methodOf(p, 'method')));
559
+ // watch: { key(value, old) {…} } or { key: { handler(value, old) {…}, immediate } }, in declaration order.
560
+ const watchers = [];
561
+ for (const p of object('watch')?.properties ?? []) {
562
+ const key = p.name.getText().replace(/^['"]|['"]$/g, '');
563
+ let handler;
564
+ let immediate = false;
565
+ if (ts.isMethodDeclaration(p))
566
+ handler = methodOf(p, 'watcher');
567
+ else if (ts.isPropertyAssignment(p) && ts.isObjectLiteralExpression(p.initializer)) {
568
+ const h = p.initializer.properties.find((q) => q.name?.getText() === 'handler');
569
+ if (!h)
570
+ throw new Error(`${path}: watcher "${key}" needs a handler`);
571
+ handler = methodOf(h, 'watcher');
572
+ for (const q of p.initializer.properties) {
573
+ if (q === h)
574
+ continue;
575
+ const v = ts.isPropertyAssignment(q) ? q.initializer.kind : null;
576
+ if (q.name?.getText() === 'immediate' && (v === ts.SyntaxKind.TrueKeyword || v === ts.SyntaxKind.FalseKeyword))
577
+ immediate = v === ts.SyntaxKind.TrueKeyword;
578
+ else
579
+ throw new Error(`${path}: watcher option ${q.getText()} is not supported in a release build yet`);
580
+ }
581
+ }
582
+ else
583
+ throw new Error(`${path}: watcher "${key}" needs a method or { handler }`);
584
+ const n = watchers.length;
585
+ const [first, ...rest] = key.split('.');
586
+ const read = refs.has(first) ? `this.${first}.value` : `this.${first}`;
587
+ b.fields.push(` $ws${n}() { return ${[read, ...rest].join('.')}; }`);
588
+ if (handler.parameters.length > 2)
589
+ throw new Error(`${path}: watcher "${key}" takes (value, old)`);
590
+ // The old value is undefined on an immediate watcher's first call.
591
+ const params = handler.parameters.map((q, i) => (i === 1 && !q.questionToken && q.type ? `${q.name.getText()}?: ${q.type.getText()}` : q.getText()));
592
+ b.fields.push(` $wh${n}(${params.join(', ')}) ${thisCode(handler.body.getText(), 'statements')}`);
593
+ watchers.push({ source: `$ws${n}`, handler: `$wh${n}`, arity: handler.parameters.length, immediate });
594
+ }
595
+ for (const [event] of emits)
596
+ b.inTemplate.names.set(`$emit_${event}`, `this.$emit_${event}`);
597
+ const { members, template } = vueTemplate(path, descriptor, b, (code) => emitCall(code, '$emit'));
598
+ for (const g of globals)
599
+ if (!b.imports.some((i) => i.includes(g)))
600
+ b.imports.push(`import { ${g} } from 'nativescript-vue';`);
601
+ const preamble = emits.size ? [`import { output } from '@nativescript/release';`] : [];
602
+ const { styles, scope } = vueStyles(path, descriptor);
603
+ return { name, file: path + '.ts', source: classSource(name, descriptor, b, members, preamble), props: b.props, optional: optional.length ? optional : undefined, template: scope ? core.scopeTemplate(template, scope) : template, styles, outputs: emits.size ? [...emits.keys()] : undefined, outputFields: emits.size ? outputFields : undefined, watchers: watchers.length ? watchers : undefined };
604
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@nstudio/nativescript-compiler-vue",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "9.2.0-alpha.9",
4
+ "description": "The Vue adapter of @nstudio/nativescript-compiler: compiles a NativeScript app written with Vue into a native iOS or Android app with no JavaScript runtime.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "source": "./index.ts",
9
+ "default": "./dist/index.js"
10
+ },
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "dist/"
15
+ ],
16
+ "scripts": {
17
+ "build": "ns-compiled-adapter build .",
18
+ "prepack": "npm run build"
19
+ },
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/nstudio/nativescript-compiler.git",
24
+ "directory": "packages/vue"
25
+ },
26
+ "dependencies": {
27
+ "@vue/compiler-sfc": "^3.5.0"
28
+ },
29
+ "peerDependencies": {
30
+ "@nstudio/nativescript-compiler": "9.2.0-alpha.9"
31
+ },
32
+ "nativescript": {
33
+ "compilerAdapter": {
34
+ "apiVersion": 1,
35
+ "detect": {
36
+ "priority": 60,
37
+ "dependencies": [
38
+ "nativescript-vue",
39
+ "vue"
40
+ ],
41
+ "entryMentions": [
42
+ "nativescript-vue"
43
+ ],
44
+ "entryImports": [
45
+ "vue"
46
+ ]
47
+ },
48
+ "testedVersions": {
49
+ "nativescript-vue": ">=3.1.0 <4.0.0"
50
+ }
51
+ }
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ }
56
+ }