@nstudio/nativescript-compiler-angular 0.0.0-stage → 9.2.0-alpha.10
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 +19 -0
- package/README.md +27 -2
- package/dist/angular-libraries.js +173 -0
- package/dist/angular.js +2938 -0
- package/dist/component-bases.js +746 -0
- package/dist/core-api.js +8 -0
- package/dist/entry.js +120 -0
- package/dist/index.js +165 -0
- package/dist/kotlin.js +293 -0
- package/dist/modules.js +700 -0
- package/dist/ng-modules.js +66 -0
- package/dist/package.js +15 -0
- package/dist/refusals.js +5 -0
- package/dist/semantics.js +262 -0
- package/dist/swift.js +352 -0
- package/kit-android/fromcore/AngularAPI.kt +175 -0
- package/kit-android/fromcore/AngularRouter.kt +617 -0
- package/kit-android/main/AngularChangeDetection.kt +530 -0
- package/kit-android/main/AngularCore.kt +685 -0
- package/kit-android/main/AngularHttp.kt +431 -0
- package/kit-android/main/AngularRouterValues.kt +154 -0
- package/kit-android/main/AngularRx.kt +224 -0
- package/kit-apple/AngularAPI.swift +224 -0
- package/kit-apple/AngularChangeDetection.swift +510 -0
- package/kit-apple/AngularCore.swift +764 -0
- package/kit-apple/AngularHttp.swift +467 -0
- package/kit-apple/AngularRouter.swift +655 -0
- package/kit-apple/AngularRouterValues.swift +285 -0
- package/kit-apple/AngularRx.swift +246 -0
- package/kit-apple/kit-index.json +763 -0
- package/package.json +56 -4
- package/runtime/angular-forms.ts +3099 -0
- package/runtime/angular-rx.ts +550 -0
- package/runtime/angular.ts +826 -0
package/dist/swift.js
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { core, ts } from "./core-api.js";
|
|
2
|
+
import { ngModuleDef, standaloneImports } from "./ng-modules.js";
|
|
3
|
+
import { KIT_TOKENS, angularCall, forwardRefTarget, injectableRole, injectableShared, injected, isInjectableClass, isLinkedSignalPreviousSource, model, parameterDecorators } from "./semantics.js";
|
|
4
|
+
/** An injection token's name: a framework class by the name it is declared with (`NativeDialog` is `NativeDialogService`), or a compiled class by its emitted name. */
|
|
5
|
+
function tokenName(t, e) {
|
|
6
|
+
const decl = t.resolve(e)?.declarations?.[0];
|
|
7
|
+
if (decl && ts.isClassDeclaration(decl) && decl.name) {
|
|
8
|
+
return decl.getSourceFile().isDeclarationFile ? decl.name.text : t.topName(decl, decl.name.text);
|
|
9
|
+
}
|
|
10
|
+
return e.getText();
|
|
11
|
+
}
|
|
12
|
+
/** What `inject(token)` gives at `at`; a ViewContainerRef has no instance whose views would attach to the component's. */
|
|
13
|
+
function injectedToken(t, token, at, decl) {
|
|
14
|
+
if (token === 'ViewContainerRef')
|
|
15
|
+
throw t.error(at, 'an injected ViewContainerRef', 'view-container-ref');
|
|
16
|
+
return injected('swift', token, at, decl && ts.isClassDeclaration(decl) ? injectableShared(decl, t.pluginFiles, t.checker) : undefined);
|
|
17
|
+
}
|
|
18
|
+
/** A class only a library's typings declare has no instance in a release build: the library's JavaScript provides it. */
|
|
19
|
+
function refuseTypingsOnlyToken(t, tokenDecl, token, at) {
|
|
20
|
+
if (tokenDecl && ts.isClassDeclaration(tokenDecl) && tokenDecl.getSourceFile().isDeclarationFile && !core.isCoreDeclaration(tokenDecl))
|
|
21
|
+
throw t.error(at, `an injected class only a library's typings declare (${token})`, 'library-injectable');
|
|
22
|
+
}
|
|
23
|
+
function parameterInject(t, p) {
|
|
24
|
+
const { swift } = core;
|
|
25
|
+
const pt = t.typeOf(p.name);
|
|
26
|
+
const { token: given, optional, skipSelf } = parameterDecorators(p);
|
|
27
|
+
if (optional && skipSelf)
|
|
28
|
+
return swift.isOptional(pt) || pt.endsWith('!') || pt === 'Any?' ? 'nil' : t.fromAny('nil', pt);
|
|
29
|
+
const injectArg = given && forwardRefTarget(given);
|
|
30
|
+
if (injectArg) {
|
|
31
|
+
const target = ts.isExpressionWithTypeArguments(injectArg) ? injectArg.expression : injectArg;
|
|
32
|
+
const token = tokenName(t, target);
|
|
33
|
+
if (token === 'NATIVE_DIALOG_DATA')
|
|
34
|
+
return t.fromAny('NativeDialogRef.current.data', pt);
|
|
35
|
+
const tokenDecl = t.resolve(target)?.declarations?.[0];
|
|
36
|
+
if (KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles)) {
|
|
37
|
+
const throws = token === 'Page' || (token === 'ActivatedRoute' && core.adapterRuntimeFile(tokenDecl?.getSourceFile().fileName) === 'runtime/angular-rx.ts') || (tokenDecl && ts.isClassDeclaration(tokenDecl) && core.adapterRuntimeFile(tokenDecl.getSourceFile().fileName) !== 'runtime/angular-rx.ts' && t.throwsInfo.initThrows(tokenDecl));
|
|
38
|
+
return swift.tryIf(throws, injectedToken(t, token, p, tokenDecl));
|
|
39
|
+
}
|
|
40
|
+
refuseTypingsOnlyToken(t, tokenDecl, token, p);
|
|
41
|
+
const raw = `Injector.inject(${t.coerce(injectArg, 'Any?')}${optional ? ', JSObject([("optional", true)])' : ''})`;
|
|
42
|
+
return pt === 'Any?' ? raw : t.fromAny(raw, pt);
|
|
43
|
+
}
|
|
44
|
+
const ref = p.type && ts.isTypeReferenceNode(p.type)
|
|
45
|
+
? p.type
|
|
46
|
+
: p.type && ts.isUnionTypeNode(p.type)
|
|
47
|
+
? p.type.types.find(ts.isTypeReferenceNode)
|
|
48
|
+
: undefined;
|
|
49
|
+
if (ref) {
|
|
50
|
+
const token = tokenName(t, ref.typeName);
|
|
51
|
+
const tokenDecl = t.resolve(ref.typeName)?.declarations?.[0];
|
|
52
|
+
if (KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles)) {
|
|
53
|
+
const throws = token === 'Page' || (token === 'ActivatedRoute' && core.adapterRuntimeFile(tokenDecl?.getSourceFile().fileName) === 'runtime/angular-rx.ts') || (tokenDecl && ts.isClassDeclaration(tokenDecl) && core.adapterRuntimeFile(tokenDecl.getSourceFile().fileName) !== 'runtime/angular-rx.ts' && t.throwsInfo.initThrows(tokenDecl));
|
|
54
|
+
return swift.tryIf(throws, injectedToken(t, token, p, tokenDecl));
|
|
55
|
+
}
|
|
56
|
+
if (tokenDecl && ts.isClassDeclaration(tokenDecl)) {
|
|
57
|
+
refuseTypingsOnlyToken(t, tokenDecl, token, p);
|
|
58
|
+
const raw = `Injector.inject(${token}.self${optional ? ', JSObject([("optional", true)])' : ''})`;
|
|
59
|
+
return pt === 'Any?' ? raw : t.fromAny(raw, pt);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
/** `inject(token)` and `injector.get(token)`: a kit token's instance or the app's service, else what the injector gives. */
|
|
65
|
+
function injection(t, call, given, made) {
|
|
66
|
+
const rawArg0 = forwardRefTarget(given);
|
|
67
|
+
const target = ts.isExpressionWithTypeArguments(rawArg0) ? rawArg0.expression : rawArg0;
|
|
68
|
+
const token = tokenName(t, target);
|
|
69
|
+
if (token === 'NATIVE_DIALOG_DATA')
|
|
70
|
+
return t.fromAny('NativeDialogRef.current.data', t.typeOf(call));
|
|
71
|
+
const tokenDecl = t.resolve(target)?.declarations?.[0];
|
|
72
|
+
if (KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles))
|
|
73
|
+
return injectedToken(t, token, call, tokenDecl);
|
|
74
|
+
refuseTypingsOnlyToken(t, tokenDecl, token, call);
|
|
75
|
+
const raw = made(t.coerce(rawArg0, 'Any?'));
|
|
76
|
+
const type = t.typeOf(call);
|
|
77
|
+
return type === 'Any?' ? raw : t.fromAny(raw, type);
|
|
78
|
+
}
|
|
79
|
+
/** `linkedSignal({ source, computation })`: `computation`'s `previous` is the runtime's pair made the parameter's object. */
|
|
80
|
+
function linkedSignal(t, options, type, equals) {
|
|
81
|
+
const prop = (n) => {
|
|
82
|
+
const p = options.properties.find((q) => q.name && ts.isIdentifier(q.name) && q.name.text === n);
|
|
83
|
+
if (!p)
|
|
84
|
+
return undefined;
|
|
85
|
+
if (ts.isPropertyAssignment(p))
|
|
86
|
+
return p.initializer;
|
|
87
|
+
if (ts.isShorthandPropertyAssignment(p))
|
|
88
|
+
return p.name;
|
|
89
|
+
throw t.error(p, `a \`${n}\` of linkedSignal's options other than a property`);
|
|
90
|
+
};
|
|
91
|
+
const source = prop('source'), computation = prop('computation');
|
|
92
|
+
if (!source || !computation)
|
|
93
|
+
throw t.error(options, 'linkedSignal options without both `source` and `computation`');
|
|
94
|
+
const c = t.checker;
|
|
95
|
+
const sig = c.getResolvedSignature(options.parent);
|
|
96
|
+
const opts = c.getTypeOfSymbol(sig.parameters[0]);
|
|
97
|
+
const s = t.type(c.getTypeOfSymbol(c.getPropertyOfType(opts, 'source')).getCallSignatures()[0].getReturnType(), options);
|
|
98
|
+
const compSig = c.getTypeOfSymbol(c.getPropertyOfType(opts, 'computation')).getCallSignatures()[0];
|
|
99
|
+
const compActual = c.getTypeAtLocation(computation).getCallSignatures()[0];
|
|
100
|
+
const takesPrevious = (compActual?.parameters.length ?? 2) > 1;
|
|
101
|
+
const prevParam = takesPrevious ? (compActual?.parameters[1] ?? compSig.parameters[1]) : undefined;
|
|
102
|
+
const prevObj = prevParam ? c.getNonNullableType(c.getTypeOfSymbol(prevParam)) : undefined;
|
|
103
|
+
const prevType = prevObj ? t.type(prevObj, options) : undefined;
|
|
104
|
+
const sourceProp = prevObj?.getProperty('source');
|
|
105
|
+
const sourceDecl = sourceProp?.valueDeclaration ?? sourceProp?.declarations?.[0];
|
|
106
|
+
const sourceOpt = !!(sourceProp && (sourceProp.flags & ts.SymbolFlags.Optional)) || (!!sourceDecl && (ts.isPropertySignature(sourceDecl) || ts.isPropertyDeclaration(sourceDecl)) && isLinkedSignalPreviousSource(sourceDecl, c)) || core.swift.isOptional(s);
|
|
107
|
+
const pSource = core.swift.isOptional(s) ? '(p.source ?? nil)' : 'p.source';
|
|
108
|
+
const read = t.symbolName(source) === 'WritableSignal' || t.symbolName(source) === 'Signal' ? `{ () throws -> ${s} in ${t.signalRead(source)} }` : t.expr(source);
|
|
109
|
+
const made = prevType && /^Object_\w+$/.test(prevType)
|
|
110
|
+
? sourceOpt
|
|
111
|
+
? `${prevType}(source: ${pSource}, value: p.value)`
|
|
112
|
+
: t.fromAnyCode(`JSObject([("source", ${pSource}), ("value", p.value)])`, prevType)
|
|
113
|
+
: `JSObject([("source", ${pSource}), ("value", p.value)])`;
|
|
114
|
+
return `Signal<${type}>(source: ${read}, computation: { (s: ${s}, previous: (source: ${s}?, value: ${type})?) throws -> ${type} in try (${t.expr(computation)})(s${prevType ? `, previous.map { p in ${made} }` : ''}) }${equals})`;
|
|
115
|
+
}
|
|
116
|
+
/** Whether a `linkedSignal(…)` call resolves to the overload taking `{ source, computation }` rather than a function. */
|
|
117
|
+
function linkedOptionsOverload(t, e) {
|
|
118
|
+
const first = t.checker.getResolvedSignature(e)?.parameters[0];
|
|
119
|
+
return !!first && t.checker.getTypeOfSymbol(first).getCallSignatures().length === 0;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* `linkedSignal(options)` with options other than a literal: `source`, `computation` and `equal` read by name once, as
|
|
123
|
+
* the signal is made, as Angular reads them. `previous` is made the type the options' own `computation` declares, which
|
|
124
|
+
* is what the function held there takes.
|
|
125
|
+
*/
|
|
126
|
+
function linkedSignalOptions(t, options, type, reference) {
|
|
127
|
+
const c = t.checker;
|
|
128
|
+
const sig = c.getResolvedSignature(options.parent);
|
|
129
|
+
const opts = c.getTypeOfSymbol(sig.parameters[0]);
|
|
130
|
+
const s = t.type(c.getTypeOfSymbol(c.getPropertyOfType(opts, 'source')).getCallSignatures()[0].getReturnType(), options);
|
|
131
|
+
const held = c.getPropertyOfType(c.getNonNullableType(c.getTypeAtLocation(options)), 'computation');
|
|
132
|
+
const prevParam = held && c.getNonNullableType(c.getTypeOfSymbol(held)).getCallSignatures()[0]?.parameters[1];
|
|
133
|
+
const prevType = prevParam ? t.type(c.getNonNullableType(c.getTypeOfSymbol(prevParam)), options) : 'Any?';
|
|
134
|
+
const pSource = core.swift.isOptional(s) ? '(p.source ?? nil)' : 'p.source';
|
|
135
|
+
const previous = t.fromAnyCode(`JSObject([("source", ${pSource}), ("value", p.value)])`, prevType);
|
|
136
|
+
const fallback = reference ? 'jsSame(a, b)' : core.swift.isFunctionType(type) ? 'false' : 'a == b';
|
|
137
|
+
const equal = `jsEqualOption(__o, default: { (a: ${type}, b: ${type}) -> Bool in ${fallback} })`;
|
|
138
|
+
return `{ (__o: Any?) -> Signal<${type}> in let __source = (try? jsGet(__o, "source")) ?? nil; let __computation = (try? jsGet(__o, "computation")) ?? nil; `
|
|
139
|
+
+ `return Signal<${type}>(source: { () throws -> ${s} in let v = try jsCall(__source); return ${t.fromAnyCode('v', s)} }, `
|
|
140
|
+
+ `computation: { (s: ${s}, previous: (source: ${s}?, value: ${type})?) throws -> ${type} in let p: Any? = previous.map { p in ${previous} }; let v = try jsCall(__computation, s, p); return ${t.fromAnyCode('v', type)} }, `
|
|
141
|
+
+ `equals: ${c.getNonNullableType(c.getTypeAtLocation(options)).getProperty('equal') ? equal : `jsReportingEquals(${equal})`}) }(${t.coerce(options, 'Any?')})`;
|
|
142
|
+
}
|
|
143
|
+
function globalCall(t, name, e, decl, lib) {
|
|
144
|
+
const arg = (k) => e.arguments[k];
|
|
145
|
+
const { swift } = core;
|
|
146
|
+
if (name === 'linkedSignal' && lib) {
|
|
147
|
+
const type = t.typeOf(e).replace(/^Signal<(.*)>$/, '$1');
|
|
148
|
+
const reference = !['Double', 'String', 'Bool'].includes(type.replace(/\?$/, '')) && !swift.isFunctionType(type);
|
|
149
|
+
const options = arg(0) && ts.isObjectLiteralExpression(ts.skipOuterExpressions(arg(0))) ? ts.skipOuterExpressions(arg(0)) : undefined;
|
|
150
|
+
const fallback = reference ? ', equals: { jsSame($0, $1) }' : '';
|
|
151
|
+
if (!options && linkedOptionsOverload(t, e))
|
|
152
|
+
return linkedSignalOptions(t, arg(0), type, reference);
|
|
153
|
+
if (!options)
|
|
154
|
+
return `Signal<${type}>(linked: ${t.expr(arg(0))}${t.equalsArg(arg(1), type) ?? fallback})`;
|
|
155
|
+
return linkedSignal(t, options, type, t.equalsArg(options, type) ?? (reference ? fallback : ', equals: { $0 == $1 }'));
|
|
156
|
+
}
|
|
157
|
+
if (name === 'computed' && angularCall(e, 'computed', t.checker) && t.typeOf(e).startsWith('Signal<')) {
|
|
158
|
+
const fn = arg(0);
|
|
159
|
+
const rt = t.typeOf(e).replace(/^Signal<(.*)>$/, '$1');
|
|
160
|
+
if (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))
|
|
161
|
+
return `Signal<${rt}>(${t.memo(fn, rt, !core.isAsync(fn) && t.throwsInfo.fn(fn))})`;
|
|
162
|
+
const equals = t.equalsArg(arg(1), rt, true);
|
|
163
|
+
return `Signal<${rt}>(Memo<${rt}>(${t.expr(fn)}${equals ?? ''}))`;
|
|
164
|
+
}
|
|
165
|
+
if (name === 'untracked' && lib)
|
|
166
|
+
return `untrack(${t.expr(arg(0))})`;
|
|
167
|
+
if (name === 'runInInjectionContext' && lib) {
|
|
168
|
+
const fn = arg(1);
|
|
169
|
+
if (fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) {
|
|
170
|
+
const type = t.typeOf(e);
|
|
171
|
+
const throws = t.throwsInfo.fn(fn);
|
|
172
|
+
return `Injector.runInContext(${t.restArgument(e, arg(0), 'Any?')}) { ()${throws ? ' throws' : ''} -> ${type} in${t.functionBody(fn, type, t.indent).slice(1)}`;
|
|
173
|
+
}
|
|
174
|
+
return `Injector.runInContext(${t.restArgument(e, arg(0), 'Any?')}, ${t.expr(arg(1))})`;
|
|
175
|
+
}
|
|
176
|
+
if ((name === 'forwardRef' || name === 'resolveForwardRef') && lib) {
|
|
177
|
+
const fn = arg(0);
|
|
178
|
+
if (fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) && !ts.isBlock(fn.body))
|
|
179
|
+
return t.expr(fn.body);
|
|
180
|
+
return `resolveForwardRef(${arg(0) ? t.restArgument(e, arg(0), 'Any?') : 'nil'})`;
|
|
181
|
+
}
|
|
182
|
+
if (name === 'isDevMode' && lib)
|
|
183
|
+
return 'false';
|
|
184
|
+
const shimmed = decl && ts.isFunctionDeclaration(decl) && decl.getSourceFile().fileName.startsWith('/__shims__/') ? decl.name?.text : undefined;
|
|
185
|
+
if (shimmed === 'enableProdMode')
|
|
186
|
+
return '()';
|
|
187
|
+
if (shimmed === 'isAngularHmrRestoringRoute')
|
|
188
|
+
return 'false';
|
|
189
|
+
if (name === 'output' && lib)
|
|
190
|
+
return `${t.typeOf(e)}()`;
|
|
191
|
+
if (name === 'inject' && lib)
|
|
192
|
+
return injection(t, e, arg(0), (token) => `Injector.inject(${token}${arg(1) ? `, ${t.restArgument(e, arg(1), 'Any?')}` : ''})`);
|
|
193
|
+
if (name === 'effect' && lib)
|
|
194
|
+
return `Effect.deferred(${t.callback(arg(0))})`;
|
|
195
|
+
if (name === 'toSignal' && lib) {
|
|
196
|
+
const options = arg(1) && ts.isObjectLiteralExpression(arg(1)) ? arg(1) : undefined;
|
|
197
|
+
const initial = options?.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'initialValue');
|
|
198
|
+
const inner = t.typeOf(e).replace(/^Signal<(.*)>$/, '$1');
|
|
199
|
+
return `toSignal(${t.expr(arg(0))}${initial ? `, initialValue: ${t.coerce(initial.initializer, inner)}` : ''})`;
|
|
200
|
+
}
|
|
201
|
+
if (name === 'firstValueFrom' && lib)
|
|
202
|
+
return `rxFirstValueFrom(${t.expr(arg(0))})`;
|
|
203
|
+
if (name === 'registerElement' && (lib || core.adapterRuntimeFile(decl?.getSourceFile().fileName) === 'runtime/angular-rx.ts'))
|
|
204
|
+
return '()';
|
|
205
|
+
return undefined;
|
|
206
|
+
}
|
|
207
|
+
function methodCall(t, owner, method, e) {
|
|
208
|
+
const target = e.expression.expression;
|
|
209
|
+
if ((owner === 'OutputEmitterRef' || owner === 'EventEmitter') && (method === 'emit' || method === 'next')) {
|
|
210
|
+
const value = /^(?:OutputEmitterRef|EventEmitter|Emitter)<(.*)>[?!]?$/.exec(t.typeOf(target))?.[1];
|
|
211
|
+
const a = e.arguments[0];
|
|
212
|
+
return `${t.expr(target)}.emit(${a ? (value && value !== 'Void' && value !== 'Unit' ? t.coerce(a, value) : t.expr(a)) : ''})`;
|
|
213
|
+
}
|
|
214
|
+
if (owner === 'Injector' && method === 'get' && e.arguments[0]) {
|
|
215
|
+
const rawArg0 = forwardRefTarget(e.arguments[0]);
|
|
216
|
+
const tokTarget = ts.isExpressionWithTypeArguments(rawArg0) ? rawArg0.expression : rawArg0;
|
|
217
|
+
const token = tokenName(t, tokTarget);
|
|
218
|
+
if (token === 'ViewContainerRef')
|
|
219
|
+
throw t.error(e, 'an injected ViewContainerRef', 'view-container-ref');
|
|
220
|
+
const tokenDecl = t.resolve(tokTarget)?.declarations?.[0];
|
|
221
|
+
if ((KIT_TOKENS.includes(token) || isInjectableClass(tokenDecl, t.pluginFiles)) && e.arguments.length === 1 && t.throwsInfo.expr(e))
|
|
222
|
+
return injectedToken(t, token, e, tokenDecl);
|
|
223
|
+
const raw = `${t.expr(target)}.get(${t.coerce(rawArg0, 'Any?')}${e.arguments[1] ? `, ${t.coerce(e.arguments[1], 'Any?')}` : ''}${e.arguments[2] ? `, ${t.coerce(e.arguments[2], 'Any?')}` : ''})`;
|
|
224
|
+
const type = t.typeOf(e);
|
|
225
|
+
return type === 'Any?' ? raw : t.fromAny(raw, type);
|
|
226
|
+
}
|
|
227
|
+
// `http.get<T>(url, options)` / `http.post<T>(url, body, options)`: the parsed body read as T.
|
|
228
|
+
if (owner === 'HttpClient' && ['get', 'delete', 'head', 'options', 'post', 'put', 'patch', 'request'].includes(method) && t.typeOf(e).startsWith('RxObservable<')) {
|
|
229
|
+
const value = /^RxObservable<(.*)>$/.exec(t.typeOf(e))?.[1] ?? 'Any?';
|
|
230
|
+
const call = method === 'request'
|
|
231
|
+
? `${t.expr(target)}.request(${t.str(e.arguments[0])}, ${e.arguments[1] ? t.str(e.arguments[1]) : '""'}${e.arguments[2] ? `, ${t.coerce(e.arguments[2], 'Any?')}` : ''})`
|
|
232
|
+
: ['post', 'put', 'patch'].includes(method)
|
|
233
|
+
? `${t.expr(target)}.${method}(${t.str(e.arguments[0])}${e.arguments[1] ? `, ${t.coerce(e.arguments[1], 'Any?')}` : ', nil'}${e.arguments[2] ? `, ${t.coerce(e.arguments[2], 'Any?')}` : ''})`
|
|
234
|
+
: `${t.expr(target)}.${method}(${t.str(e.arguments[0])}${e.arguments[1] ? `, ${t.coerce(e.arguments[1], 'Any?')}` : ''})`;
|
|
235
|
+
return value === 'Any?' ? call : `${call}.mapValues { (__v: Any?) -> ${value} in ${t.fromAny('__v', value)} }`;
|
|
236
|
+
}
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
/** A source base class the injector also makes, whose `shared` this class's overrides: each class has its own root instance. */
|
|
240
|
+
function injectableBase(t, cls) {
|
|
241
|
+
for (let b = t.sourceBase(cls); b; b = t.sourceBase(b))
|
|
242
|
+
if (ts.isClassDeclaration(b) && ['based', 'root'].includes(injectableRole(b, t.pluginFiles) ?? ''))
|
|
243
|
+
return true;
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* What makes a class the injector makes as a root service: an extension of it, or class members when a base class's
|
|
248
|
+
* are overridden (an extension cannot override) or when its subclasses may override them.
|
|
249
|
+
*/
|
|
250
|
+
function injectableStatics(t, cls, code, form) {
|
|
251
|
+
const name = ts.isModuleBlock(cls.parent) ? cls.name.text : t.topName(cls, cls.name.text);
|
|
252
|
+
const ctor = cls.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
|
|
253
|
+
const args = (ctor?.parameters ?? []).map((p) => t.constructorParameter(p));
|
|
254
|
+
const throwsInit = /^\s*(?:override )?(?:convenience )?init\(.*\) throws/m.test(code) || (ctor?.parameters ?? []).some((p) => t.throwsInfo.injects(p));
|
|
255
|
+
const make = core.swift.tryIf(throwsInit, `${name}(${args.join(', ')})`);
|
|
256
|
+
const mods = form === 'extension' ? 'static' : form === 'class' ? 'class' : 'override class';
|
|
257
|
+
const shared = injectableShared(cls, t.pluginFiles, t.checker);
|
|
258
|
+
const members = [
|
|
259
|
+
throwsInit ? ` ${mods} var ${shared}: ${name} { get throws { try Injector.root(${name}.self) { ${make} } } }` : ` ${mods} var ${shared}: ${name} { Injector.root(${name}.self, making: { ${make} }) }`,
|
|
260
|
+
` ${mods} var jsSharedInstance: Any? { get throws { ${throwsInit ? 'try ' : ''}${shared} } }`,
|
|
261
|
+
` ${mods} func jsConstruct() throws -> Any? { ${make} }`,
|
|
262
|
+
];
|
|
263
|
+
return form === 'extension' ? [`extension ${name}: JSInjectableType {`, ...members, '}'] : members;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* What the injector reads of an NgModule: its metadata, evaluated once as the decorator is, and how it is made, its
|
|
267
|
+
* constructor's parameters injected.
|
|
268
|
+
*/
|
|
269
|
+
function ngModuleStatics(t, cls, name, def, code) {
|
|
270
|
+
const ctor = cls.members.find((m) => ts.isConstructorDeclaration(m) && !!m.body);
|
|
271
|
+
const args = (ctor?.parameters ?? []).map((p) => t.constructorParameter(p));
|
|
272
|
+
const throwsInit = /^\s*(?:override )?(?:convenience )?init\(.*\) throws/m.test(code) || (ctor?.parameters ?? []).some((p) => t.throwsInfo.injects(p));
|
|
273
|
+
return [
|
|
274
|
+
` static let jsNgImports: Any? = JSArray<Any?>([${def.imports.map((e) => t.coerce(e, 'Any?')).join(', ')}])`,
|
|
275
|
+
` static let jsNgProviders: Any? = ${def.providers ? t.coerce(def.providers, 'Any?') : 'nil'}`,
|
|
276
|
+
` static func jsNgConstruct() throws -> Any? { ${core.swift.tryIf(throwsInit, `${name}(${args.join(', ')})`)} }`,
|
|
277
|
+
];
|
|
278
|
+
}
|
|
279
|
+
export const swiftHooks = {
|
|
280
|
+
...model,
|
|
281
|
+
typeMap: {
|
|
282
|
+
OutputEmitterRef: 'Emitter<$0>',
|
|
283
|
+
EventEmitter: 'Emitter<$0>',
|
|
284
|
+
LetSlot: { type: 'LetSlot<$0>', shim: true },
|
|
285
|
+
RouterExtensions: { type: 'Router', shim: true },
|
|
286
|
+
EnvironmentInjector: { type: 'Injector', shim: true },
|
|
287
|
+
...Object.fromEntries(['RxObservable', 'RxSubject', 'RxBehaviorSubject', 'RxReplaySubject'].map((n) => [n, { type: `${n}<$0>`, shim: true }])),
|
|
288
|
+
...Object.fromEntries(['NativeDialogRef', 'NativeDialogService', 'DestroyRef', 'Injector', 'InjectionToken', 'ErrorHandler', 'NgZone', 'HttpClient', 'ChangeDetectorRef', 'PurePipeCache', 'NodeInjector', 'ElementRef', 'SimpleChange',
|
|
289
|
+
'TeardownHandle', 'NavigationEnd', 'NavigationStart', 'NavigationCancel', 'NavigationError', 'RoutesRecognized', 'ResolveStart', 'ResolveEnd',
|
|
290
|
+
'KitHttpClient', 'KitActivatedRoute', 'KitRouter', 'KitNativeDialogRef', 'KitNativeDialogService',
|
|
291
|
+
'HttpParams', 'HttpHeaders', 'HttpResponse', 'HttpErrorResponse', 'HttpRequest', 'HttpContext', 'HttpContextToken',
|
|
292
|
+
'ParamMap', 'UrlSegment', 'UrlTree', 'DefaultUrlSerializer', 'ActivatedRouteSnapshot',
|
|
293
|
+
'ViewContainerRef', 'TemplateRef', 'ComponentRef', 'EmbeddedViewRef', 'ApplicationRef', 'Location'].map((n) => [n, { type: n, shim: true, metatype: true }])),
|
|
294
|
+
},
|
|
295
|
+
globalCall,
|
|
296
|
+
methodCall,
|
|
297
|
+
newCall: (t, name, e) => (name === 'Inject' && e.arguments?.[0] && t.resolve(e.expression)?.declarations?.[0]?.getSourceFile().fileName.startsWith('/__shims__/') ? `(${t.coerce(e.arguments[0], 'Any?')} as Any?)` : undefined),
|
|
298
|
+
constructorParameter: parameterInject,
|
|
299
|
+
componentField(t, m) {
|
|
300
|
+
const callee = m.initializer ? t.calleeName(m.initializer) : '';
|
|
301
|
+
if (callee !== 'input' && callee !== 'input.required' && callee !== 'model' && callee !== 'model.required')
|
|
302
|
+
return undefined;
|
|
303
|
+
// An Angular input is a prop: a signal the parent writes.
|
|
304
|
+
const type = t.typeOf(m.name).replace(/^Signal<(.*)>$/, '$1');
|
|
305
|
+
const given = m.initializer.arguments[0];
|
|
306
|
+
return { prop: { type, default: given ? (type.startsWith('JSNullish<') ? t.stored(given, given, type) : t.expr(given)) : callee === 'input' || callee === 'model' ? 'nil' : undefined } };
|
|
307
|
+
},
|
|
308
|
+
/** A standalone component's imports as its root-view injector reads them, evaluated once as the decorator is. */
|
|
309
|
+
componentStatics(t, cls) {
|
|
310
|
+
const ngImports = standaloneImports(cls, t.checker, t.compiles);
|
|
311
|
+
return ngImports ? [` static let jsNgImports: Any? = JSArray<Any?>([${ngImports.map((e) => t.coerce(e, 'Any?')).join(', ')}])`] : [];
|
|
312
|
+
},
|
|
313
|
+
componentAsValue: (t, cls, type) => `ComponentFactory { ${t.rootView(cls, type, `try AngularView.construct { ${t.throwsInfo.initThrows(cls) ? 'try ' : ''}${type}() }.${t.components.get(cls.name.text).members.render}()`)} }`,
|
|
314
|
+
/** A component created as a root view (bootstrap, route, dialog): made and rendered in its standalone injector. */
|
|
315
|
+
wrapRootView: (t, cls, type, make) => (standaloneImports(cls, t.checker, t.compiles) ? `try Injector.standalone(${type}.self, ${type}.jsNgImports) { ${make} }` : make),
|
|
316
|
+
serviceClass(t, cls, name) {
|
|
317
|
+
const members = t.componentMembers(cls, [], true);
|
|
318
|
+
// A constructor that throws throws from the inject() that made it, and the next inject() makes the service again.
|
|
319
|
+
const throwsInit = members.some((m) => /^\s*(?:convenience )?init\(.*\) throws/m.test(m));
|
|
320
|
+
const shared = throwsInit
|
|
321
|
+
? [
|
|
322
|
+
` static var shared: ${name} { get throws { try Injector.root(${name}.self) { try ${name}() } } }`,
|
|
323
|
+
` static var jsSharedInstance: Any? { get throws { try shared } }`,
|
|
324
|
+
` static func jsConstruct() throws -> Any? { try ${name}() }`,
|
|
325
|
+
]
|
|
326
|
+
: [
|
|
327
|
+
` static var shared: ${name} { Injector.root(${name}.self, making: { ${name}() }) }`,
|
|
328
|
+
` static var jsSharedInstance: Any? { shared }`,
|
|
329
|
+
` static func jsConstruct() throws -> Any? { ${name}() }`,
|
|
330
|
+
];
|
|
331
|
+
return [`final class ${name}: JSInjectableType {`, core.swift.NONISOLATED_DEINIT, ...shared, '', ...members, '}'].join('\n');
|
|
332
|
+
},
|
|
333
|
+
// An app's @Injectable class extending another class: translated as any class is, and made by the injector as a service is.
|
|
334
|
+
afterClass: (t, cls, code) => (injectableRole(cls, t.pluginFiles) === 'based' && !injectableBase(t, cls) ? injectableStatics(t, cls, code, 'extension').join('\n') : undefined),
|
|
335
|
+
classExtras(t, cls, name, code) {
|
|
336
|
+
const supertypes = [];
|
|
337
|
+
const members = [];
|
|
338
|
+
const role = injectableRole(cls, t.pluginFiles);
|
|
339
|
+
if (role === 'root' || (role === 'based' && injectableBase(t, cls))) {
|
|
340
|
+
const overrides = injectableBase(t, cls);
|
|
341
|
+
if (!overrides)
|
|
342
|
+
supertypes.push('JSInjectableType');
|
|
343
|
+
members.push(...injectableStatics(t, cls, code, overrides ? 'override' : 'class'));
|
|
344
|
+
}
|
|
345
|
+
const ngModule = ngModuleDef(cls, t.checker, t.compiles);
|
|
346
|
+
if (ngModule) {
|
|
347
|
+
supertypes.push('JSNgModuleType');
|
|
348
|
+
members.push(...ngModuleStatics(t, cls, name, ngModule, [code, ...members].join('\n')));
|
|
349
|
+
}
|
|
350
|
+
return { supertypes, members };
|
|
351
|
+
},
|
|
352
|
+
};
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
package org.nativescript.kit
|
|
2
|
+
|
|
3
|
+
// Angular's dependency injection and the @nativescript/angular services an app injects, for components and
|
|
4
|
+
// services compiled to classes with a `shared` instance (`providedIn: 'root'`), as kit-apple's AngularAPI.swift.
|
|
5
|
+
|
|
6
|
+
/** A component class used as a value (`dialog.open(SheetComponent)`): what creating and rendering it gives. */
|
|
7
|
+
class ComponentFactory(internal val make: () -> View)
|
|
8
|
+
|
|
9
|
+
/** `NativeDialogRef`: the open dialog a component was created in. */
|
|
10
|
+
class NativeDialogRef {
|
|
11
|
+
/** `NATIVE_DIALOG_DATA`: the `data` the dialog was opened with. */
|
|
12
|
+
var data: Any? = null
|
|
13
|
+
internal set
|
|
14
|
+
private val closed = RxReplaySubject<Any?>(1.0)
|
|
15
|
+
|
|
16
|
+
fun close(result: Any? = null) = Modal.close(result)
|
|
17
|
+
fun afterClosed(): RxObservable<Any?> = closed.asObservable()
|
|
18
|
+
internal fun didClose(result: Any?) = closed.next(result)
|
|
19
|
+
|
|
20
|
+
companion object {
|
|
21
|
+
/** The dialog whose component is being created; one no dialog opened before then. */
|
|
22
|
+
var current = NativeDialogRef()
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** `NativeDialog` (`NativeDialogService`): a component shown as a native modal, with `nativeOptions` as `showModal` takes them. */
|
|
27
|
+
class NativeDialogService private constructor() {
|
|
28
|
+
fun open(component: Any?, config: Any? = null): NativeDialogRef {
|
|
29
|
+
val ref = NativeDialogRef()
|
|
30
|
+
ref.data = jsGet(config, "data")
|
|
31
|
+
val factory = jsBox(component) as? ComponentFactory ?: return ref
|
|
32
|
+
Modal.show(jsGet(config, "nativeOptions"), closeCallback = { result -> ref.didClose(result) }) {
|
|
33
|
+
val previous = NativeDialogRef.current
|
|
34
|
+
NativeDialogRef.current = ref
|
|
35
|
+
val pending = Reactivity.pending()
|
|
36
|
+
val view = try { EffectOrder.detached { factory.make() } } finally { NativeDialogRef.current = previous }
|
|
37
|
+
Reactivity.detectChanges(after = pending)
|
|
38
|
+
view
|
|
39
|
+
}
|
|
40
|
+
return ref
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
companion object {
|
|
44
|
+
val shared = NativeDialogService()
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* `HttpClient` through core's `Http.request`, the request @nativescript/angular's backend sends through
|
|
50
|
+
* core's XMLHttpRequest: the body parsed as JSON unless `responseType` is `'text'`, a status of 400 or more an error.
|
|
51
|
+
*/
|
|
52
|
+
class HttpClient private constructor() {
|
|
53
|
+
private fun send(method: String, url: String, body: Any? = null, options: Any? = null): RxObservable<Any?> {
|
|
54
|
+
val flatOpts = jsBox(options)
|
|
55
|
+
val text = jsToString(jsGetOptional(flatOpts, "responseType")) == "text"
|
|
56
|
+
val observe = jsToString(jsGetOptional(flatOpts, "observe") ?: "body")
|
|
57
|
+
val rawHeaders = jsGetOptional(flatOpts, "headers")
|
|
58
|
+
val rawParams = jsGetOptional(flatOpts, "params")
|
|
59
|
+
|
|
60
|
+
var fullUrl = url
|
|
61
|
+
if (!jsIsNullish(rawParams)) {
|
|
62
|
+
val q = (jsBox(rawParams) as? HttpParams)?.toString() ?: HttpParams(rawParams).toString()
|
|
63
|
+
if (q.isNotEmpty()) {
|
|
64
|
+
fullUrl = if (fullUrl.contains("?")) "$fullUrl&$q" else "$fullUrl?$q"
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
var headersObj: Any? = (jsBox(rawHeaders) as? HttpHeaders)?.toJSObject() ?: rawHeaders
|
|
69
|
+
val payloadBody = body ?: jsGetOptional(flatOpts, "body")
|
|
70
|
+
val upperMethod = method.uppercase()
|
|
71
|
+
|
|
72
|
+
val request: () -> JSPromise<Any?> = {
|
|
73
|
+
val failure = { status: Double, reason: String -> JSError("Http failure response for $fullUrl: ${jsToString(status)} $reason") }
|
|
74
|
+
val (promise, resolvers) = JSPromise.pending<Any?>()
|
|
75
|
+
try {
|
|
76
|
+
val settings = JSObject("url" to fullUrl, "method" to upperMethod)
|
|
77
|
+
if (!jsIsNullish(payloadBody) && upperMethod != "GET" && upperMethod != "HEAD") {
|
|
78
|
+
if (payloadBody is String) {
|
|
79
|
+
settings["content"] = payloadBody
|
|
80
|
+
} else {
|
|
81
|
+
val json = jsJSONStringify(payloadBody)
|
|
82
|
+
if (json is String) {
|
|
83
|
+
settings["content"] = json
|
|
84
|
+
if (jsIsNullish(headersObj)) {
|
|
85
|
+
headersObj = JSObject("Content-Type" to "application/json")
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (!jsIsNullish(headersObj)) settings["headers"] = headersObj
|
|
91
|
+
(Core_http_http_request_index.request(settings) ?: jsCannotRead("then")).then({ response: Any? ->
|
|
92
|
+
try {
|
|
93
|
+
val status = jsToNumber(jsGet(response, "statusCode"))
|
|
94
|
+
val reason = if (status == 0.0) "Unknown Error" else reasonPhrase(status.toInt())
|
|
95
|
+
if (status >= 400 || status == 0.0) {
|
|
96
|
+
resolvers.reject(failure(status, reason))
|
|
97
|
+
} else {
|
|
98
|
+
val rawContent = jsToString(jsCallMethod(jsGet(response, "content"), "toString"))
|
|
99
|
+
val parsed: Any? = if (text) rawContent else if (rawContent.isEmpty()) null else jsJSONParse(rawContent)
|
|
100
|
+
if (observe == "response") {
|
|
101
|
+
resolvers.resolve(HttpResponse(JSObject(
|
|
102
|
+
"body" to parsed,
|
|
103
|
+
"status" to status,
|
|
104
|
+
"statusText" to reason,
|
|
105
|
+
"url" to fullUrl,
|
|
106
|
+
)))
|
|
107
|
+
} else {
|
|
108
|
+
resolvers.resolve(parsed)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
} catch (e: Throwable) {
|
|
112
|
+
resolvers.reject(jsCaught(e))
|
|
113
|
+
}
|
|
114
|
+
}, { _: Any? -> resolvers.reject(failure(0.0, "Unknown Error")) })
|
|
115
|
+
} catch (e: Throwable) {
|
|
116
|
+
resolvers.reject(jsCaught(e))
|
|
117
|
+
}
|
|
118
|
+
promise
|
|
119
|
+
}
|
|
120
|
+
val observable = RxObservable.ending<Any?> { next, error, complete ->
|
|
121
|
+
val subscription = TeardownHandle()
|
|
122
|
+
request().then({ value ->
|
|
123
|
+
if (!subscription.closed) {
|
|
124
|
+
next(value)
|
|
125
|
+
complete()
|
|
126
|
+
}
|
|
127
|
+
}, { err -> if (!subscription.closed) error(err) })
|
|
128
|
+
subscription
|
|
129
|
+
}
|
|
130
|
+
observable.first = request
|
|
131
|
+
return observable
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
fun request(first: Any?, url: String? = null, options: Any? = null): RxObservable<Any?> {
|
|
135
|
+
val req = jsBox(first) as? HttpRequest
|
|
136
|
+
if (req != null) {
|
|
137
|
+
return send(req.method, req.url, req.body, JSObject(
|
|
138
|
+
"headers" to req.headers,
|
|
139
|
+
"params" to req.params,
|
|
140
|
+
"responseType" to req.responseType,
|
|
141
|
+
"observe" to "response",
|
|
142
|
+
))
|
|
143
|
+
}
|
|
144
|
+
return send(jsToString(first), url ?: "", null, options)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
fun get(url: String, options: Any? = null): RxObservable<Any?> = send("GET", url, null, options)
|
|
148
|
+
fun delete(url: String, options: Any? = null): RxObservable<Any?> = send("DELETE", url, null, options)
|
|
149
|
+
fun head(url: String, options: Any? = null): RxObservable<Any?> = send("HEAD", url, null, options)
|
|
150
|
+
fun options(url: String, options: Any? = null): RxObservable<Any?> = send("OPTIONS", url, null, options)
|
|
151
|
+
fun post(url: String, body: Any? = null, options: Any? = null): RxObservable<Any?> = send("POST", url, body, options)
|
|
152
|
+
fun put(url: String, body: Any? = null, options: Any? = null): RxObservable<Any?> = send("PUT", url, body, options)
|
|
153
|
+
fun patch(url: String, body: Any? = null, options: Any? = null): RxObservable<Any?> = send("PATCH", url, body, options)
|
|
154
|
+
|
|
155
|
+
fun jsonp(url: String, callbackParam: String): RxObservable<Any?> {
|
|
156
|
+
val sep = if (url.contains("?")) "&" else "?"
|
|
157
|
+
return get("$url$sep${jsEncodeURIComponent(callbackParam)}=JSONP_CALLBACK")
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
private fun reasonPhrase(status: Int): String = when (status) {
|
|
161
|
+
200 -> "OK"; 201 -> "Created"; 202 -> "Accepted"; 204 -> "No Content"
|
|
162
|
+
400 -> "Bad Request"; 401 -> "Unauthorized"; 403 -> "Forbidden"; 404 -> "Not Found"; 405 -> "Method Not Allowed"
|
|
163
|
+
408 -> "Request Timeout"; 409 -> "Conflict"; 410 -> "Gone"; 422 -> "Unprocessable Entity"; 429 -> "Too Many Requests"
|
|
164
|
+
500 -> "Internal Server Error"; 501 -> "Not Implemented"; 502 -> "Bad Gateway"; 503 -> "Service Unavailable"; 504 -> "Gateway Timeout"
|
|
165
|
+
else -> ""
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
companion object {
|
|
169
|
+
val shared = HttpClient()
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
typealias KitHttpClient = HttpClient
|
|
174
|
+
typealias KitNativeDialogRef = NativeDialogRef
|
|
175
|
+
typealias KitNativeDialogService = NativeDialogService
|