@ng-desktop/builders 0.0.0-stage → 0.4.0

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 (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +13 -2
  3. package/bin/ng-desktop.mjs +200 -0
  4. package/builders.json +15 -0
  5. package/fesm2022/application-builder.d.mts +62 -0
  6. package/fesm2022/application-builder.mjs +58 -0
  7. package/fesm2022/ast-metadata-extractor.d.mts +40 -0
  8. package/fesm2022/ast-metadata-extractor.mjs +460 -0
  9. package/fesm2022/build-bundle.d.mts +45 -0
  10. package/fesm2022/build-bundle.mjs +462 -0
  11. package/fesm2022/builder.d.ts +66 -0
  12. package/fesm2022/builder.js +123 -0
  13. package/fesm2022/dev-server-builder.d.mts +26 -0
  14. package/fesm2022/dev-server-builder.mjs +24 -0
  15. package/fesm2022/dev-server.mjs +47 -0
  16. package/fesm2022/hmr-client.d.mts +24 -0
  17. package/fesm2022/hmr-client.mjs +84 -0
  18. package/fesm2022/icon-compiler.d.mts +6 -0
  19. package/fesm2022/icon-compiler.mjs +148 -0
  20. package/fesm2022/index.d.ts +13 -0
  21. package/fesm2022/index.js +13 -0
  22. package/fesm2022/permission-analyzer.d.mts +45 -0
  23. package/fesm2022/permission-analyzer.mjs +333 -0
  24. package/fesm2022/resolve-engine-binary.d.mts +35 -0
  25. package/fesm2022/resolve-engine-binary.mjs +130 -0
  26. package/fesm2022/server-compiler.d.mts +29 -0
  27. package/fesm2022/server-compiler.mjs +236 -0
  28. package/fesm2022/style-compiler.d.mts +26 -0
  29. package/fesm2022/style-compiler.mjs +258 -0
  30. package/fesm2022/template-compiler.d.mts +53 -0
  31. package/fesm2022/template-compiler.mjs +892 -0
  32. package/fesm2022/workspace-resolver.d.mts +24 -0
  33. package/fesm2022/workspace-resolver.mjs +199 -0
  34. package/package.json +79 -4
  35. package/schema/angular-native-schema.json +52 -0
  36. package/schema/native-builder-schema.json +97 -0
  37. package/schematics/collection.json +10 -0
  38. package/schematics/ng-add/index.d.mts +20 -0
  39. package/schematics/ng-add/index.mjs +56 -0
  40. package/schematics/ng-add/schema.json +24 -0
@@ -0,0 +1,462 @@
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ readdirSync,
5
+ readFileSync,
6
+ statSync,
7
+ watch,
8
+ writeFileSync,
9
+ } from 'node:fs';
10
+ import { dirname, relative, resolve } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { extractComponentMetadata } from './ast-metadata-extractor.mjs';
13
+ import { pushHmrReload, pushHmrServerReload } from './hmr-client.mjs';
14
+ import { buildMultiResolutionIcons } from './icon-compiler.mjs';
15
+ import { analyzeProjectPermissions } from './permission-analyzer.mjs';
16
+ import { compileServerBundle, discoverServerRoutes, runEsbuildBuild } from './server-compiler.mjs';
17
+ import {
18
+ emitStyleInstruction,
19
+ formatStyleRuleExtensions,
20
+ parseStylesCss,
21
+ } from './style-compiler.mjs';
22
+ import { parseTemplateHtml } from './template-compiler.mjs';
23
+ import { resolveWorkspaceProject } from './workspace-resolver.mjs';
24
+
25
+ export {
26
+ compileServerBundle,
27
+ discoverServerRoutes,
28
+ extractComponentMetadata,
29
+ parseStylesCss,
30
+ parseTemplateHtml,
31
+ pushHmrReload,
32
+ pushHmrServerReload,
33
+ };
34
+
35
+ const lastEmittedByOutDir = new Map();
36
+
37
+ function extractCliFlagValue(argv, flag) {
38
+ const prefix = `${flag}=`;
39
+ for (let i = 0; i < argv.length; i += 1) {
40
+ const arg = argv[i];
41
+ if (arg.startsWith(prefix)) {
42
+ return arg.slice(prefix.length).trim() || undefined;
43
+ }
44
+ if (arg === flag && i + 1 < argv.length && !argv[i + 1].startsWith('--')) {
45
+ return argv[i + 1].trim() || undefined;
46
+ }
47
+ }
48
+ return undefined;
49
+ }
50
+
51
+ function mapNativeEventName(evtName) {
52
+ if (evtName === 'click') return 'clicked';
53
+ if (evtName === 'change') return 'toggled';
54
+ if (evtName === 'valueChange') return 'value-changed';
55
+ return evtName;
56
+ }
57
+
58
+ function collectComponentTsFiles(dirPath, rootAppDir, out = []) {
59
+ if (!existsSync(dirPath)) return out;
60
+ for (const entry of readdirSync(dirPath)) {
61
+ const full = resolve(dirPath, entry);
62
+ const stat = statSync(full);
63
+ if (stat.isDirectory()) {
64
+ collectComponentTsFiles(full, rootAppDir, out);
65
+ } else if (entry.endsWith('.ts') && !entry.endsWith('.spec.ts') && entry !== 'app.ts') {
66
+ out.push(relative(rootAppDir, full));
67
+ }
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /**
73
+ * 4. Bytecode Emitter (SRP): Translates Styles IR + Signals + Icons + Template AST into `.ngb` instructions.
74
+ */
75
+ export function emitNgbBundle(
76
+ styleRules,
77
+ numericSignals,
78
+ methods,
79
+ astRoots,
80
+ iconMeta,
81
+ sourceLabel,
82
+ ) {
83
+ const lines = [`// Auto-compiled by Angular Native Template Compiler from ${sourceLabel}`];
84
+
85
+ for (const [sigName, initialValue] of Object.entries(numericSignals)) {
86
+ lines.push(`signal ${sigName} ${initialValue}`);
87
+ }
88
+
89
+ for (const rule of styleRules) {
90
+ lines.push(emitStyleInstruction(rule));
91
+ }
92
+
93
+ const appendInstructions = [];
94
+ const bindingInstructions = [];
95
+
96
+ function visitNode(node) {
97
+ if (node.isComment) {
98
+ lines.push(`comment ${node.id} ${node.text}`);
99
+ return;
100
+ }
101
+
102
+ lines.push(`create ${node.id} ${node.tag}`);
103
+
104
+ if (node.title) {
105
+ lines.push(`text ${node.id} ${node.title}`);
106
+ } else if (node.text) {
107
+ lines.push(`text ${node.id} ${node.text}`);
108
+ }
109
+
110
+ if ((node.tag === 'ng-window' || node.tag === 'adw-window') && iconMeta) {
111
+ lines.push(`icon ${node.id} ${iconMeta.appId} ${iconMeta.relPath}`);
112
+ }
113
+
114
+ for (const [attrKey, attrVal] of Object.entries(node.attributes || {})) {
115
+ lines.push(`attr ${node.id} ${attrKey} ${attrVal}`);
116
+ }
117
+
118
+ for (const cls of node.classes) {
119
+ lines.push(`add_class ${node.id} ${cls}`);
120
+ }
121
+
122
+ if (node.reactiveBinding) {
123
+ bindingInstructions.push(
124
+ `bind_text ${node.id} ${node.reactiveBinding.signalName} ${node.reactiveBinding.template}`,
125
+ );
126
+ }
127
+
128
+ for (const attrBind of node.reactiveAttrs || []) {
129
+ bindingInstructions.push(
130
+ `bind_attr ${node.id} ${attrBind.attrKey} ${attrBind.signalName} ${attrBind.template}`,
131
+ );
132
+ }
133
+
134
+ if (node.visibilityBinding) {
135
+ bindingInstructions.push(
136
+ `bind_visible ${node.id} ${node.visibilityBinding.signalName} ${node.visibilityBinding.op} ${node.visibilityBinding.rhs}`,
137
+ );
138
+ }
139
+
140
+ for (const [evtName, methodName] of Object.entries(node.events)) {
141
+ const nativeEvt = mapNativeEventName(evtName);
142
+ const methodMeta = methods[methodName];
143
+ if (methodMeta) {
144
+ const opcode = methodMeta.kind === 'set' ? 'on_set' : 'on_add';
145
+ bindingInstructions.push(
146
+ `${opcode} ${node.id} ${nativeEvt} ${methodMeta.signalName} ${methodMeta.value}`,
147
+ );
148
+ }
149
+ }
150
+
151
+ for (const child of node.children) {
152
+ visitNode(child);
153
+ appendInstructions.push(`append ${node.id} ${child.id}`);
154
+ }
155
+ }
156
+
157
+ for (const root of astRoots) {
158
+ visitNode(root);
159
+ }
160
+
161
+ lines.push(...appendInstructions);
162
+ lines.push(...bindingInstructions);
163
+ return lines.join('\n') + '\n';
164
+ }
165
+
166
+ function emitAppJsBundleIfPresent(outDir, projectName, allStyleRules, iconMeta) {
167
+ const browserDir = resolve(outDir, 'browser');
168
+ if (!existsSync(browserDir)) {
169
+ return undefined;
170
+ }
171
+ const entries = readdirSync(browserDir);
172
+ const mainFile =
173
+ entries.find((f) => f === 'main.js') ?? entries.find((f) => /^main-.*\.js$/.test(f));
174
+ if (!mainFile) {
175
+ return undefined;
176
+ }
177
+ const polyfillsFile =
178
+ entries.find((f) => f === 'polyfills.js') ?? entries.find((f) => /^polyfills-.*\.js$/.test(f));
179
+
180
+ const preamble = [
181
+ `globalThis.__NG_NATIVE_APP_ID__ = ${JSON.stringify(projectName)};`,
182
+ iconMeta
183
+ ? `globalThis.__NG_DESKTOP_ICON__ = ${JSON.stringify(iconMeta)};`
184
+ : 'delete globalThis.__NG_DESKTOP_ICON__;',
185
+ ];
186
+ for (const rule of allStyleRules) {
187
+ const extras = formatStyleRuleExtensions(rule);
188
+ preamble.push(
189
+ `globalThis.__NG_NATIVE__?.registerStyle(${JSON.stringify(rule.className)}, ${JSON.stringify(rule.background)}, ${JSON.stringify(rule.color)}, ${Number(rule.padding) || 0}, ${Number(rule.spacing) || 0}, ${JSON.stringify(extras)});`,
190
+ );
191
+ }
192
+
193
+ const entryLines = [];
194
+ if (polyfillsFile) {
195
+ entryLines.push(`import ${JSON.stringify(`./${polyfillsFile}`)};`);
196
+ }
197
+ entryLines.push(`import ${JSON.stringify(`./${mainFile}`)};`);
198
+
199
+ const bundled = runEsbuildBuild({
200
+ workspaceRoot: outDir,
201
+ resolveDir: browserDir,
202
+ entrySource: entryLines.join('\n'),
203
+ loader: 'js',
204
+ define: { __NG_DESKTOP_PROD_BUNDLE__: 'true' },
205
+ minifySyntax: true,
206
+ banner: { js: preamble.join('\n') },
207
+ });
208
+
209
+ const entryBundleFile = resolve(outDir, 'app.bundle.js');
210
+ writeFileSync(entryBundleFile, bundled, 'utf8');
211
+ return entryBundleFile;
212
+ }
213
+
214
+ function collectComponentStyleRules(compMeta, baseDir) {
215
+ const rules = [];
216
+ const stylePaths = [];
217
+ if (compMeta.styleUrl) {
218
+ stylePaths.push(compMeta.styleUrl);
219
+ }
220
+ if (Array.isArray(compMeta.styleUrls)) {
221
+ stylePaths.push(...compMeta.styleUrls);
222
+ }
223
+ for (const relCss of stylePaths) {
224
+ const absCss = resolve(baseDir, relCss);
225
+ if (existsSync(absCss)) {
226
+ rules.push(...parseStylesCss(readFileSync(absCss, 'utf8'), relCss));
227
+ }
228
+ }
229
+ if (Array.isArray(compMeta.styles)) {
230
+ for (const inlineCss of compMeta.styles) {
231
+ rules.push(...parseStylesCss(inlineCss, `${compMeta.selector}.inline.css`));
232
+ }
233
+ }
234
+ return rules;
235
+ }
236
+
237
+ function dedupeStyleRules(rules) {
238
+ const byClass = new Map();
239
+ for (const rule of rules) {
240
+ byClass.set(rule.className, rule);
241
+ }
242
+ return [...byClass.values()];
243
+ }
244
+
245
+ export function compileBundle({
246
+ rebuildIcons = true,
247
+ cwd,
248
+ configPath,
249
+ projectName: requestedProject,
250
+ version: versionOverride,
251
+ } = {}) {
252
+ const workspace = resolveWorkspaceProject({
253
+ cwd,
254
+ configPath,
255
+ projectName: requestedProject,
256
+ });
257
+ const rootDir = workspace.workspaceRoot;
258
+ const projectName = workspace.projectName;
259
+ const nativeOptions = workspace.nativeOptions ?? {};
260
+ const resolvedOutputPath = workspace.outputPath;
261
+ const resolvedVersion = versionOverride || workspace.version;
262
+
263
+ const sourceRootAbs = resolve(rootDir, workspace.sourceRoot);
264
+ const appDir = resolve(sourceRootAbs, 'app');
265
+ const tsSource = readFileSync(resolve(appDir, 'app.ts'), 'utf8');
266
+ const { state, numericSignals, methods, component } = extractComponentMetadata(
267
+ tsSource,
268
+ 'app.ts',
269
+ );
270
+ const htmlSource =
271
+ typeof component.template === 'string'
272
+ ? component.template
273
+ : component.templateUrl && existsSync(resolve(appDir, component.templateUrl))
274
+ ? readFileSync(resolve(appDir, component.templateUrl), 'utf8')
275
+ : '';
276
+ const indexHtmlPath = resolve(sourceRootAbs, 'index.html');
277
+ const indexHtml = existsSync(indexHtmlPath) ? readFileSync(indexHtmlPath, 'utf8') : '';
278
+
279
+ const iconHrefMatch = indexHtml.match(/<link[^>]*rel="icon"[^>]*href="([^"]+)"/);
280
+ const iconFileName = iconHrefMatch ? iconHrefMatch[1] : 'favicon.ico';
281
+ const publicPrefix = workspace.projectRoot === '.' ? 'public' : `${workspace.projectRoot}/public`;
282
+ const iconRelPath = `${publicPrefix}/${iconFileName}`;
283
+ const iconAbsPath = resolve(rootDir, iconRelPath);
284
+
285
+ const componentRegistry = {};
286
+ const collectedRules = [...collectComponentStyleRules(component, appDir)];
287
+
288
+ const candidateFiles = collectComponentTsFiles(appDir, appDir);
289
+ for (const file of candidateFiles) {
290
+ const filePath = resolve(appDir, file);
291
+ if (existsSync(filePath)) {
292
+ const ts = readFileSync(filePath, 'utf8');
293
+ if (!ts.includes('@Component')) continue;
294
+ const meta = extractComponentMetadata(ts, file);
295
+ if (!meta.component.hasComponentDecorator) continue;
296
+ const compDir = dirname(filePath);
297
+ const templateHtml =
298
+ typeof meta.component.template === 'string'
299
+ ? meta.component.template
300
+ : meta.component.templateUrl && existsSync(resolve(compDir, meta.component.templateUrl))
301
+ ? readFileSync(resolve(compDir, meta.component.templateUrl), 'utf8')
302
+ : '';
303
+ collectedRules.push(...collectComponentStyleRules(meta.component, compDir));
304
+ componentRegistry[meta.component.selector] = {
305
+ templateHtml,
306
+ templateUrl: meta.component.templateUrl || `${meta.component.selector}.html`,
307
+ };
308
+ }
309
+ }
310
+ const allStyleRules = dedupeStyleRules(collectedRules);
311
+
312
+ const templateAst = parseTemplateHtml(
313
+ htmlSource,
314
+ state,
315
+ numericSignals,
316
+ 'app.html',
317
+ componentRegistry,
318
+ );
319
+
320
+ const outDir = resolve(rootDir, resolvedOutputPath);
321
+ mkdirSync(outDir, { recursive: true });
322
+
323
+ let iconMeta = null;
324
+ if (existsSync(iconAbsPath)) {
325
+ iconMeta = { appId: projectName, relPath: iconRelPath };
326
+ if (rebuildIcons) {
327
+ buildMultiResolutionIcons(iconAbsPath, projectName, outDir, state.windowTitle);
328
+ }
329
+ }
330
+
331
+ const bundle = emitNgbBundle(
332
+ allStyleRules,
333
+ numericSignals,
334
+ methods,
335
+ templateAst,
336
+ iconMeta,
337
+ `${workspace.sourceRoot}/app/app.{ts,html,css}`,
338
+ );
339
+
340
+ const bundleFile = resolve(outDir, 'main.ngb');
341
+ writeFileSync(bundleFile, bundle, 'utf8');
342
+
343
+ const entryBundleFile = emitAppJsBundleIfPresent(outDir, projectName, allStyleRules, iconMeta);
344
+ const serverBundleFile = compileServerBundle({
345
+ workspaceRoot: rootDir,
346
+ sourceRootAbs,
347
+ outDir,
348
+ projectName,
349
+ });
350
+
351
+ const permissions = analyzeProjectPermissions(sourceRootAbs, nativeOptions.permissions);
352
+ const permissionsFile = resolve(outDir, 'permissions.manifest.json');
353
+ writeFileSync(permissionsFile, JSON.stringify(permissions, null, 2) + '\n', 'utf8');
354
+
355
+ const runtimeConfig = {
356
+ schemaVersion: 1,
357
+ workspaceKind: workspace.workspaceKind,
358
+ projectName,
359
+ version: resolvedVersion,
360
+ targetPlatform: nativeOptions.targetPlatform || 'linux-gtk4',
361
+ outputPath: resolvedOutputPath,
362
+ iconSearchDir: `${resolvedOutputPath}/icons`,
363
+ ...(entryBundleFile ? { entryBundle: 'app.bundle.js' } : {}),
364
+ ...(serverBundleFile ? { serverBundle: 'server.bundle.js' } : {}),
365
+ permissions,
366
+ };
367
+ const runtimeConfigFile = resolve(outDir, 'ng-desktop.runtime.json');
368
+ writeFileSync(runtimeConfigFile, JSON.stringify(runtimeConfig, null, 2) + '\n', 'utf8');
369
+
370
+ console.log(
371
+ `[Angular Native Compiler] Compiled ${projectName} v${resolvedVersion} (${workspace.workspaceKind}) -> ${bundleFile}`,
372
+ );
373
+ if (entryBundleFile) {
374
+ console.log(`[Angular Native Compiler] Bundled Ivy JS runtime entry -> ${entryBundleFile}`);
375
+ }
376
+ if (serverBundleFile) {
377
+ console.log(`[Angular Native Compiler] Bundled Analog server routes -> ${serverBundleFile}`);
378
+ }
379
+
380
+ const prevEmitted = lastEmittedByOutDir.get(outDir);
381
+ const appBundleContent = entryBundleFile ? readFileSync(entryBundleFile, 'utf8') : null;
382
+ const serverBundleContent = serverBundleFile ? readFileSync(serverBundleFile, 'utf8') : null;
383
+ const hmrDelta = {
384
+ ngbChanged: !prevEmitted || prevEmitted.ngb !== bundle,
385
+ appBundleChanged: Boolean(
386
+ appBundleContent && (!prevEmitted || prevEmitted.appBundle !== appBundleContent),
387
+ ),
388
+ serverBundleChanged: Boolean(
389
+ serverBundleContent && (!prevEmitted || prevEmitted.serverBundle !== serverBundleContent),
390
+ ),
391
+ };
392
+ lastEmittedByOutDir.set(outDir, {
393
+ ngb: bundle,
394
+ appBundle: appBundleContent,
395
+ serverBundle: serverBundleContent,
396
+ });
397
+
398
+ const socketPath = resolve(outDir, 'hmr.sock');
399
+ if (existsSync(socketPath)) {
400
+ if (hmrDelta.ngbChanged) {
401
+ pushHmrReload(socketPath, bundle).then((res) => {
402
+ if (res.connected && res.response?.status === 'ok') {
403
+ console.log(`[Angular Native HMR] Pushed live bundle update over IPC -> ${socketPath}`);
404
+ }
405
+ });
406
+ }
407
+ if (hmrDelta.serverBundleChanged && serverBundleContent) {
408
+ pushHmrServerReload(socketPath, serverBundleContent).then((res) => {
409
+ if (res.connected && res.response?.status === 'ok') {
410
+ console.log(
411
+ `[Angular Native HMR] Pushed live server route reload over IPC -> ${socketPath}`,
412
+ );
413
+ }
414
+ });
415
+ }
416
+ }
417
+
418
+ return {
419
+ projectName,
420
+ version: resolvedVersion,
421
+ sourceRoot: sourceRootAbs,
422
+ bundleFile,
423
+ ...(entryBundleFile ? { entryBundleFile } : {}),
424
+ ...(serverBundleFile ? { serverBundleFile } : {}),
425
+ permissionsFile,
426
+ runtimeConfigFile,
427
+ permissions,
428
+ socketPath,
429
+ hmrDelta,
430
+ };
431
+ }
432
+
433
+ export function watchBundle(options = {}) {
434
+ const { sourceRoot } = compileBundle({ ...options, rebuildIcons: true });
435
+ console.log(`[Angular Native Watcher] Watching '${sourceRoot}' for changes...`);
436
+
437
+ let debounceTimer = null;
438
+ return watch(sourceRoot, { recursive: true }, (_eventType, filename) => {
439
+ if (!filename || !/\.(ts|html|css)$/.test(filename)) return;
440
+ if (debounceTimer) clearTimeout(debounceTimer);
441
+ debounceTimer = setTimeout(() => {
442
+ try {
443
+ compileBundle({ ...options, rebuildIcons: filename.endsWith('index.html') });
444
+ } catch (err) {
445
+ console.error('[Angular Native Watcher] Compilation error:', err);
446
+ }
447
+ }, 60);
448
+ });
449
+ }
450
+
451
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
452
+ const cliOptions = {
453
+ configPath: extractCliFlagValue(process.argv, '--config'),
454
+ projectName: extractCliFlagValue(process.argv, '--project'),
455
+ version: extractCliFlagValue(process.argv, '--version'),
456
+ };
457
+ if (process.argv.includes('--watch')) {
458
+ watchBundle(cliOptions);
459
+ } else {
460
+ compileBundle({ ...cliOptions, rebuildIcons: true });
461
+ }
462
+ }
@@ -0,0 +1,66 @@
1
+ export type NativeOsKind = 'auto' | 'linux' | 'windows' | 'macos';
2
+ export type NativeArchKind = 'auto' | 'x86_64' | 'aarch64' | 'universal';
3
+ export type NativeCpuProfile = 'auto' | 'native' | 'baseline' | 'avx2' | 'neon';
4
+ export type NativePlatformTarget = 'linux-gtk4' | 'windows-winui' | 'macos-appkit';
5
+ export type NativeJsEngineKind = 'jsc' | 'quickjs';
6
+ export type NativePackageFormat = 'deb' | 'appimage' | 'flatpak' | 'msi' | 'dmg';
7
+ export type LinuxPackageFormat = 'deb' | 'appimage' | 'flatpak';
8
+ export type NativePermissionsMode = 'auto' | 'strict';
9
+ export interface NativePermissionsOptions {
10
+ mode?: NativePermissionsMode;
11
+ allow?: string[];
12
+ deny?: string[];
13
+ }
14
+ export interface NativeBuilderOptions {
15
+ os?: NativeOsKind;
16
+ arch?: NativeArchKind;
17
+ cpu?: NativeCpuProfile;
18
+ targetPlatform?: NativePlatformTarget;
19
+ jsEngine?: NativeJsEngineKind;
20
+ outputPath?: string;
21
+ version?: string;
22
+ permissions?: NativePermissionsOptions;
23
+ packageFormats?: NativePackageFormat[];
24
+ }
25
+ export interface ResolvedNativeBuilderConfig {
26
+ os: 'linux' | 'windows' | 'macos';
27
+ arch: 'x86_64' | 'aarch64' | 'universal';
28
+ cpu: NativeCpuProfile;
29
+ targetPlatform: NativePlatformTarget;
30
+ jsEngine: NativeJsEngineKind;
31
+ outputPath: string;
32
+ rustTargetTriple: string;
33
+ packageFormats: NativePackageFormat[];
34
+ }
35
+ export interface NativeBuilderResult {
36
+ success: boolean;
37
+ projectName: string;
38
+ os: 'linux' | 'windows' | 'macos';
39
+ arch: 'x86_64' | 'aarch64' | 'universal';
40
+ cpu: NativeCpuProfile;
41
+ rustTargetTriple: string;
42
+ targetPlatform: NativePlatformTarget;
43
+ jsEngine: NativeJsEngineKind;
44
+ bundlePath: string;
45
+ permissionsManifestPath: string;
46
+ runtimeConfigPath: string;
47
+ packageArtifacts: string[];
48
+ }
49
+ /**
50
+ * Resolves minimal `angular.json` options (`os`, `arch`, `cpu`) into full target platform,
51
+ * embedded JS engine, Rust target triple, and output directory defaults.
52
+ */
53
+ export declare function resolveNativeBuilderConfig(projectName: string, options?: NativeBuilderOptions): ResolvedNativeBuilderConfig;
54
+ /**
55
+ * Generates an `angular.json` `architect.native` target configuration block
56
+ * for `@ng-desktop/builders:application`.
57
+ */
58
+ export declare function createNativeTargetConfig(options: NativeBuilderOptions): {
59
+ builder: '@ng-desktop/builders:application';
60
+ options: NativeBuilderOptions;
61
+ };
62
+ /**
63
+ * Executes the Angular 22 Native Builder pipeline, resolving minimal OS/CPU config,
64
+ * `.ngb` bundle path, and target distribution artifacts.
65
+ */
66
+ export declare function executeNativeBuilder(projectName: string, options: NativeBuilderOptions): NativeBuilderResult;
@@ -0,0 +1,123 @@
1
+ function detectHostOs() {
2
+ if (typeof process !== 'undefined') {
3
+ if (process.platform === 'win32')
4
+ return 'windows';
5
+ if (process.platform === 'darwin')
6
+ return 'macos';
7
+ }
8
+ return 'linux';
9
+ }
10
+ function detectHostArch() {
11
+ if (typeof process !== 'undefined' && process.arch === 'arm64') {
12
+ return 'aarch64';
13
+ }
14
+ return 'x86_64';
15
+ }
16
+ function resolveTargetTriple(os, arch) {
17
+ if (os === 'windows') {
18
+ return arch === 'aarch64' ? 'aarch64-pc-windows-msvc' : 'x86_64-pc-windows-msvc';
19
+ }
20
+ if (os === 'macos') {
21
+ if (arch === 'universal')
22
+ return 'universal-apple-darwin';
23
+ return arch === 'x86_64' ? 'x86_64-apple-darwin' : 'aarch64-apple-darwin';
24
+ }
25
+ return arch === 'aarch64' ? 'aarch64-unknown-linux-gnu' : 'x86_64-unknown-linux-gnu';
26
+ }
27
+ /**
28
+ * Resolves minimal `angular.json` options (`os`, `arch`, `cpu`) into full target platform,
29
+ * embedded JS engine, Rust target triple, and output directory defaults.
30
+ */
31
+ export function resolveNativeBuilderConfig(projectName, options = {}) {
32
+ let os;
33
+ if (options.os && options.os !== 'auto') {
34
+ os = options.os;
35
+ }
36
+ else if (options.targetPlatform === 'windows-winui') {
37
+ os = 'windows';
38
+ }
39
+ else if (options.targetPlatform === 'macos-appkit') {
40
+ os = 'macos';
41
+ }
42
+ else if (options.targetPlatform === 'linux-gtk4') {
43
+ os = 'linux';
44
+ }
45
+ else {
46
+ os = detectHostOs();
47
+ }
48
+ const targetPlatform = options.targetPlatform ??
49
+ (os === 'windows' ? 'windows-winui' : os === 'macos' ? 'macos-appkit' : 'linux-gtk4');
50
+ const jsEngine = options.jsEngine ?? (os === 'windows' ? 'quickjs' : 'jsc');
51
+ const arch = options.arch && options.arch !== 'auto' ? options.arch : detectHostArch();
52
+ const cpu = options.cpu ?? 'auto';
53
+ const outputPath = (options.outputPath ?? `dist/${projectName}`).replace(/\/+$/, '');
54
+ const defaultFormats = os === 'linux' ? ['deb', 'appimage', 'flatpak'] : os === 'windows' ? ['msi'] : ['dmg'];
55
+ return {
56
+ os,
57
+ arch,
58
+ cpu,
59
+ targetPlatform,
60
+ jsEngine,
61
+ outputPath,
62
+ rustTargetTriple: resolveTargetTriple(os, arch),
63
+ packageFormats: options.packageFormats ?? defaultFormats,
64
+ };
65
+ }
66
+ /**
67
+ * Generates an `angular.json` `architect.native` target configuration block
68
+ * for `@ng-desktop/builders:application`.
69
+ */
70
+ export function createNativeTargetConfig(options) {
71
+ return {
72
+ builder: '@ng-desktop/builders:application',
73
+ options: {
74
+ os: options.os ?? 'linux',
75
+ arch: options.arch ?? 'x86_64',
76
+ ...(options.cpu ? { cpu: options.cpu } : {}),
77
+ ...(options.targetPlatform ? { targetPlatform: options.targetPlatform } : {}),
78
+ ...(options.jsEngine ? { jsEngine: options.jsEngine } : {}),
79
+ ...(options.outputPath ? { outputPath: options.outputPath } : {}),
80
+ ...(options.packageFormats ? { packageFormats: options.packageFormats } : {}),
81
+ },
82
+ };
83
+ }
84
+ /**
85
+ * Executes the Angular 22 Native Builder pipeline, resolving minimal OS/CPU config,
86
+ * `.ngb` bundle path, and target distribution artifacts.
87
+ */
88
+ export function executeNativeBuilder(projectName, options) {
89
+ const resolved = resolveNativeBuilderConfig(projectName, options);
90
+ const packageArtifacts = [];
91
+ for (const fmt of resolved.packageFormats) {
92
+ if (fmt === 'deb') {
93
+ packageArtifacts.push(`${resolved.outputPath}/packages/deb/DEBIAN/control`);
94
+ packageArtifacts.push(`${resolved.outputPath}/packages/deb/usr/share/applications/${projectName}.desktop`);
95
+ }
96
+ else if (fmt === 'appimage') {
97
+ packageArtifacts.push(`${resolved.outputPath}/packages/appimage/AppRun`);
98
+ }
99
+ else if (fmt === 'flatpak') {
100
+ packageArtifacts.push(`${resolved.outputPath}/packages/flatpak/${projectName}.yml`);
101
+ }
102
+ else if (fmt === 'msi') {
103
+ packageArtifacts.push(`${resolved.outputPath}/packages/windows/${projectName}.msi`);
104
+ }
105
+ else if (fmt === 'dmg') {
106
+ packageArtifacts.push(`${resolved.outputPath}/packages/macos/${projectName}.dmg`);
107
+ }
108
+ }
109
+ return {
110
+ success: true,
111
+ projectName,
112
+ os: resolved.os,
113
+ arch: resolved.arch,
114
+ cpu: resolved.cpu,
115
+ rustTargetTriple: resolved.rustTargetTriple,
116
+ targetPlatform: resolved.targetPlatform,
117
+ jsEngine: resolved.jsEngine,
118
+ bundlePath: `${resolved.outputPath}/main.ngb`,
119
+ permissionsManifestPath: `${resolved.outputPath}/permissions.manifest.json`,
120
+ runtimeConfigPath: `${resolved.outputPath}/ng-desktop.runtime.json`,
121
+ packageArtifacts,
122
+ };
123
+ }
@@ -0,0 +1,26 @@
1
+ import {
2
+ ArchitectBuilderContextLike,
3
+ ArchitectBuilderObject,
4
+ NativeApplicationBuilderOptions,
5
+ NativeApplicationBuilderOutput,
6
+ } from './application-builder.mjs';
7
+
8
+ export interface NativeDevServerBuilderOptions extends NativeApplicationBuilderOptions {
9
+ watch?: boolean;
10
+ }
11
+
12
+ export interface NativeDevServerBuilderOutput extends NativeApplicationBuilderOutput {
13
+ watching: boolean;
14
+ }
15
+
16
+ export function runNativeDevServerBuilder(
17
+ options?: NativeDevServerBuilderOptions,
18
+ context?: ArchitectBuilderContextLike,
19
+ ): Promise<NativeDevServerBuilderOutput>;
20
+
21
+ export const devServerBuilder: ArchitectBuilderObject<
22
+ NativeDevServerBuilderOptions,
23
+ NativeDevServerBuilderOutput
24
+ >;
25
+
26
+ export default devServerBuilder;
@@ -0,0 +1,24 @@
1
+ import { createArchitectBuilder, runNativeApplicationBuilder } from './application-builder.mjs';
2
+ import { watchBundle } from './build-bundle.mjs';
3
+
4
+ export async function runNativeDevServerBuilder(options = {}, context = {}) {
5
+ const initial = await runNativeApplicationBuilder(options, context);
6
+ const watching = Boolean(options?.watch);
7
+ if (watching) {
8
+ const workspaceRoot = context?.workspaceRoot || options?.cwd || process.cwd();
9
+ const watcher = watchBundle({
10
+ cwd: workspaceRoot,
11
+ configPath: options?.configPath,
12
+ projectName: initial.projectName,
13
+ version: options?.version,
14
+ });
15
+ context?.addTeardown?.(() => watcher.close());
16
+ }
17
+ return {
18
+ ...initial,
19
+ watching,
20
+ };
21
+ }
22
+
23
+ export const devServerBuilder = createArchitectBuilder(runNativeDevServerBuilder);
24
+ export default devServerBuilder;