@ng-native/device 0.26.1 → 0.28.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 (48) hide show
  1. package/dist/accessibility.d.ts +5 -3
  2. package/dist/accessibility.js +5 -0
  3. package/dist/accessibility.js.map +1 -1
  4. package/dist/desktop-options.d.ts +5 -0
  5. package/dist/desktop-options.js +6 -1
  6. package/dist/desktop-options.js.map +1 -1
  7. package/dist/dialogs.js +4 -2
  8. package/dist/dialogs.js.map +1 -1
  9. package/dist/dock.d.ts +2 -0
  10. package/dist/dock.js +4 -1
  11. package/dist/dock.js.map +1 -1
  12. package/dist/menu-model.d.ts +11 -9
  13. package/dist/menu-model.js +72 -9
  14. package/dist/menu-model.js.map +1 -1
  15. package/dist/menus.d.ts +19 -0
  16. package/dist/menus.js +24 -3
  17. package/dist/menus.js.map +1 -1
  18. package/dist/os-support.d.ts +1 -1
  19. package/dist/os-support.js +188 -62
  20. package/dist/os-support.js.map +1 -1
  21. package/dist/os-version.d.ts +3 -1
  22. package/dist/os-version.js +3 -1
  23. package/dist/os-version.js.map +1 -1
  24. package/dist/os.d.ts +5 -3
  25. package/dist/os.js +5 -3
  26. package/dist/os.js.map +1 -1
  27. package/dist/processes.d.ts +2 -0
  28. package/dist/processes.js +4 -1
  29. package/dist/processes.js.map +1 -1
  30. package/dist/safe-area.d.ts +12 -3
  31. package/dist/safe-area.js +16 -4
  32. package/dist/safe-area.js.map +1 -1
  33. package/dist/sharing.js +4 -3
  34. package/dist/sharing.js.map +1 -1
  35. package/dist/shortcut.d.ts +2 -2
  36. package/dist/shortcut.js +37 -2
  37. package/dist/shortcut.js.map +1 -1
  38. package/dist/spawn-rules.js +8 -0
  39. package/dist/spawn-rules.js.map +1 -1
  40. package/dist/tray.d.ts +6 -3
  41. package/dist/tray.js +8 -4
  42. package/dist/tray.js.map +1 -1
  43. package/dist/vibration.d.ts +1 -1
  44. package/dist/vibration.js +3 -3
  45. package/dist/vibration.js.map +1 -1
  46. package/dist/window-restore.js +1 -1
  47. package/dist/window-restore.js.map +1 -1
  48. package/package.json +2 -2
@@ -81,6 +81,8 @@ export declare class Processes {
81
81
  /** Overridden in a test to start the app with an environment, and to fake programs. */
82
82
  static readonly SOURCE: InjectionToken<NativeProcesses | null>;
83
83
  private readonly native;
84
+ /** The OS the app runs on, whose template script rebuilds the host. */
85
+ private readonly os;
84
86
  private readonly capabilities;
85
87
  private readonly running;
86
88
  /**
package/dist/processes.js CHANGED
@@ -14,6 +14,7 @@
14
14
  * arrive on `ngNativeProcesses`.
15
15
  */
16
16
  import { InjectionToken, Service, inject, signal } from '@angular/core';
17
+ import { injectOs } from "./os.js";
17
18
  import { reactNative } from "./react-native.js";
18
19
  import { compileCapability, filterEnvironment, matchSpawn, } from "./spawn-rules.js";
19
20
  import * as i0 from "@angular/core";
@@ -60,6 +61,8 @@ export class Processes {
60
61
  /** Overridden in a test to start the app with an environment, and to fake programs. */
61
62
  static SOURCE = new InjectionToken('angular-native.processesSource', { factory: processesSource });
62
63
  native = inject(Processes.SOURCE);
64
+ /** The OS the app runs on, whose template script rebuilds the host. */
65
+ os = injectOs();
63
66
  capabilities = (this.native?.spawnCapabilities ?? []).map(compileCapability);
64
67
  running = new Map();
65
68
  /**
@@ -93,7 +96,7 @@ export class Processes {
93
96
  if (!match) {
94
97
  throw new UndeclaredCapabilityError(`[angular-native] ${program} ${JSON.stringify(args)} matches no spawn capability. ` +
95
98
  'Declare the program and its arguments in capabilities.spawn of the @ng-native/desktop ' +
96
- 'plugin options in app.json, then rebuild with npm run macos.');
99
+ `plugin options in app.json, then rebuild with npm run ${this.os}.`);
97
100
  }
98
101
  const env = filterEnvironment(options.env ?? this.env, native.envNames ?? Object.keys(this.env));
99
102
  this.spawning++;
@@ -1 +1 @@
1
- {"version":3,"file":"processes.js","sourceRoot":"","sources":["../src/processes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,cAAc,EA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AK;gBAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;gBACxB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;YAC3C,OAAO;QACT,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC1B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAClC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;YAC3D,OAAO;QACT,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;YAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IAED,8CAA8C;IAC9C,WAAW;QACT,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;IACvB,CAAC;uGA7HU,SAAS;wGAAT,SAAS;;2FAAT,SAAS;kBADrB,OAAO","sourcesContent":["/**\n * `Processes`: the app's environment on a desktop OS, and the programs it declares, run with\n * `spawn`. Absent on iOS, Android and the web, which give an app neither.\n *\n * The host contract, on the `NgNativeProcesses` module:\n *\n * - `getConstants()` answers `env` (the environment, already filtered to `capabilities.env`),\n * `envNames` (`capabilities.env` itself), `spawn` (the declared spawn capabilities) and `resolved` (where each declared bare name was\n * pinned at startup, or null where it is absent).\n * - `spawn(program, args, cwd, env)` runs the program, never through a shell, after checking the\n * call against the declaration again, and answers a handle; it rejects an undeclared call.\n * - `write(handle, data)`, `closeStdin(handle)` and `kill(handle, signal)`.\n * - `{ type: 'stdout' | 'stderr', handle, data }` and `{ type: 'exit', handle, code, signal }`\n * arrive on `ngNativeProcesses`.\n */\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { reactNative } from './react-native.ts';\nimport {\n compileCapability,\n filterEnvironment,\n matchSpawn,\n type CompiledCapability,\n type SpawnCapability,\n} from './spawn-rules.ts';\n\n/** How a spawned program ended: its exit code, or the signal that stopped it. */\nexport interface ProcessExit {\n readonly code: number | null;\n readonly signal: string | null;\n}\n\n/** What the host reports about a spawned program. */\nexport type ProcessEvent =\n | { readonly type: 'stdout' | 'stderr'; readonly handle: number; readonly data: string }\n | {\n readonly type: 'exit';\n readonly handle: number;\n readonly code: number | null;\n readonly signal: string | null;\n };\n\n/** What the desktop host's module reports, and what a test fakes. */\nexport interface NativeProcesses {\n /** The environment variables the app was started with, filtered to those it declares. */\n readonly env: Readonly<Record<string, string>>;\n /** The variables `capabilities.env` declares: all a spawned program may be given. */\n readonly envNames?: readonly string[];\n /** The declared spawn capabilities. None declared, nothing may be spawned. */\n readonly spawnCapabilities?: readonly SpawnCapability[];\n /** Where each declared bare program name was pinned at startup, or null where it is absent. */\n readonly resolved?: Readonly<Record<string, string | null>>;\n spawn?(\n program: string,\n args: readonly string[],\n cwd: string | null,\n env: Readonly<Record<string, string>>,\n ): Promise<number>;\n write?(handle: number, data: string): void;\n closeStdin?(handle: number): void;\n kill?(handle: number, signal: string): void;\n subscribe?(listener: (event: ProcessEvent) => void): () => void;\n}\n\n/** A program `spawn` started. */\nexport interface ChildProcess {\n /** Settles once the program has ended. */\n readonly exit: Promise<ProcessExit>;\n /** Hear what the program writes to standard output. Answers the function that stops it. */\n onStdout(listener: (chunk: string) => void): () => void;\n /** Hear what the program writes to standard error. */\n onStderr(listener: (chunk: string) => void): () => void;\n /** Write to the program's standard input. */\n write(data: string): void;\n /** Close the program's standard input. */\n end(): void;\n /** Stop the program. `SIGTERM` unless it says. */\n kill(signal?: 'SIGTERM' | 'SIGINT' | 'SIGKILL' | 'SIGHUP'): void;\n}\n\n/** What `spawn` takes beside the program and its arguments. */\nexport interface SpawnOptions {\n /** The working directory. The app's own when unset. */\n readonly cwd?: string;\n /**\n * The program's environment. Only the variables the app declares in `capabilities.env` are\n * passed; the rest are left out. Unset, it gets `Processes.env`.\n */\n readonly env?: Readonly<Record<string, string>>;\n}\n\n/** A spawn the app did not declare: a misconfiguration, so it throws rather than doing nothing. */\nexport class UndeclaredCapabilityError extends Error {\n override readonly name = 'UndeclaredCapabilityError';\n}\n\n/** The desktop host's TurboModule. */\ninterface ProcessesTurboModule {\n getConstants?(): {\n env?: Record<string, string>;\n envNames?: string[];\n spawn?: SpawnCapability[];\n resolved?: Record<string, string | null>;\n };\n spawn?(program: string, args: string[], cwd: string | null, env: object): Promise<number>;\n write?(handle: number, data: string): void;\n closeStdin?(handle: number): void;\n kill?(handle: number, signal: string): void;\n}\n\n/** React Native's event emitter, which the host's process events arrive on. */\ntype Emitter = {\n addListener(event: string, listener: (event: unknown) => void): { remove(): void };\n};\n\n/** The desktop host's module, or null where there is none: every OS but a desktop one. */\nfunction processesSource(): NativeProcesses | null {\n const native = reactNative() as {\n TurboModuleRegistry?: { get?(name: string): unknown };\n DeviceEventEmitter?: Emitter;\n } | null;\n const module = native?.TurboModuleRegistry?.get?.('NgNativeProcesses') as\n ProcessesTurboModule | null | undefined;\n const constants = module?.getConstants?.();\n if (!module || !constants?.env) return null;\n return {\n ...declared(constants.env, constants),\n ...processMethods(module, native?.DeviceEventEmitter),\n };\n}\n\n/** What the host's constants declare, with what an older host leaves out filled in. */\nfunction declared(\n env: Record<string, string>,\n constants: ReturnType<NonNullable<ProcessesTurboModule['getConstants']>>,\n) {\n return {\n env,\n envNames: constants.envNames ?? Object.keys(env),\n spawnCapabilities: constants.spawn ?? [],\n resolved: constants.resolved ?? {},\n };\n}\n\n/** The module's methods, as the service calls them. */\nfunction processMethods(module: ProcessesTurboModule, emitter: Emitter | undefined) {\n return {\n spawn:\n module.spawn &&\n ((...call: Parameters<NonNullable<NativeProcesses['spawn']>>) =>\n module.spawn!(call[0], [...call[1]], call[2], call[3])),\n write: (handle: number, data: string) => module.write?.(handle, data),\n closeStdin: (handle: number) => module.closeStdin?.(handle),\n kill: (handle: number, signal: string) => module.kill?.(handle, signal),\n subscribe: (listener: (event: ProcessEvent) => void) => {\n const subscription = emitter?.addListener('ngNativeProcesses', (event) =>\n listener(event as ProcessEvent),\n );\n return () => subscription?.remove();\n },\n };\n}\n\n/** One spawned program's listeners, until it exits. */\ninterface Running {\n readonly stdout: Set<(chunk: string) => void>;\n readonly stderr: Set<(chunk: string) => void>;\n exited(exit: ProcessExit): void;\n}\n\n@Service()\nexport class Processes {\n /** Overridden in a test to start the app with an environment, and to fake programs. */\n static readonly SOURCE = new InjectionToken<NativeProcesses | null>(\n 'angular-native.processesSource',\n { factory: processesSource },\n );\n\n private readonly native = inject(Processes.SOURCE);\n private readonly capabilities: readonly CompiledCapability[] = (\n this.native?.spawnCapabilities ?? []\n ).map(compileCapability);\n private readonly running = new Map<number, Running>();\n /**\n * What the host said of a program before its spawn resolved with the handle: its reader threads\n * can queue a short program's output and exit ahead of that answer.\n */\n private readonly early = new Map<number, ProcessEvent[]>();\n /** Spawns waiting on the host, while which an unknown handle's events are kept. */\n private spawning = 0;\n /** Held events not yet replayed, by handle: live ones queue behind them, in order. */\n private readonly replaying = new Map<number, ProcessEvent[]>();\n private readonly unsubscribe = this.native?.subscribe?.((event) => this.heard(event)) ?? null;\n\n /** Whether the OS gives the app processes: a desktop OS with the desktop host's module. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /** The environment variables, as the app was started with them. Empty where absent. */\n readonly env: Readonly<Record<string, string>> = Object.freeze({ ...this.native?.env });\n\n /**\n * Run `program` with `args`, never through a shell. The call has to match a capability the app\n * declares in app.json; one that does not throws `UndeclaredCapabilityError`. Resolves to null\n * where processes are absent.\n *\n * const git = await processes.spawn('git', ['status', '--porcelain'], { cwd: repo });\n * git?.onStdout((chunk) => output.update((text) => text + chunk));\n * const { code } = (await git?.exit) ?? { code: null };\n */\n async spawn(\n program: string,\n args: readonly string[] = [],\n options: SpawnOptions = {},\n ): Promise<ChildProcess | null> {\n const native = this.native;\n if (!native?.spawn) return null;\n const match = matchSpawn(this.capabilities, program, args, native.resolved ?? {});\n if (!match) {\n throw new UndeclaredCapabilityError(\n `[angular-native] ${program} ${JSON.stringify(args)} matches no spawn capability. ` +\n 'Declare the program and its arguments in capabilities.spawn of the @ng-native/desktop ' +\n 'plugin options in app.json, then rebuild with npm run macos.',\n );\n }\n const env = filterEnvironment(\n options.env ?? this.env,\n native.envNames ?? Object.keys(this.env),\n );\n this.spawning++;\n let handle: number;\n try {\n handle = await native.spawn(match.path, args, options.cwd ?? null, env);\n } finally {\n this.spawning--;\n }\n const child = this.child(native, handle);\n // Nothing is waiting for the rest: they were another program's, gone before the app heard it.\n if (!this.spawning) this.early.clear();\n return child;\n }\n\n private child(native: NativeProcesses, handle: number): ChildProcess {\n const stdout = new Set<(chunk: string) => void>();\n const stderr = new Set<(chunk: string) => void>();\n let exited!: (exit: ProcessExit) => void;\n const exit = new Promise<ProcessExit>((resolve) => (exited = resolve));\n this.running.set(handle, { stdout, stderr, exited });\n const early = this.early.get(handle);\n if (early) {\n this.early.delete(handle);\n this.replaying.set(handle, early);\n // A turn later, as the host's events arrive, so the caller has listened by then.\n setTimeout(() => {\n this.replaying.delete(handle);\n early.forEach((event) => this.heard(event));\n }, 0);\n }\n const listen = (set: Set<(chunk: string) => void>, listener: (chunk: string) => void) => {\n set.add(listener);\n return () => void set.delete(listener);\n };\n return {\n exit,\n onStdout: (listener) => listen(stdout, listener),\n onStderr: (listener) => listen(stderr, listener),\n write: (data) => native.write?.(handle, data),\n end: () => native.closeStdin?.(handle),\n kill: (signal = 'SIGTERM') => native.kill?.(handle, signal),\n };\n }\n\n private heard(event: ProcessEvent): void {\n const queued = this.replaying.get(event.handle);\n if (queued) {\n queued.push(event);\n return;\n }\n const running = this.running.get(event.handle);\n if (!running) {\n if (!this.spawning) return;\n const early = this.early.get(event.handle);\n if (early) early.push(event);\n else this.early.set(event.handle, [event]);\n return;\n }\n if (event.type === 'exit') {\n this.running.delete(event.handle);\n running.exited({ code: event.code, signal: event.signal });\n return;\n }\n for (const listener of running[event.type]) listener(event.data);\n }\n\n /** Stop hearing the host, as the app goes. */\n ngOnDestroy(): void {\n this.unsubscribe?.();\n }\n}\n"]}
1
+ {"version":3,"file":"processes.js","sourceRoot":"","sources":["../src/processes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAe,MAAM,eAAe,CAAC;AACrF,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,UAAU,GAGX,MAAM,kBAAkB,CAAC;;AAmE1B,mGAAmG;AACnG,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IAChC,IAAI,GAAG,2BAA2B,CAAC;CACtD;AAqBD,0FAA0F;AAC1F,SAAS,eAAe;IACtB,MAAM,MAAM,GAAG,WAAW,EAGlB,CAAC;IACT,MAAM,MAAM,GAAG,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,CAAC,mBAAmB,CAC5B,CAAC;IAC1C,MAAM,SAAS,GAAG,MAAM,EAAE,YAAY,EAAE,EAAE,CAAC;IAC3C,IAAI,CAAC,MAAM,IAAI,CAAC,SAAS,EAAE,GAAG;QAAE,OAAO,IAAI,CAAC;IAC5C,OAAO;QACL,GAAG,QAAQ,CAAC,SAAS,CAAC,GAAG,EAAE,SAAS,CAAC;QACrC,GAAG,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,kBAAkB,CAAC;KACtD,CAAC;AACJ,CAAC;AAED,uFAAuF;AACvF,SAAS,QAAQ,CACf,GAA2B,EAC3B,SAAwE;IAExE,OAAO;QACL,GAAG;QACH,QAAQ,EAAE,SAAS,CAAC,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;QAChD,iBAAiB,EAAE,SAAS,C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AM,EAAE,CAAC;YACX,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACnB,OAAO;QACT,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QAC/C,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,IAAI,CAAC,IAAI,CAAC,QAAQ;gBAAE,OAAO;YAC3B,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAC3C,IAAI,KAAK;gBAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;gBACxB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;YAC3C,OAAO;QACT,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC1B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YAClC,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;YAC3D,OAAO;QACT,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;YAAE,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACnE,CAAC;IAED,8CAA8C;IAC9C,WAAW;QACT,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;IACvB,CAAC;uGA/HU,SAAS;wGAAT,SAAS;;2FAAT,SAAS;kBADrB,OAAO","sourcesContent":["/**\n * `Processes`: the app's environment on a desktop OS, and the programs it declares, run with\n * `spawn`. Absent on iOS, Android and the web, which give an app neither.\n *\n * The host contract, on the `NgNativeProcesses` module:\n *\n * - `getConstants()` answers `env` (the environment, already filtered to `capabilities.env`),\n * `envNames` (`capabilities.env` itself), `spawn` (the declared spawn capabilities) and `resolved` (where each declared bare name was\n * pinned at startup, or null where it is absent).\n * - `spawn(program, args, cwd, env)` runs the program, never through a shell, after checking the\n * call against the declaration again, and answers a handle; it rejects an undeclared call.\n * - `write(handle, data)`, `closeStdin(handle)` and `kill(handle, signal)`.\n * - `{ type: 'stdout' | 'stderr', handle, data }` and `{ type: 'exit', handle, code, signal }`\n * arrive on `ngNativeProcesses`.\n */\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { injectOs } from './os.ts';\nimport { reactNative } from './react-native.ts';\nimport {\n compileCapability,\n filterEnvironment,\n matchSpawn,\n type CompiledCapability,\n type SpawnCapability,\n} from './spawn-rules.ts';\n\n/** How a spawned program ended: its exit code, or the signal that stopped it. */\nexport interface ProcessExit {\n readonly code: number | null;\n readonly signal: string | null;\n}\n\n/** What the host reports about a spawned program. */\nexport type ProcessEvent =\n | { readonly type: 'stdout' | 'stderr'; readonly handle: number; readonly data: string }\n | {\n readonly type: 'exit';\n readonly handle: number;\n readonly code: number | null;\n readonly signal: string | null;\n };\n\n/** What the desktop host's module reports, and what a test fakes. */\nexport interface NativeProcesses {\n /** The environment variables the app was started with, filtered to those it declares. */\n readonly env: Readonly<Record<string, string>>;\n /** The variables `capabilities.env` declares: all a spawned program may be given. */\n readonly envNames?: readonly string[];\n /** The declared spawn capabilities. None declared, nothing may be spawned. */\n readonly spawnCapabilities?: readonly SpawnCapability[];\n /** Where each declared bare program name was pinned at startup, or null where it is absent. */\n readonly resolved?: Readonly<Record<string, string | null>>;\n spawn?(\n program: string,\n args: readonly string[],\n cwd: string | null,\n env: Readonly<Record<string, string>>,\n ): Promise<number>;\n write?(handle: number, data: string): void;\n closeStdin?(handle: number): void;\n kill?(handle: number, signal: string): void;\n subscribe?(listener: (event: ProcessEvent) => void): () => void;\n}\n\n/** A program `spawn` started. */\nexport interface ChildProcess {\n /** Settles once the program has ended. */\n readonly exit: Promise<ProcessExit>;\n /** Hear what the program writes to standard output. Answers the function that stops it. */\n onStdout(listener: (chunk: string) => void): () => void;\n /** Hear what the program writes to standard error. */\n onStderr(listener: (chunk: string) => void): () => void;\n /** Write to the program's standard input. */\n write(data: string): void;\n /** Close the program's standard input. */\n end(): void;\n /** Stop the program. `SIGTERM` unless it says. */\n kill(signal?: 'SIGTERM' | 'SIGINT' | 'SIGKILL' | 'SIGHUP'): void;\n}\n\n/** What `spawn` takes beside the program and its arguments. */\nexport interface SpawnOptions {\n /** The working directory. The app's own when unset. */\n readonly cwd?: string;\n /**\n * The program's environment. Only the variables the app declares in `capabilities.env` are\n * passed; the rest are left out. Unset, it gets `Processes.env`.\n */\n readonly env?: Readonly<Record<string, string>>;\n}\n\n/** A spawn the app did not declare: a misconfiguration, so it throws rather than doing nothing. */\nexport class UndeclaredCapabilityError extends Error {\n override readonly name = 'UndeclaredCapabilityError';\n}\n\n/** The desktop host's TurboModule. */\ninterface ProcessesTurboModule {\n getConstants?(): {\n env?: Record<string, string>;\n envNames?: string[];\n spawn?: SpawnCapability[];\n resolved?: Record<string, string | null>;\n };\n spawn?(program: string, args: string[], cwd: string | null, env: object): Promise<number>;\n write?(handle: number, data: string): void;\n closeStdin?(handle: number): void;\n kill?(handle: number, signal: string): void;\n}\n\n/** React Native's event emitter, which the host's process events arrive on. */\ntype Emitter = {\n addListener(event: string, listener: (event: unknown) => void): { remove(): void };\n};\n\n/** The desktop host's module, or null where there is none: every OS but a desktop one. */\nfunction processesSource(): NativeProcesses | null {\n const native = reactNative() as {\n TurboModuleRegistry?: { get?(name: string): unknown };\n DeviceEventEmitter?: Emitter;\n } | null;\n const module = native?.TurboModuleRegistry?.get?.('NgNativeProcesses') as\n ProcessesTurboModule | null | undefined;\n const constants = module?.getConstants?.();\n if (!module || !constants?.env) return null;\n return {\n ...declared(constants.env, constants),\n ...processMethods(module, native?.DeviceEventEmitter),\n };\n}\n\n/** What the host's constants declare, with what an older host leaves out filled in. */\nfunction declared(\n env: Record<string, string>,\n constants: ReturnType<NonNullable<ProcessesTurboModule['getConstants']>>,\n) {\n return {\n env,\n envNames: constants.envNames ?? Object.keys(env),\n spawnCapabilities: constants.spawn ?? [],\n resolved: constants.resolved ?? {},\n };\n}\n\n/** The module's methods, as the service calls them. */\nfunction processMethods(module: ProcessesTurboModule, emitter: Emitter | undefined) {\n return {\n spawn:\n module.spawn &&\n ((...call: Parameters<NonNullable<NativeProcesses['spawn']>>) =>\n module.spawn!(call[0], [...call[1]], call[2], call[3])),\n write: (handle: number, data: string) => module.write?.(handle, data),\n closeStdin: (handle: number) => module.closeStdin?.(handle),\n kill: (handle: number, signal: string) => module.kill?.(handle, signal),\n subscribe: (listener: (event: ProcessEvent) => void) => {\n const subscription = emitter?.addListener('ngNativeProcesses', (event) =>\n listener(event as ProcessEvent),\n );\n return () => subscription?.remove();\n },\n };\n}\n\n/** One spawned program's listeners, until it exits. */\ninterface Running {\n readonly stdout: Set<(chunk: string) => void>;\n readonly stderr: Set<(chunk: string) => void>;\n exited(exit: ProcessExit): void;\n}\n\n@Service()\nexport class Processes {\n /** Overridden in a test to start the app with an environment, and to fake programs. */\n static readonly SOURCE = new InjectionToken<NativeProcesses | null>(\n 'angular-native.processesSource',\n { factory: processesSource },\n );\n\n private readonly native = inject(Processes.SOURCE);\n /** The OS the app runs on, whose template script rebuilds the host. */\n private readonly os = injectOs();\n private readonly capabilities: readonly CompiledCapability[] = (\n this.native?.spawnCapabilities ?? []\n ).map(compileCapability);\n private readonly running = new Map<number, Running>();\n /**\n * What the host said of a program before its spawn resolved with the handle: its reader threads\n * can queue a short program's output and exit ahead of that answer.\n */\n private readonly early = new Map<number, ProcessEvent[]>();\n /** Spawns waiting on the host, while which an unknown handle's events are kept. */\n private spawning = 0;\n /** Held events not yet replayed, by handle: live ones queue behind them, in order. */\n private readonly replaying = new Map<number, ProcessEvent[]>();\n private readonly unsubscribe = this.native?.subscribe?.((event) => this.heard(event)) ?? null;\n\n /** Whether the OS gives the app processes: a desktop OS with the desktop host's module. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /** The environment variables, as the app was started with them. Empty where absent. */\n readonly env: Readonly<Record<string, string>> = Object.freeze({ ...this.native?.env });\n\n /**\n * Run `program` with `args`, never through a shell. The call has to match a capability the app\n * declares in app.json; one that does not throws `UndeclaredCapabilityError`. Resolves to null\n * where processes are absent.\n *\n * const git = await processes.spawn('git', ['status', '--porcelain'], { cwd: repo });\n * git?.onStdout((chunk) => output.update((text) => text + chunk));\n * const { code } = (await git?.exit) ?? { code: null };\n */\n async spawn(\n program: string,\n args: readonly string[] = [],\n options: SpawnOptions = {},\n ): Promise<ChildProcess | null> {\n const native = this.native;\n if (!native?.spawn) return null;\n const match = matchSpawn(this.capabilities, program, args, native.resolved ?? {});\n if (!match) {\n throw new UndeclaredCapabilityError(\n `[angular-native] ${program} ${JSON.stringify(args)} matches no spawn capability. ` +\n 'Declare the program and its arguments in capabilities.spawn of the @ng-native/desktop ' +\n `plugin options in app.json, then rebuild with npm run ${this.os}.`,\n );\n }\n const env = filterEnvironment(\n options.env ?? this.env,\n native.envNames ?? Object.keys(this.env),\n );\n this.spawning++;\n let handle: number;\n try {\n handle = await native.spawn(match.path, args, options.cwd ?? null, env);\n } finally {\n this.spawning--;\n }\n const child = this.child(native, handle);\n // Nothing is waiting for the rest: they were another program's, gone before the app heard it.\n if (!this.spawning) this.early.clear();\n return child;\n }\n\n private child(native: NativeProcesses, handle: number): ChildProcess {\n const stdout = new Set<(chunk: string) => void>();\n const stderr = new Set<(chunk: string) => void>();\n let exited!: (exit: ProcessExit) => void;\n const exit = new Promise<ProcessExit>((resolve) => (exited = resolve));\n this.running.set(handle, { stdout, stderr, exited });\n const early = this.early.get(handle);\n if (early) {\n this.early.delete(handle);\n this.replaying.set(handle, early);\n // A turn later, as the host's events arrive, so the caller has listened by then.\n setTimeout(() => {\n this.replaying.delete(handle);\n early.forEach((event) => this.heard(event));\n }, 0);\n }\n const listen = (set: Set<(chunk: string) => void>, listener: (chunk: string) => void) => {\n set.add(listener);\n return () => void set.delete(listener);\n };\n return {\n exit,\n onStdout: (listener) => listen(stdout, listener),\n onStderr: (listener) => listen(stderr, listener),\n write: (data) => native.write?.(handle, data),\n end: () => native.closeStdin?.(handle),\n kill: (signal = 'SIGTERM') => native.kill?.(handle, signal),\n };\n }\n\n private heard(event: ProcessEvent): void {\n const queued = this.replaying.get(event.handle);\n if (queued) {\n queued.push(event);\n return;\n }\n const running = this.running.get(event.handle);\n if (!running) {\n if (!this.spawning) return;\n const early = this.early.get(event.handle);\n if (early) early.push(event);\n else this.early.set(event.handle, [event]);\n return;\n }\n if (event.type === 'exit') {\n this.running.delete(event.handle);\n running.exited({ code: event.code, signal: event.signal });\n return;\n }\n for (const listener of running[event.type]) listener(event.data);\n }\n\n /** Stop hearing the host, as the app goes. */\n ngOnDestroy(): void {\n this.unsubscribe?.();\n }\n}\n"]}
@@ -33,6 +33,7 @@ export declare class SafeArea {
33
33
  private readonly current;
34
34
  private readonly measured;
35
35
  private readonly controls;
36
+ private readonly trailingControls;
36
37
  /** What each provider still up last reported, the latest last. */
37
38
  private readonly reports;
38
39
  private reporter;
@@ -50,17 +51,25 @@ export declare class SafeArea {
50
51
  * On macOS, how far the window's close, minimise and zoom buttons reach into the reporting
51
52
  * pane from its leading edge: what `--safe-area-inset-titlebar-leading` holds. Their width in a
52
53
  * window with no sidebar and in the sidebar pane under them; zero in the content pane beside a
53
- * sidebar, which they do not reach, and on every other OS. One value for the app: the latest
54
- * report's, not one per pane.
54
+ * sidebar, which they do not reach. On Linux, the reach of the window controls on the leading
55
+ * side, in a window whose content runs under its header bar; zero on every other OS. One value
56
+ * for the app: the latest report's, not one per pane.
55
57
  */
56
58
  readonly titlebarLeading: Signal<number>;
59
+ /**
60
+ * How far a desktop window's title bar controls reach into the reporting pane from its trailing
61
+ * edge: what `--safe-area-inset-titlebar-trailing` holds. Zero on macOS, whose controls are on
62
+ * the leading side, on Linux in a window whose content stays below its header bar (the default
63
+ * title bar), and on every OS with no title bar. One value for the app, as `titlebarLeading` is.
64
+ */
65
+ readonly titlebarTrailing: Signal<number>;
57
66
  /** Whether anything has reported yet, for a layout that would rather wait than jump. */
58
67
  readonly known: Signal<boolean>;
59
68
  /**
60
69
  * Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from
61
70
  * anywhere else is a number that stops matching the screen the moment the device rotates.
62
71
  */
63
- report(insets: Insets, frame: Frame, from?: object, titlebarLeading?: number): void;
72
+ report(insets: Insets, frame: Frame, from?: object, titlebarLeading?: number, titlebarTrailing?: number): void;
64
73
  /**
65
74
  * Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the
66
75
  * latest, what a provider still up last reported takes its place, or nothing when none is.
package/dist/safe-area.js CHANGED
@@ -25,6 +25,8 @@ export class SafeArea {
25
25
  ...(ngDevMode ? [{ debugName: "measured" }] : /* istanbul ignore next */ []));
26
26
  controls = signal(0, /* @ts-ignore */
27
27
  ...(ngDevMode ? [{ debugName: "controls" }] : /* istanbul ignore next */ []));
28
+ trailingControls = signal(0, /* @ts-ignore */
29
+ ...(ngDevMode ? [{ debugName: "trailingControls" }] : /* istanbul ignore next */ []));
28
30
  /** What each provider still up last reported, the latest last. */
29
31
  reports = new Map();
30
32
  reporter = null;
@@ -42,10 +44,18 @@ export class SafeArea {
42
44
  * On macOS, how far the window's close, minimise and zoom buttons reach into the reporting
43
45
  * pane from its leading edge: what `--safe-area-inset-titlebar-leading` holds. Their width in a
44
46
  * window with no sidebar and in the sidebar pane under them; zero in the content pane beside a
45
- * sidebar, which they do not reach, and on every other OS. One value for the app: the latest
46
- * report's, not one per pane.
47
+ * sidebar, which they do not reach. On Linux, the reach of the window controls on the leading
48
+ * side, in a window whose content runs under its header bar; zero on every other OS. One value
49
+ * for the app: the latest report's, not one per pane.
47
50
  */
48
51
  titlebarLeading = this.controls.asReadonly();
52
+ /**
53
+ * How far a desktop window's title bar controls reach into the reporting pane from its trailing
54
+ * edge: what `--safe-area-inset-titlebar-trailing` holds. Zero on macOS, whose controls are on
55
+ * the leading side, on Linux in a window whose content stays below its header bar (the default
56
+ * title bar), and on every OS with no title bar. One value for the app, as `titlebarLeading` is.
57
+ */
58
+ titlebarTrailing = this.trailingControls.asReadonly();
49
59
  /** Whether anything has reported yet, for a layout that would rather wait than jump. */
50
60
  known = computed(() => this.measured() !== null, /* @ts-ignore */
51
61
  ...(ngDevMode ? [{ debugName: "known" }] : /* istanbul ignore next */ []));
@@ -53,15 +63,16 @@ export class SafeArea {
53
63
  * Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from
54
64
  * anywhere else is a number that stops matching the screen the moment the device rotates.
55
65
  */
56
- report(insets, frame, from, titlebarLeading = 0) {
66
+ report(insets, frame, from, titlebarLeading = 0, titlebarTrailing = 0) {
57
67
  this.current.set(insets);
58
68
  this.measured.set(frame);
59
69
  this.controls.set(titlebarLeading);
70
+ this.trailingControls.set(titlebarTrailing);
60
71
  this.reporter = from ?? null;
61
72
  if (!from)
62
73
  return;
63
74
  this.reports.delete(from);
64
- this.reports.set(from, { insets, frame, titlebarLeading });
75
+ this.reports.set(from, { insets, frame, titlebarLeading, titlebarTrailing });
65
76
  }
66
77
  /**
67
78
  * Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the
@@ -77,6 +88,7 @@ export class SafeArea {
77
88
  this.current.set(previous?.[1].insets ?? NOTHING);
78
89
  this.measured.set(previous?.[1].frame ?? null);
79
90
  this.controls.set(previous?.[1].titlebarLeading ?? 0);
91
+ this.trailingControls.set(previous?.[1].titlebarTrailing ?? 0);
80
92
  return true;
81
93
  }
82
94
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.2.0", ngImport: i0, type: SafeArea, deps: [], target: i0.ɵɵFactoryTarget.Service });
@@ -1 +1 @@
1
- {"version":3,"file":"safe-area.js","sourceRoot":"","sources":["../src/safe-area.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,OAAO,EAAE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AI;YAAE,OAAO;QAClB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC,CAAC;IAC7D,CAAC;IAED;;;;OAIG;IACH,QAAQ,CAAC,IAAY;QACnB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI;YAAE,OAAO,KAAK,CAAC;QACzC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/C,IAAI,CAAC,QAAQ,GAAG,QAAQ,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;QACtC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC;QAClD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,eAAe,IAAI,CAAC,CAAC,CAAC;QACtD,OAAO,IAAI,CAAC;IACd,CAAC;uGAlEU,QAAQ;wGAAR,QAAQ;;2FAAR,QAAQ;kBADpB,OAAO","sourcesContent":["/**\n * How much of the screen belongs to the system: the notch, the status bar, the home indicator,\n * a rounded corner, and on Android the display cutout and the navigation bar.\n *\n * Unlike everything else here, this has no React Native module behind it. Insets are a property\n * of a *view*, not of the device, and the only thing that can report them is a native view inside\n * the window - `<safe-area-provider>` in `@ng-native/components`, which pushes what it\n * measures in here. That is also why the values start at zero: nothing is known until a view has\n * been laid out, which is one frame after the app mounts.\n *\n * Most layouts should not read this at all. A `<safe-area-view>` applies the insets natively,\n * without a round trip through JavaScript, and a screen in a native stack has its header do it.\n * This is for the cases neither covers: a floating button that must clear the home indicator, a\n * scroll view whose content inset is computed, a sheet drawing its own chrome.\n */\nimport { Service, computed, signal, type Signal } from '@angular/core';\n\nexport interface Insets {\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n readonly left: number;\n}\n\nexport interface Frame {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\nconst NOTHING: Insets = { top: 0, right: 0, bottom: 0, left: 0 };\n\n@Service()\nexport class SafeArea {\n /** Whether the service is here: on every OS, where it answers what the OS reports. */\n readonly available: Signal<boolean> = signal(true).asReadonly();\n\n private readonly current = signal<Insets>(NOTHING);\n private readonly measured = signal<Frame | null>(null);\n private readonly controls = signal(0);\n /** What each provider still up last reported, the latest last. */\n private readonly reports = new Map<\n object,\n { insets: Insets; frame: Frame; titlebarLeading: number }\n >();\n private reporter: object | null = null;\n\n /** What the system occupies on each edge, in points. */\n readonly insets: Signal<Insets> = this.current.asReadonly();\n\n /**\n * The provider's own frame: the area it was handed to lay out in.\n *\n * On Android 15 that includes the system bars, because the app draws behind them - which is why\n * `Screen.window` reads this rather than `Dimensions`. Null until the provider has laid out,\n * one frame after the app mounts, and again once every provider that reported is destroyed.\n */\n readonly frame: Signal<Frame | null> = this.measured.asReadonly();\n\n /**\n * On macOS, how far the window's close, minimise and zoom buttons reach into the reporting\n * pane from its leading edge: what `--safe-area-inset-titlebar-leading` holds. Their width in a\n * window with no sidebar and in the sidebar pane under them; zero in the content pane beside a\n * sidebar, which they do not reach, and on every other OS. One value for the app: the latest\n * report's, not one per pane.\n */\n readonly titlebarLeading: Signal<number> = this.controls.asReadonly();\n\n /** Whether anything has reported yet, for a layout that would rather wait than jump. */\n readonly known = computed(() => this.measured() !== null);\n\n /**\n * Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from\n * anywhere else is a number that stops matching the screen the moment the device rotates.\n */\n report(insets: Insets, frame: Frame, from?: object, titlebarLeading = 0): void {\n this.current.set(insets);\n this.measured.set(frame);\n this.controls.set(titlebarLeading);\n this.reporter = from ?? null;\n if (!from) return;\n this.reports.delete(from);\n this.reports.set(from, { insets, frame, titlebarLeading });\n }\n\n /**\n * Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the\n * latest, what a provider still up last reported takes its place, or nothing when none is.\n * True when the values changed.\n */\n withdraw(from: object): boolean {\n this.reports.delete(from);\n if (this.reporter !== from) return false;\n const [previous] = [...this.reports].slice(-1);\n this.reporter = previous?.[0] ?? null;\n this.current.set(previous?.[1].insets ?? NOTHING);\n this.measured.set(previous?.[1].frame ?? null);\n this.controls.set(previous?.[1].titlebarLeading ?? 0);\n return true;\n }\n}\n"]}
1
+ {"version":3,"file":"safe-area.js","sourceRoot":"","sources":["../src/safe-area.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAe,MAAM,eAAe,CAAC;;AAgBvE,MAAM,OAAO,GAAW,EAAE,GAAG,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;AAGjE,MAAM,OAAO,QAAQ;IACnB,sFAAsF;IAC7E,SAAS,GAAoB,MAAM,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;IAE/C,OAAO,GAAG,MAAM,CAAS,OAAO;gFAAC,CAAC;IAClC,QAAQ,GAAG,MAAM,CAAe,IAAI;iFAAC,CAAC;IACtC,QAAQ,GAAG,MAAM,CAAC,CAAC;iFAAC,CAAC;IACrB,gBAAgB,GAAG,MAAM,CAAC,CAAC;yFAAC,CAAC;IAC9C,kEAAkE;IACjD,OAAO,GAAG,IAAI,GAAG,EAG/B,CAAC;IACI,QAAQ,GAAkB,IAAI,CAAC;IAEvC,wDAAwD;IAC/C,MAAM,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C,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/C,IAAI,CAAC,QAAQ,GAAG,QAAQ,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;QACtC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC;QAClD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,eAAe,IAAI,CAAC,CAAC,CAAC;QACtD,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,gBAAgB,IAAI,CAAC,CAAC,CAAC;QAC/D,OAAO,IAAI,CAAC;IACd,CAAC;uGApFU,QAAQ;wGAAR,QAAQ;;2FAAR,QAAQ;kBADpB,OAAO","sourcesContent":["/**\n * How much of the screen belongs to the system: the notch, the status bar, the home indicator,\n * a rounded corner, and on Android the display cutout and the navigation bar.\n *\n * Unlike everything else here, this has no React Native module behind it. Insets are a property\n * of a *view*, not of the device, and the only thing that can report them is a native view inside\n * the window - `<safe-area-provider>` in `@ng-native/components`, which pushes what it\n * measures in here. That is also why the values start at zero: nothing is known until a view has\n * been laid out, which is one frame after the app mounts.\n *\n * Most layouts should not read this at all. A `<safe-area-view>` applies the insets natively,\n * without a round trip through JavaScript, and a screen in a native stack has its header do it.\n * This is for the cases neither covers: a floating button that must clear the home indicator, a\n * scroll view whose content inset is computed, a sheet drawing its own chrome.\n */\nimport { Service, computed, signal, type Signal } from '@angular/core';\n\nexport interface Insets {\n readonly top: number;\n readonly right: number;\n readonly bottom: number;\n readonly left: number;\n}\n\nexport interface Frame {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\nconst NOTHING: Insets = { top: 0, right: 0, bottom: 0, left: 0 };\n\n@Service()\nexport class SafeArea {\n /** Whether the service is here: on every OS, where it answers what the OS reports. */\n readonly available: Signal<boolean> = signal(true).asReadonly();\n\n private readonly current = signal<Insets>(NOTHING);\n private readonly measured = signal<Frame | null>(null);\n private readonly controls = signal(0);\n private readonly trailingControls = signal(0);\n /** What each provider still up last reported, the latest last. */\n private readonly reports = new Map<\n object,\n { insets: Insets; frame: Frame; titlebarLeading: number; titlebarTrailing: number }\n >();\n private reporter: object | null = null;\n\n /** What the system occupies on each edge, in points. */\n readonly insets: Signal<Insets> = this.current.asReadonly();\n\n /**\n * The provider's own frame: the area it was handed to lay out in.\n *\n * On Android 15 that includes the system bars, because the app draws behind them - which is why\n * `Screen.window` reads this rather than `Dimensions`. Null until the provider has laid out,\n * one frame after the app mounts, and again once every provider that reported is destroyed.\n */\n readonly frame: Signal<Frame | null> = this.measured.asReadonly();\n\n /**\n * On macOS, how far the window's close, minimise and zoom buttons reach into the reporting\n * pane from its leading edge: what `--safe-area-inset-titlebar-leading` holds. Their width in a\n * window with no sidebar and in the sidebar pane under them; zero in the content pane beside a\n * sidebar, which they do not reach. On Linux, the reach of the window controls on the leading\n * side, in a window whose content runs under its header bar; zero on every other OS. One value\n * for the app: the latest report's, not one per pane.\n */\n readonly titlebarLeading: Signal<number> = this.controls.asReadonly();\n\n /**\n * How far a desktop window's title bar controls reach into the reporting pane from its trailing\n * edge: what `--safe-area-inset-titlebar-trailing` holds. Zero on macOS, whose controls are on\n * the leading side, on Linux in a window whose content stays below its header bar (the default\n * title bar), and on every OS with no title bar. One value for the app, as `titlebarLeading` is.\n */\n readonly titlebarTrailing: Signal<number> = this.trailingControls.asReadonly();\n\n /** Whether anything has reported yet, for a layout that would rather wait than jump. */\n readonly known = computed(() => this.measured() !== null);\n\n /**\n * Called by `<safe-area-provider>` when native reports. Not for apps: an inset written from\n * anywhere else is a number that stops matching the screen the moment the device rotates.\n */\n report(\n insets: Insets,\n frame: Frame,\n from?: object,\n titlebarLeading = 0,\n titlebarTrailing = 0,\n ): void {\n this.current.set(insets);\n this.measured.set(frame);\n this.controls.set(titlebarLeading);\n this.trailingControls.set(titlebarTrailing);\n this.reporter = from ?? null;\n if (!from) return;\n this.reports.delete(from);\n this.reports.set(from, { insets, frame, titlebarLeading, titlebarTrailing });\n }\n\n /**\n * Called by `<safe-area-provider>` as it goes: forgets its report. When that report was the\n * latest, what a provider still up last reported takes its place, or nothing when none is.\n * True when the values changed.\n */\n withdraw(from: object): boolean {\n this.reports.delete(from);\n if (this.reporter !== from) return false;\n const [previous] = [...this.reports].slice(-1);\n this.reporter = previous?.[0] ?? null;\n this.current.set(previous?.[1].insets ?? NOTHING);\n this.measured.set(previous?.[1].frame ?? null);\n this.controls.set(previous?.[1].titlebarLeading ?? 0);\n this.trailingControls.set(previous?.[1].titlebarTrailing ?? 0);\n return true;\n }\n}\n"]}
package/dist/sharing.js CHANGED
@@ -6,15 +6,16 @@
6
6
  * means they changed their mind, and only the first is worth a confirmation or an analytics event.
7
7
  */
8
8
  import { InjectionToken, Service, inject, signal } from '@angular/core';
9
+ import { isDesktopOs } from "./os.js";
9
10
  import { reactNative } from "./react-native.js";
10
11
  import * as i0 from "@angular/core";
11
12
  export function sharingSource() {
12
13
  const native = reactNative();
13
14
  if (!native)
14
15
  return null;
15
- // React Native's Share has no macOS implementation: the desktop host's NgNativeSharing is the
16
- // share picker there, and without it sharing is absent.
17
- if (native.Platform.OS === 'macos') {
16
+ // React Native's Share has no desktop implementation: the desktop host's NgNativeSharing is the
17
+ // share picker on macOS and Linux, and without it sharing is absent.
18
+ if (isDesktopOs(native.Platform.OS)) {
18
19
  return native.TurboModuleRegistry?.get('NgNativeSharing') ?? null;
19
20
  }
20
21
  const android = native.Platform.OS === 'android';
@@ -1 +1 @@
1
- {"version":3,"file":"sharing.js","sourceRoot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OAAO,EAAE,aAAa,EAAE,CAC3B,CAAC;IAEe,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAEjD,mFAAmF;IAC1E,SAAS,GAAoB,MAAM,CAAC,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC;IAEhF;;;;;OAKG;IACH,KAAK,CAAC,KAAK,CAAC,OAAqB;QAC/B,IAAI,CAAC,IAAI,CAAC,MAAM;YAAE,OAAO,KAAK,CAAC;QAC/B,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG;YAAE,OAAO,KAAK,CAAC;QAEnD,IAAI,CAAC;YACH,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACpD,OAAO,MAAM,KAAK,cAAc,CAAC;QACnC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;uGA5BU,OAAO;wGAAP,OAAO;;2FAAP,OAAO;kBADnB,OAAO","sourcesContent":["/**\n * The system share sheet.\n *\n * `Share.share` resolves either way - dismissing the sheet is not an error - and the distinction\n * it draws is one a caller usually wants: `shared` means an app took the content, `dismissed`\n * means they changed their mind, and only the first is worth a confirmation or an analytics event.\n */\n\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { reactNative } from './react-native.ts';\n\nexport interface ShareRequest {\n /** What is being shared. At least one of these; iOS prefers `url` when both are present. */\n readonly message?: string;\n readonly url?: string;\n /** Android's dialog title, and iOS's mail subject. */\n readonly title?: string;\n}\n\nexport interface NativeSharing {\n share(request: ShareRequest): Promise<{ action: string; activityType?: string | null }>;\n}\n\nexport function sharingSource(): NativeSharing | null {\n const native = reactNative();\n if (!native) return null;\n // React Native's Share has no macOS implementation: the desktop host's NgNativeSharing is the\n // share picker there, and without it sharing is absent.\n if (native.Platform.OS === 'macos') {\n return (native.TurboModuleRegistry?.get('NgNativeSharing') as NativeSharing | null) ?? null;\n }\n const android = native.Platform.OS === 'android';\n return { share: (request) => native.Share.share(android ? forAndroid(request) : request) };\n}\n\n/**\n * `Share.share` on Android reads `title` and `message` and nothing else - `url` is not a field\n * React Native's own Android module looks at, so a request built the iOS way, `{ url, title }`\n * with no `message`, opens a sheet with a title and an empty body and nothing to actually share.\n * React Native's own docs say as much: Android's `message` \"will often include a URL\". Folding it\n * in here is what makes `share({ url, title })` behave the same on both platforms, as the type\n * says it should.\n */\nfunction forAndroid(request: ShareRequest): ShareRequest {\n if (!request.url) return request;\n const message = request.message ? `${request.message}\\n${request.url}` : request.url;\n return { title: request.title, message };\n}\n\n@Service()\nexport class Sharing {\n /** Overridden in a test to answer the sheet without one opening. */\n static readonly SOURCE = new InjectionToken<NativeSharing | null>(\n 'angular-native.sharingSource',\n { factory: sharingSource },\n );\n\n private readonly native = inject(Sharing.SOURCE);\n\n /** Whether React Native's module is here. Where it is not, every call is inert. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /**\n * Open the share sheet. Resolves to whether anything took the content.\n *\n * Failures resolve to false rather than rejecting: the sheet failing to open and the user\n * closing it are the same outcome at the call site, and neither is exceptional.\n */\n async share(request: ShareRequest): Promise<boolean> {\n if (!this.native) return false;\n if (!request.message && !request.url) return false;\n\n try {\n const { action } = await this.native.share(request);\n return action === 'sharedAction';\n } catch {\n return false;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"sharing.js","sourceRoot":"","sources":["../src/sharing.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAe,MAAM,eAAe,CAAC;AACrF,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;;AAchD,MAAM,UAAU,aAAa;IAC3B,MAAM,MAAM,GAAG,WAAW,E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KAAK,CAAC,OAAqB;QAC/B,IAAI,CAAC,IAAI,CAAC,MAAM;YAAE,OAAO,KAAK,CAAC;QAC/B,IAAI,CAAC,OAAO,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG;YAAE,OAAO,KAAK,CAAC;QAEnD,IAAI,CAAC;YACH,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACpD,OAAO,MAAM,KAAK,cAAc,CAAC;QACnC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;uGA5BU,OAAO;wGAAP,OAAO;;2FAAP,OAAO;kBADnB,OAAO","sourcesContent":["/**\n * The system share sheet.\n *\n * `Share.share` resolves either way - dismissing the sheet is not an error - and the distinction\n * it draws is one a caller usually wants: `shared` means an app took the content, `dismissed`\n * means they changed their mind, and only the first is worth a confirmation or an analytics event.\n */\n\nimport { InjectionToken, Service, inject, signal, type Signal } from '@angular/core';\nimport { isDesktopOs } from './os.ts';\nimport { reactNative } from './react-native.ts';\n\nexport interface ShareRequest {\n /** What is being shared. At least one of these; iOS prefers `url` when both are present. */\n readonly message?: string;\n readonly url?: string;\n /** Android's dialog title, and iOS's mail subject. */\n readonly title?: string;\n}\n\nexport interface NativeSharing {\n share(request: ShareRequest): Promise<{ action: string; activityType?: string | null }>;\n}\n\nexport function sharingSource(): NativeSharing | null {\n const native = reactNative();\n if (!native) return null;\n // React Native's Share has no desktop implementation: the desktop host's NgNativeSharing is the\n // share picker on macOS and Linux, and without it sharing is absent.\n if (isDesktopOs(native.Platform.OS)) {\n return (native.TurboModuleRegistry?.get('NgNativeSharing') as NativeSharing | null) ?? null;\n }\n const android = native.Platform.OS === 'android';\n return { share: (request) => native.Share.share(android ? forAndroid(request) : request) };\n}\n\n/**\n * `Share.share` on Android reads `title` and `message` and nothing else - `url` is not a field\n * React Native's own Android module looks at, so a request built the iOS way, `{ url, title }`\n * with no `message`, opens a sheet with a title and an empty body and nothing to actually share.\n * React Native's own docs say as much: Android's `message` \"will often include a URL\". Folding it\n * in here is what makes `share({ url, title })` behave the same on both platforms, as the type\n * says it should.\n */\nfunction forAndroid(request: ShareRequest): ShareRequest {\n if (!request.url) return request;\n const message = request.message ? `${request.message}\\n${request.url}` : request.url;\n return { title: request.title, message };\n}\n\n@Service()\nexport class Sharing {\n /** Overridden in a test to answer the sheet without one opening. */\n static readonly SOURCE = new InjectionToken<NativeSharing | null>(\n 'angular-native.sharingSource',\n { factory: sharingSource },\n );\n\n private readonly native = inject(Sharing.SOURCE);\n\n /** Whether React Native's module is here. Where it is not, every call is inert. */\n readonly available: Signal<boolean> = signal(this.native !== null).asReadonly();\n\n /**\n * Open the share sheet. Resolves to whether anything took the content.\n *\n * Failures resolve to false rather than rejecting: the sheet failing to open and the user\n * closing it are the same outcome at the call site, and neither is exceptional.\n */\n async share(request: ShareRequest): Promise<boolean> {\n if (!this.native) return false;\n if (!request.message && !request.url) return false;\n\n try {\n const { action } = await this.native.share(request);\n return action === 'sharedAction';\n } catch {\n return false;\n }\n }\n}\n"]}
@@ -27,8 +27,8 @@ export interface ParsedShortcut {
27
27
  readonly shift: boolean;
28
28
  }
29
29
  /**
30
- * A shortcut read for `os`. Throws on one that names no key or a modifier it does not know, since
31
- * that is a mistake in the app, not something a user can press.
30
+ * A shortcut read for `os`. Throws on one that names no key, a modifier or a key it does not know,
31
+ * since that is a mistake in the app, not something a user can press.
32
32
  */
33
33
  export declare function parseShortcut(shortcut: string, os: ShortcutOs): ParsedShortcut;
34
34
  /** Whether pressing `chord` on `os` is `shortcut`: the same key, and exactly its modifiers. */
package/dist/shortcut.js CHANGED
@@ -5,11 +5,36 @@
5
5
  * host, iOS hardware keyboards and Android's key-shortcut dispatch all follow the same rules.
6
6
  */
7
7
  const MODIFIERS = new Set(['mod', 'cmd', 'meta', 'ctrl', 'alt', 'option', 'shift']);
8
+ /**
9
+ * The keys named with a word, as `KeyboardEvent.key` spells them. The menu and key tables of the
10
+ * hosts (AppKit, GTK, UIKit and Android) are what these come from; `Space` is written as a word
11
+ * and read as the `' '` the web reports.
12
+ */
13
+ const NAMED_KEYS = new Set([
14
+ 'ArrowLeft',
15
+ 'ArrowRight',
16
+ 'ArrowUp',
17
+ 'ArrowDown',
18
+ 'Enter',
19
+ 'Escape',
20
+ 'Backspace',
21
+ 'Delete',
22
+ 'Tab',
23
+ 'Home',
24
+ 'End',
25
+ 'PageUp',
26
+ 'PageDown',
27
+ 'Insert',
28
+ 'Pause',
29
+ 'ScrollLock',
30
+ 'ContextMenu',
31
+ ...Array.from({ length: 20 }, (_, n) => `F${n + 1}`),
32
+ ]);
8
33
  /** Whether `os` is one of Apple's, where `mod` is Cmd. */
9
34
  const apple = (os) => os === 'ios' || os === 'macos';
10
35
  /**
11
- * A shortcut read for `os`. Throws on one that names no key or a modifier it does not know, since
12
- * that is a mistake in the app, not something a user can press.
36
+ * A shortcut read for `os`. Throws on one that names no key, a modifier or a key it does not know,
37
+ * since that is a mistake in the app, not something a user can press.
13
38
  */
14
39
  export function parseShortcut(shortcut, os) {
15
40
  const { key, held } = split(shortcut);
@@ -38,6 +63,16 @@ function split(shortcut) {
38
63
  if (!key || MODIFIERS.has(key.toLowerCase())) {
39
64
  throw new Error(`[angular-native] '${shortcut}' names no key to press.`);
40
65
  }
66
+ if (key === 'Space')
67
+ return { key: ' ', held };
68
+ // A key longer than one character is a name from the table, spelt exactly: `enter` or `up`
69
+ // would register and never fire. Counted as the user sees it, so `é` is one.
70
+ if ([...key].length > 1 && !NAMED_KEYS.has(key)) {
71
+ const near = [...NAMED_KEYS].find((name) => name.toLowerCase() === key.toLowerCase());
72
+ throw new Error(`[angular-native] '${shortcut}' has no key '${key}'.` +
73
+ (near ? ` Did you mean '${near}'?` : '') +
74
+ ` Named keys are spelt as KeyboardEvent.key does, such as ArrowUp, Enter, Escape, PageDown and F5.`);
75
+ }
41
76
  return { key, held };
42
77
  }
43
78
  /** Whether pressing `chord` on `os` is `shortcut`: the same key, and exactly its modifiers. */
@@ -1 +1 @@
1
- {"version":3,"file":"shortcut.js","sourceRoot":"","sources":["../src/shortcut.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA4BH,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC;AAEpF,0DAA0D;AAC1D,MAAM,KAAK,GAAG,CAAC,EAAc,EAAW,EAAE,CAAC,EAAE,KAAK,KAAK,IAAI,EAAE,KAAK,OAAO,CAAC;AAE1E;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,QAAgB,EAAE,EAAc;IAC5D,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;IACtC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC5B,OAAO;QACL,GAAG,EAAE,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,GAAG;QAC/C,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC;QAC/D,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC7C,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC;QAC1C,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC;KACzB,CAAC;AACJ,CAAC;AAED,4DAA4D;AAC5D,SAAS,KAAK,CAAC,QA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;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,SAA6B,EAAE,EAAc;IAC9E,IAAI,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC;QACd,OAAO;YACL,GAAG,EAAE,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG;YACrC,IAAI,EAAE,IAAI;YACV,IAAI,EAAE,KAAK;YACX,GAAG,EAAE,KAAK;YACV,KAAK,EAAE,KAAK;SACb,CAAC;IACJ,CAAC;IACD,MAAM,GAAG,GAAG,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,YAAY,CAAC;IAC9D,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AACpE,CAAC","sourcesContent":["/**\n * Keyboard shortcuts, as `<menu-item shortcut>` and `[shortcut]` write them: `mod+s`,\n * `mod+shift+k`, `mod+,`. `mod` is Cmd on Apple's OSes and Ctrl everywhere else, so one string\n * serves every OS. The matching and the text-input rule are here, in TypeScript, so the desktop\n * host, iOS hardware keyboards and Android's key-shortcut dispatch all follow the same rules.\n */\n\nimport type { OsName } from './os.ts';\n\n/** The OSes a shortcut is read on, as the `OS` token names them. */\nexport type ShortcutOs = OsName;\n\n/** A key pressed with its modifiers, as a key event reports it. */\nexport interface KeyChord {\n /** The key, as `KeyboardEvent.key` names it: `s`, `,`, `ArrowLeft`, `[`. */\n readonly key: string;\n /** Cmd on a Mac or an iPad keyboard, the Windows or Meta key elsewhere. */\n readonly meta?: boolean;\n readonly ctrl?: boolean;\n /** Option on a Mac. */\n readonly alt?: boolean;\n readonly shift?: boolean;\n}\n\n/** A shortcut read for one OS: the key, lower case, and exactly the modifiers it needs. */\nexport interface ParsedShortcut {\n readonly key: string;\n readonly meta: boolean;\n readonly ctrl: boolean;\n readonly alt: boolean;\n readonly shift: boolean;\n}\n\nconst MODIFIERS = new Set(['mod', 'cmd', 'meta', 'ctrl', 'alt', 'option', 'shift']);\n\n/** Whether `os` is one of Apple's, where `mod` is Cmd. */\nconst apple = (os: ShortcutOs): boolean => os === 'ios' || os === 'macos';\n\n/**\n * A shortcut read for `os`. Throws on one that names no key or a modifier it does not know, since\n * that is a mistake in the app, not something a user can press.\n */\nexport function parseShortcut(shortcut: string, os: ShortcutOs): ParsedShortcut {\n const { key, held } = split(shortcut);\n const mod = held.has('mod');\n return {\n key: key.length === 1 ? key.toLowerCase() : key,\n meta: held.has('cmd') || held.has('meta') || (mod && apple(os)),\n ctrl: held.has('ctrl') || (mod && !apple(os)),\n alt: held.has('alt') || held.has('option'),\n shift: held.has('shift'),\n };\n}\n\n/** A shortcut's key and the modifiers it names, checked. */\nfunction split(shortcut: string): { key: string; held: Set<string> } {\n // A trailing `+` is the plus key itself: `mod++`.\n const parts = shortcut.endsWith('++')\n ? [...shortcut.slice(0, -2).split('+'), '+']\n : shortcut.split('+');\n const key = parts.pop() ?? '';\n const held = new Set(parts.map((part) => part.trim().toLowerCase()));\n for (const modifier of held) {\n if (!MODIFIERS.has(modifier)) {\n throw new Error(`[angular-native] '${shortcut}' has no modifier '${modifier}'.`);\n }\n }\n if (!key || MODIFIERS.has(key.toLowerCase())) {\n throw new Error(`[angular-native] '${shortcut}' names no key to press.`);\n }\n return { key, held };\n}\n\n/** Whether pressing `chord` on `os` is `shortcut`: the same key, and exactly its modifiers. */\nexport function matchesShortcut(shortcut: string, chord: KeyChord, os: ShortcutOs): boolean {\n const wanted = parseShortcut(shortcut, os);\n const key = chord.key.length === 1 ? chord.key.toLowerCase() : chord.key;\n return (\n key === wanted.key &&\n Boolean(chord.meta) === wanted.meta &&\n Boolean(chord.ctrl) === wanted.ctrl &&\n Boolean(chord.alt) === wanted.alt &&\n Boolean(chord.shift) === wanted.shift\n );\n}\n\n/** The editing keys a focused text input owns: undo, cut, copy, paste and select all. */\nconst EDITING = ['mod+z', 'mod+x', 'mod+c', 'mod+v', 'mod+a'];\n\n/** Whether `shortcut` is one of the editing keys a focused text input owns on `os`. */\nexport function isEditingShortcut(shortcut: string, os: ShortcutOs): boolean {\n const parsed = parseShortcut(shortcut, os);\n return EDITING.some((editing) => {\n const own = parseShortcut(editing, os);\n return (Object.keys(own) as (keyof ParsedShortcut)[]).every((k) => own[k] === parsed[k]);\n });\n}\n\n/**\n * Whether an app's `shortcut` fires for `chord`. It fires when the chord matches, except that the\n * editing keys (mod+z, x, c, v and a) go to a focused text input, so an app's shortcut on one of\n * them fires only while no text input has focus. Every other shortcut fires wherever focus is, as\n * a menu's key equivalents do.\n */\nexport function shortcutFires(\n shortcut: string,\n chord: KeyChord,\n os: ShortcutOs,\n textInputFocused: boolean,\n): boolean {\n if (!matchesShortcut(shortcut, chord, os)) return false;\n return !(textInputFocused && isEditingShortcut(shortcut, os));\n}\n\n/**\n * The back and forward keys on `os`: a shortcut role rather than a `mod` chord, since each OS has\n * its own. Cmd-[ and Cmd-] on macOS and iPadOS keyboards (Cmd-Left stays with text editing), and\n * Alt-Left and Alt-Right elsewhere, as Windows, Linux and Android browsers have them.\n */\nexport function navigationShortcut(direction: 'back' | 'forward', os: ShortcutOs): ParsedShortcut {\n if (apple(os)) {\n return {\n key: direction === 'back' ? '[' : ']',\n meta: true,\n ctrl: false,\n alt: false,\n shift: false,\n };\n }\n const key = direction === 'back' ? 'ArrowLeft' : 'ArrowRight';\n return { key, meta: false, ctrl: false, alt: true, shift: false };\n}\n"]}
1
+ {"version":3,"file":"shortcut.js","sourceRoot":"","sources":["../src/shortcut.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA4BH,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC;AAEpF;;;;GAIG;AACH,MAAM,UAAU,GAAwB,IAAI,GAAG,CAAC;I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["/**\n * Keyboard shortcuts, as `<menu-item shortcut>` and `[shortcut]` write them: `mod+s`,\n * `mod+shift+k`, `mod+,`. `mod` is Cmd on Apple's OSes and Ctrl everywhere else, so one string\n * serves every OS. The matching and the text-input rule are here, in TypeScript, so the desktop\n * host, iOS hardware keyboards and Android's key-shortcut dispatch all follow the same rules.\n */\n\nimport type { OsName } from './os.ts';\n\n/** The OSes a shortcut is read on, as the `OS` token names them. */\nexport type ShortcutOs = OsName;\n\n/** A key pressed with its modifiers, as a key event reports it. */\nexport interface KeyChord {\n /** The key, as `KeyboardEvent.key` names it: `s`, `,`, `ArrowLeft`, `[`. */\n readonly key: string;\n /** Cmd on a Mac or an iPad keyboard, the Windows or Meta key elsewhere. */\n readonly meta?: boolean;\n readonly ctrl?: boolean;\n /** Option on a Mac. */\n readonly alt?: boolean;\n readonly shift?: boolean;\n}\n\n/** A shortcut read for one OS: the key, lower case, and exactly the modifiers it needs. */\nexport interface ParsedShortcut {\n readonly key: string;\n readonly meta: boolean;\n readonly ctrl: boolean;\n readonly alt: boolean;\n readonly shift: boolean;\n}\n\nconst MODIFIERS = new Set(['mod', 'cmd', 'meta', 'ctrl', 'alt', 'option', 'shift']);\n\n/**\n * The keys named with a word, as `KeyboardEvent.key` spells them. The menu and key tables of the\n * hosts (AppKit, GTK, UIKit and Android) are what these come from; `Space` is written as a word\n * and read as the `' '` the web reports.\n */\nconst NAMED_KEYS: ReadonlySet<string> = new Set([\n 'ArrowLeft',\n 'ArrowRight',\n 'ArrowUp',\n 'ArrowDown',\n 'Enter',\n 'Escape',\n 'Backspace',\n 'Delete',\n 'Tab',\n 'Home',\n 'End',\n 'PageUp',\n 'PageDown',\n 'Insert',\n 'Pause',\n 'ScrollLock',\n 'ContextMenu',\n ...Array.from({ length: 20 }, (_, n) => `F${n + 1}`),\n]);\n\n/** Whether `os` is one of Apple's, where `mod` is Cmd. */\nconst apple = (os: ShortcutOs): boolean => os === 'ios' || os === 'macos';\n\n/**\n * A shortcut read for `os`. Throws on one that names no key, a modifier or a key it does not know,\n * since that is a mistake in the app, not something a user can press.\n */\nexport function parseShortcut(shortcut: string, os: ShortcutOs): ParsedShortcut {\n const { key, held } = split(shortcut);\n const mod = held.has('mod');\n return {\n key: key.length === 1 ? key.toLowerCase() : key,\n meta: held.has('cmd') || held.has('meta') || (mod && apple(os)),\n ctrl: held.has('ctrl') || (mod && !apple(os)),\n alt: held.has('alt') || held.has('option'),\n shift: held.has('shift'),\n };\n}\n\n/** A shortcut's key and the modifiers it names, checked. */\nfunction split(shortcut: string): { key: string; held: Set<string> } {\n // A trailing `+` is the plus key itself: `mod++`.\n const parts = shortcut.endsWith('++')\n ? [...shortcut.slice(0, -2).split('+'), '+']\n : shortcut.split('+');\n const key = parts.pop() ?? '';\n const held = new Set(parts.map((part) => part.trim().toLowerCase()));\n for (const modifier of held) {\n if (!MODIFIERS.has(modifier)) {\n throw new Error(`[angular-native] '${shortcut}' has no modifier '${modifier}'.`);\n }\n }\n if (!key || MODIFIERS.has(key.toLowerCase())) {\n throw new Error(`[angular-native] '${shortcut}' names no key to press.`);\n }\n if (key === 'Space') return { key: ' ', held };\n // A key longer than one character is a name from the table, spelt exactly: `enter` or `up`\n // would register and never fire. Counted as the user sees it, so `é` is one.\n if ([...key].length > 1 && !NAMED_KEYS.has(key)) {\n const near = [...NAMED_KEYS].find((name) => name.toLowerCase() === key.toLowerCase());\n throw new Error(\n `[angular-native] '${shortcut}' has no key '${key}'.` +\n (near ? ` Did you mean '${near}'?` : '') +\n ` Named keys are spelt as KeyboardEvent.key does, such as ArrowUp, Enter, Escape, PageDown and F5.`,\n );\n }\n return { key, held };\n}\n\n/** Whether pressing `chord` on `os` is `shortcut`: the same key, and exactly its modifiers. */\nexport function matchesShortcut(shortcut: string, chord: KeyChord, os: ShortcutOs): boolean {\n const wanted = parseShortcut(shortcut, os);\n const key = chord.key.length === 1 ? chord.key.toLowerCase() : chord.key;\n return (\n key === wanted.key &&\n Boolean(chord.meta) === wanted.meta &&\n Boolean(chord.ctrl) === wanted.ctrl &&\n Boolean(chord.alt) === wanted.alt &&\n Boolean(chord.shift) === wanted.shift\n );\n}\n\n/** The editing keys a focused text input owns: undo, cut, copy, paste and select all. */\nconst EDITING = ['mod+z', 'mod+x', 'mod+c', 'mod+v', 'mod+a'];\n\n/** Whether `shortcut` is one of the editing keys a focused text input owns on `os`. */\nexport function isEditingShortcut(shortcut: string, os: ShortcutOs): boolean {\n const parsed = parseShortcut(shortcut, os);\n return EDITING.some((editing) => {\n const own = parseShortcut(editing, os);\n return (Object.keys(own) as (keyof ParsedShortcut)[]).every((k) => own[k] === parsed[k]);\n });\n}\n\n/**\n * Whether an app's `shortcut` fires for `chord`. It fires when the chord matches, except that the\n * editing keys (mod+z, x, c, v and a) go to a focused text input, so an app's shortcut on one of\n * them fires only while no text input has focus. Every other shortcut fires wherever focus is, as\n * a menu's key equivalents do.\n */\nexport function shortcutFires(\n shortcut: string,\n chord: KeyChord,\n os: ShortcutOs,\n textInputFocused: boolean,\n): boolean {\n if (!matchesShortcut(shortcut, chord, os)) return false;\n return !(textInputFocused && isEditingShortcut(shortcut, os));\n}\n\n/**\n * The back and forward keys on `os`: a shortcut role rather than a `mod` chord, since each OS has\n * its own. Cmd-[ and Cmd-] on macOS and iPadOS keyboards (Cmd-Left stays with text editing), and\n * Alt-Left and Alt-Right elsewhere, as Windows, Linux and Android browsers have them.\n */\nexport function navigationShortcut(direction: 'back' | 'forward', os: ShortcutOs): ParsedShortcut {\n if (apple(os)) {\n return {\n key: direction === 'back' ? '[' : ']',\n meta: true,\n ctrl: false,\n alt: false,\n shift: false,\n };\n }\n const key = direction === 'back' ? 'ArrowLeft' : 'ArrowRight';\n return { key, meta: false, ctrl: false, alt: true, shift: false };\n}\n"]}
@@ -64,6 +64,14 @@ const REFUSED_PROGRAMS = new Set([
64
64
  'pwsh',
65
65
  'nice',
66
66
  'nohup',
67
+ // Linux's: escalation (`pkexec`), a shell of its own (`busybox`), and leaving a Flatpak sandbox,
68
+ // the session or the mount namespace (`flatpak-spawn --host`, `systemd-run`, `nsenter`, `chroot`).
69
+ 'pkexec',
70
+ 'busybox',
71
+ 'flatpak-spawn',
72
+ 'systemd-run',
73
+ 'nsenter',
74
+ 'chroot',
67
75
  ]);
68
76
  /** Windows batch files, which run through `cmd.exe` and so re-parse their arguments. */
69
77
  const REFUSED_EXTENSIONS = ['.bat', '.cmd'];
@@ -1 +1 @@
1
- {"version":3,"file":"spawn-rules.js","sourceRoot":"","sources":["../src/spawn-rules.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAgCH;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAsB;IAC5C,UAAU;IACV,MAAM;IACN,WAAW;IACX,OAAO;IACP,mBAAmB;IACnB,gBAAgB;CACjB,CAAC;AAEF;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAC/B,IAAI;IACJ,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,IAAI;IACJ,KAAK;IACL,OAAO;IACP,MAAM;IACN,MAAM;IACN,IAAI;IACJ,WAAW;IACX,KAAK;IACL,YAAY;IACZ,MAAM;IACN,MAAM;IACN,OAAO;CACR,CAAC,CAAC;AAEH,wFAAwF;AACxF,MAAM,kBAAkB,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAE5C,MAAM,WAAW,GAAG,mDAAmD,CAAC;AAExE,+CAA+C;AAC/C,MAAM,OAAO,cAAe,SAAQ,KAAK;IACrB,IAAI,GAAG,gBAAgB,CAAC;CAC3C;AAED,oFAAoF;AACpF,SAAS,QAAQ,CAAC,OAAe;IAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACjD,OAAO,IAAI,CAAC,WAAW,EAAE,CA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,CAAC;IAC1D,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAaD;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,MAAqB;IACnE,IAAI,cAAc,CAAC,OAAO,CAAC;QAAE,OAAO,IAAI,CAAC;IACzC,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;QACxC,CAAC,CAAC,CAAC,OAAO,CAAC;QACX,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,OAAO,EAAE,CAAC,CAAC;IAClD,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC;YAAE,SAAS;QAC9C,OAAO,MAAM,CAAC,MAAM,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACvD,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,2FAA2F;AAC3F,MAAM,UAAU,iBAAiB,CAC/B,GAAiD,EACjD,OAA0B;IAE1B,MAAM,QAAQ,GAA2B,EAAE,CAAC;IAC5C,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC/D,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,QAAQ,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;IACjF,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["/**\n * The rules a desktop app's declared spawn capabilities follow: which programs it may run, with\n * which arguments. Plain TypeScript with no imports, so the config plugin can check the declaration\n * at build time and `Processes` can refuse an undeclared call with a clear error before the\n * desktop host checks it again natively.\n *\n * An entry names a program and the arguments it may take:\n *\n * { program: '/usr/bin/git', args: ['clone', '{url:https://\\\\S+}', '{dir:[\\\\w.-]+}'] }\n *\n * Each argument is a literal, matched exactly, or a `{name:regex}` placeholder. A placeholder\n * followed by `...` matches zero or more arguments, each by the same rules.\n *\n * - A placeholder's pattern is anchored: it matches the whole argument, so `{branch:[a-z]+}`\n * never accepts `--upload-pack=...`.\n * - A placeholder never accepts an argument starting with `-` unless each alternative of its\n * pattern starts with one, so an option cannot be injected where a value was declared.\n * - No argument may hold a NUL character, which a C string would cut short.\n * - Shells, `env` and other programs that run their arguments as a command are refused as\n * programs, and so are Windows `.bat` and `.cmd` files, which `cmd.exe` re-parses (the BatBadBut\n * class of bug). `spawn` never goes through a shell.\n * - A program is an absolute path, or a bare name resolved once at startup on a fixed search path\n * (`SEARCH_PATH`), never the inherited `PATH`, and pinned there.\n *\n * The boundary guards against bugs and injected content, not against a hostile app.\n */\n\n/** A spawn capability as `app.json` declares it. */\nexport interface SpawnCapability {\n /** An absolute path, or a bare name resolved on `SEARCH_PATH` at startup. */\n readonly program: string;\n /** Literal arguments and `{name:regex}` placeholders, in order. */\n readonly args?: readonly string[];\n}\n\n/** One declared argument, parsed. */\nexport type ArgumentRule =\n | { readonly kind: 'literal'; readonly value: string }\n | {\n readonly kind: 'placeholder';\n readonly name: string;\n readonly pattern: RegExp;\n /** Whether each alternative of the pattern starts with `-`, so the value may be an option. */\n readonly option: boolean;\n /** `{name:regex}...`: zero or more arguments. */\n readonly repeated: boolean;\n };\n\n/** A spawn capability, checked and parsed. */\nexport interface CompiledCapability {\n readonly program: string;\n readonly args: readonly ArgumentRule[];\n}\n\n/** What a call that matched was given for each placeholder: a list for a repeated one. */\nexport type PlaceholderValues = Record<string, string | readonly string[]>;\n\n/**\n * Where a bare program name is looked for, in order: the system's directories, then Homebrew's on\n * Apple silicon and on Intel. A Finder-launched app inherits only launchd's `PATH`, so Homebrew's\n * tools would never resolve on the inherited one.\n */\nexport const SEARCH_PATH: readonly string[] = [\n '/usr/bin',\n '/bin',\n '/usr/sbin',\n '/sbin',\n '/opt/homebrew/bin',\n '/usr/local/bin',\n];\n\n/**\n * Programs refused whatever their path: shells, and programs whose job is to run their own\n * arguments as a command (`env`, `xargs`, `sudo`, `nice`, `nohup`), which would turn an argument\n * pattern into a command line.\n */\nconst REFUSED_PROGRAMS = new Set([\n 'sh',\n 'bash',\n 'zsh',\n 'dash',\n 'ksh',\n 'mksh',\n 'csh',\n 'tcsh',\n 'fish',\n 'nu',\n 'env',\n 'xargs',\n 'sudo',\n 'doas',\n 'su',\n 'osascript',\n 'cmd',\n 'powershell',\n 'pwsh',\n 'nice',\n 'nohup',\n]);\n\n/** Windows batch files, which run through `cmd.exe` and so re-parse their arguments. */\nconst REFUSED_EXTENSIONS = ['.bat', '.cmd'];\n\nconst PLACEHOLDER = /^\\{([A-Za-z_][A-Za-z0-9_]*):([\\s\\S]+)\\}(\\.\\.\\.)?$/;\n\n/** Why a declaration or a call was refused. */\nexport class SpawnRuleError extends Error {\n override readonly name = 'SpawnRuleError';\n}\n\n/** The last segment of a path, either separator, lower-cased and without `.exe`. */\nfunction baseName(program: string): string {\n const last = program.split(/[\\\\/]/).at(-1) ?? '';\n return last.toLowerCase().replace(/\\.exe$/, '');\n}\n\n/** Why `program` cannot be declared, or null when it can. */\nexport function programProblem(program: string): string | null {\n if (typeof program !== 'string' || program.length === 0) return 'a program is required';\n if (program.includes('\\0')) return 'a program cannot hold a NUL character';\n if (program !== program.trim()) return 'a program cannot start or end with white space';\n const lower = program.toLowerCase();\n if (REFUSED_EXTENSIONS.some((extension) => lower.endsWith(extension))) {\n return `${program} is a batch file, which runs through cmd.exe and re-parses its arguments`;\n }\n const name = baseName(program);\n if (REFUSED_PROGRAMS.has(name)) {\n return `${program} runs its arguments as a command, so it cannot be declared`;\n }\n if (program.startsWith('/')) {\n const segments = program.split('/').slice(1);\n if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {\n return `${program} is not a normalized absolute path`;\n }\n return null;\n }\n if (/[\\\\/]/.test(program)) {\n return `${program} is a relative path: give an absolute path or a bare name`;\n }\n if (program === '.' || program === '..') return `${program} is not a program`;\n return null;\n}\n\n/** Parse one declared argument. */\nexport function parseArgument(arg: string): ArgumentRule {\n if (typeof arg !== 'string') throw new SpawnRuleError('an argument must be a string');\n if (arg.includes('\\0')) throw new SpawnRuleError('an argument cannot hold a NUL character');\n const placeholder = PLACEHOLDER.exec(arg);\n if (!placeholder) return { kind: 'literal', value: arg };\n const [, name, source, dots] = placeholder as unknown as [string, string, string, string?];\n if (hasLookbehindOrNamedGroup(source)) {\n throw new SpawnRuleError(\n `{${name}} has a (?< named group or lookbehind, which the desktop's native rules cannot compile`,\n );\n }\n let pattern: RegExp;\n try {\n // On its own first: a pattern that compiles alone has balanced groups, so one such as\n // `a)|(.*` cannot close the anchoring group early and escape it.\n new RegExp(source);\n // Anchored as a whole, so an alternation cannot escape it: `{x:a|b}` is `^(?:a|b)$`.\n pattern = new RegExp(`^(?:${source})$`);\n } catch (error) {\n throw new SpawnRuleError(`{${name}} has a pattern that does not compile: ${String(error)}`);\n }\n const option = alternatives(source).every((one) => /^\\^?\\\\?-/.test(one));\n return { kind: 'placeholder', name, pattern, option, repeated: dots !== undefined };\n}\n\n/**\n * Whether a pattern opens a `(?<` group (a named group or a lookbehind) outside an escape or a\n * class. JavaScript compiles one, but the native rules' ECMAScript `std::regex` does not, and a\n * declaration it cannot compile would be dropped there with no error.\n */\nfunction hasLookbehindOrNamedGroup(source: string): boolean {\n let inClass = false;\n for (let at = 0; at < source.length; at++) {\n const char = source[at];\n if (char === '\\\\') at++;\n else if (inClass) inClass = char !== ']';\n else if (char === '[') inClass = true;\n else if (source.startsWith('(?<', at)) return true;\n }\n return false;\n}\n\n/**\n * A pattern's top-level alternatives: `-v|.*` is `-v` and `.*`. A `|` in a group, in a class or\n * escaped is not one. The pattern has compiled, so its groups and classes are balanced.\n */\nfunction alternatives(source: string): string[] {\n const found: string[] = [];\n let depth = 0;\n let inClass = false;\n let start = 0;\n for (let at = 0; at < source.length; at++) {\n const char = source[at];\n if (char === '\\\\') at++;\n else if (inClass) inClass = char !== ']';\n else if (char === '[') inClass = true;\n else if (char === '(') depth++;\n else if (char === ')') depth--;\n else if (char === '|' && depth === 0) {\n found.push(source.slice(start, at));\n start = at + 1;\n }\n }\n found.push(source.slice(start));\n return found;\n}\n\n/** Check and parse one declared capability. Throws `SpawnRuleError` on a bad declaration. */\nexport function compileCapability(capability: SpawnCapability): CompiledCapability {\n const problem = programProblem(capability?.program);\n if (problem) throw new SpawnRuleError(problem);\n if (capability.args !== undefined && !Array.isArray(capability.args)) {\n throw new SpawnRuleError(`${capability.program}: args must be a list`);\n }\n const args = (capability.args ?? []).map(parseArgument);\n const names = new Set<string>();\n let repeated = 0;\n for (const rule of args) {\n if (rule.kind !== 'placeholder') continue;\n if (names.has(rule.name)) {\n throw new SpawnRuleError(`${capability.program}: {${rule.name}} is declared twice`);\n }\n names.add(rule.name);\n if (rule.repeated) repeated++;\n }\n // Two repeated placeholders could share the arguments between them in more than one way.\n if (repeated > 1) {\n throw new SpawnRuleError(`${capability.program}: at most one placeholder may repeat`);\n }\n return { program: capability.program, args };\n}\n\n/** Whether one argument passes a placeholder. */\nfunction passes(rule: Extract<ArgumentRule, { kind: 'placeholder' }>, arg: string): boolean {\n if (arg.startsWith('-') && !rule.option) return false;\n return rule.pattern.test(arg);\n}\n\n/** Whether one argument passes a rule. */\nfunction fits(rule: ArgumentRule, arg: string): boolean {\n return rule.kind === 'literal' ? rule.value === arg : passes(rule, arg);\n}\n\n/**\n * Whether `args` fit a capability's argument rules, and the values its placeholders took; null\n * when they do not. The rules before a repeated placeholder take the first arguments, those after\n * it the last, and it takes what is left between, each by its own pattern.\n */\nexport function matchArguments(\n rules: readonly ArgumentRule[],\n args: readonly string[],\n): PlaceholderValues | null {\n if (args.some((arg) => typeof arg !== 'string' || arg.includes('\\0'))) return null;\n const at = rules.findIndex((rule) => rule.kind === 'placeholder' && rule.repeated);\n const head = at === -1 ? rules : rules.slice(0, at);\n const tail = at === -1 ? [] : rules.slice(at + 1);\n if (at === -1 ? args.length !== rules.length : args.length < head.length + tail.length) {\n return null;\n }\n const values: Record<string, string | readonly string[]> = {};\n const take = (rule: ArgumentRule, arg: string): boolean => {\n if (!fits(rule, arg)) return false;\n if (rule.kind === 'placeholder') values[rule.name] = arg;\n return true;\n };\n for (let index = 0; index < head.length; index++) {\n if (!take(head[index]!, args[index]!)) return null;\n }\n const tailStart = args.length - tail.length;\n for (let index = 0; index < tail.length; index++) {\n if (!take(tail[index]!, args[tailStart + index]!)) return null;\n }\n if (at !== -1) {\n const rule = rules[at] as Extract<ArgumentRule, { kind: 'placeholder' }>;\n const middle = args.slice(head.length, tailStart);\n if (!middle.every((arg) => passes(rule, arg))) return null;\n values[rule.name] = middle;\n }\n return values;\n}\n\n/** What `matchSpawn` answers for a call a capability allows. */\nexport interface SpawnMatch {\n readonly capability: CompiledCapability;\n /** The program to run: the declared absolute path, or the name as it was pinned. */\n readonly path: string;\n readonly values: PlaceholderValues;\n}\n\n/**\n * The capability that allows running `program` with `args`, or null when none does. `program` is\n * the declared path or name exactly: a bare name is never looked up on any `PATH` here, and only\n * runs where `resolved` pinned it.\n *\n * @param resolved where each declared bare name was pinned at startup, by `resolveProgram`\n */\nexport function matchSpawn(\n capabilities: readonly CompiledCapability[],\n program: string,\n args: readonly string[],\n resolved: Readonly<Record<string, string | null>> = {},\n): SpawnMatch | null {\n for (const capability of capabilities) {\n const pinned = capability.program.startsWith('/')\n ? capability.program\n : (resolved[capability.program] ?? null);\n if (pinned === null) continue;\n if (program !== capability.program && program !== pinned) continue;\n const values = matchArguments(capability.args, args);\n if (values) return { capability, path: pinned, values };\n }\n return null;\n}\n\n/** What `resolveProgram` asks of the file system. */\nexport interface ProgramLookup {\n /** Whether an executable file is at `path`. */\n isExecutable(path: string): boolean;\n /**\n * Whether `path` is a developer tool stub that only runs `xcrun`, with no Command Line Tools\n * installed to run. Such a tool reports absent.\n */\n isStub?(path: string): boolean;\n}\n\n/**\n * Where a declared program runs from, pinned once at startup, or null when it is absent: not\n * found, or an `xcrun` stub without the Command Line Tools. A bare name is looked for on\n * `SEARCH_PATH` alone.\n */\nexport function resolveProgram(program: string, lookup: ProgramLookup): string | null {\n if (programProblem(program)) return null;\n const candidates = program.startsWith('/')\n ? [program]\n : SEARCH_PATH.map((dir) => `${dir}/${program}`);\n for (const candidate of candidates) {\n if (!lookup.isExecutable(candidate)) continue;\n return lookup.isStub?.(candidate) ? null : candidate;\n }\n return null;\n}\n\n/** The environment a spawned program gets: only the variables declared, of those given. */\nexport function filterEnvironment(\n env: Readonly<Record<string, string | undefined>>,\n allowed: readonly string[],\n): Record<string, string> {\n const filtered: Record<string, string> = {};\n for (const name of allowed) {\n const value = Object.hasOwn(env, name) ? env[name] : undefined;\n if (typeof value === 'string' && !value.includes('\\0')) filtered[name] = value;\n }\n return filtered;\n}\n"]}
1
+ {"version":3,"file":"spawn-rules.js","sourceRoot":"","sources":["../src/spawn-rules.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAgCH;;;;GAIG;AACH,MAAM,CAAC,MAAM,WAAW,GAAsB;IAC5C,UAAU;IACV,MAAM;IACN,WAAW;IACX,OAAO;IACP,mBAAmB;IACnB,gBAAgB;CACjB,CAAC;AAEF;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC;IAC/B,IAAI;IACJ,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,IAAI;IACJ,KAAK;IACL,OAAO;IACP,MAAM;IACN,MAAM;IACN,IAAI;IACJ,WAAW;IACX,KAAK;IACL,YAAY;IACZ,MAAM;IACN,MAAM;IACN,OAAO;IACP,iGAAiG;IACjG,mGAAmG;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QAAQ,GAA2B,EAAE,CAAC;IAC5C,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC/D,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,QAAQ,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC;IACjF,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["/**\n * The rules a desktop app's declared spawn capabilities follow: which programs it may run, with\n * which arguments. Plain TypeScript with no imports, so the config plugin can check the declaration\n * at build time and `Processes` can refuse an undeclared call with a clear error before the\n * desktop host checks it again natively.\n *\n * An entry names a program and the arguments it may take:\n *\n * { program: '/usr/bin/git', args: ['clone', '{url:https://\\\\S+}', '{dir:[\\\\w.-]+}'] }\n *\n * Each argument is a literal, matched exactly, or a `{name:regex}` placeholder. A placeholder\n * followed by `...` matches zero or more arguments, each by the same rules.\n *\n * - A placeholder's pattern is anchored: it matches the whole argument, so `{branch:[a-z]+}`\n * never accepts `--upload-pack=...`.\n * - A placeholder never accepts an argument starting with `-` unless each alternative of its\n * pattern starts with one, so an option cannot be injected where a value was declared.\n * - No argument may hold a NUL character, which a C string would cut short.\n * - Shells, `env` and other programs that run their arguments as a command are refused as\n * programs, and so are Windows `.bat` and `.cmd` files, which `cmd.exe` re-parses (the BatBadBut\n * class of bug). `spawn` never goes through a shell.\n * - A program is an absolute path, or a bare name resolved once at startup on a fixed search path\n * (`SEARCH_PATH`), never the inherited `PATH`, and pinned there.\n *\n * The boundary guards against bugs and injected content, not against a hostile app.\n */\n\n/** A spawn capability as `app.json` declares it. */\nexport interface SpawnCapability {\n /** An absolute path, or a bare name resolved on `SEARCH_PATH` at startup. */\n readonly program: string;\n /** Literal arguments and `{name:regex}` placeholders, in order. */\n readonly args?: readonly string[];\n}\n\n/** One declared argument, parsed. */\nexport type ArgumentRule =\n | { readonly kind: 'literal'; readonly value: string }\n | {\n readonly kind: 'placeholder';\n readonly name: string;\n readonly pattern: RegExp;\n /** Whether each alternative of the pattern starts with `-`, so the value may be an option. */\n readonly option: boolean;\n /** `{name:regex}...`: zero or more arguments. */\n readonly repeated: boolean;\n };\n\n/** A spawn capability, checked and parsed. */\nexport interface CompiledCapability {\n readonly program: string;\n readonly args: readonly ArgumentRule[];\n}\n\n/** What a call that matched was given for each placeholder: a list for a repeated one. */\nexport type PlaceholderValues = Record<string, string | readonly string[]>;\n\n/**\n * Where a bare program name is looked for, in order: the system's directories, then Homebrew's on\n * Apple silicon and on Intel. A Finder-launched app inherits only launchd's `PATH`, so Homebrew's\n * tools would never resolve on the inherited one.\n */\nexport const SEARCH_PATH: readonly string[] = [\n '/usr/bin',\n '/bin',\n '/usr/sbin',\n '/sbin',\n '/opt/homebrew/bin',\n '/usr/local/bin',\n];\n\n/**\n * Programs refused whatever their path: shells, and programs whose job is to run their own\n * arguments as a command (`env`, `xargs`, `sudo`, `nice`, `nohup`), which would turn an argument\n * pattern into a command line.\n */\nconst REFUSED_PROGRAMS = new Set([\n 'sh',\n 'bash',\n 'zsh',\n 'dash',\n 'ksh',\n 'mksh',\n 'csh',\n 'tcsh',\n 'fish',\n 'nu',\n 'env',\n 'xargs',\n 'sudo',\n 'doas',\n 'su',\n 'osascript',\n 'cmd',\n 'powershell',\n 'pwsh',\n 'nice',\n 'nohup',\n // Linux's: escalation (`pkexec`), a shell of its own (`busybox`), and leaving a Flatpak sandbox,\n // the session or the mount namespace (`flatpak-spawn --host`, `systemd-run`, `nsenter`, `chroot`).\n 'pkexec',\n 'busybox',\n 'flatpak-spawn',\n 'systemd-run',\n 'nsenter',\n 'chroot',\n]);\n\n/** Windows batch files, which run through `cmd.exe` and so re-parse their arguments. */\nconst REFUSED_EXTENSIONS = ['.bat', '.cmd'];\n\nconst PLACEHOLDER = /^\\{([A-Za-z_][A-Za-z0-9_]*):([\\s\\S]+)\\}(\\.\\.\\.)?$/;\n\n/** Why a declaration or a call was refused. */\nexport class SpawnRuleError extends Error {\n override readonly name = 'SpawnRuleError';\n}\n\n/** The last segment of a path, either separator, lower-cased and without `.exe`. */\nfunction baseName(program: string): string {\n const last = program.split(/[\\\\/]/).at(-1) ?? '';\n return last.toLowerCase().replace(/\\.exe$/, '');\n}\n\n/** Why `program` cannot be declared, or null when it can. */\nexport function programProblem(program: string): string | null {\n if (typeof program !== 'string' || program.length === 0) return 'a program is required';\n if (program.includes('\\0')) return 'a program cannot hold a NUL character';\n if (program !== program.trim()) return 'a program cannot start or end with white space';\n const lower = program.toLowerCase();\n if (REFUSED_EXTENSIONS.some((extension) => lower.endsWith(extension))) {\n return `${program} is a batch file, which runs through cmd.exe and re-parses its arguments`;\n }\n const name = baseName(program);\n if (REFUSED_PROGRAMS.has(name)) {\n return `${program} runs its arguments as a command, so it cannot be declared`;\n }\n if (program.startsWith('/')) {\n const segments = program.split('/').slice(1);\n if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) {\n return `${program} is not a normalized absolute path`;\n }\n return null;\n }\n if (/[\\\\/]/.test(program)) {\n return `${program} is a relative path: give an absolute path or a bare name`;\n }\n if (program === '.' || program === '..') return `${program} is not a program`;\n return null;\n}\n\n/** Parse one declared argument. */\nexport function parseArgument(arg: string): ArgumentRule {\n if (typeof arg !== 'string') throw new SpawnRuleError('an argument must be a string');\n if (arg.includes('\\0')) throw new SpawnRuleError('an argument cannot hold a NUL character');\n const placeholder = PLACEHOLDER.exec(arg);\n if (!placeholder) return { kind: 'literal', value: arg };\n const [, name, source, dots] = placeholder as unknown as [string, string, string, string?];\n if (hasLookbehindOrNamedGroup(source)) {\n throw new SpawnRuleError(\n `{${name}} has a (?< named group or lookbehind, which the desktop's native rules cannot compile`,\n );\n }\n let pattern: RegExp;\n try {\n // On its own first: a pattern that compiles alone has balanced groups, so one such as\n // `a)|(.*` cannot close the anchoring group early and escape it.\n new RegExp(source);\n // Anchored as a whole, so an alternation cannot escape it: `{x:a|b}` is `^(?:a|b)$`.\n pattern = new RegExp(`^(?:${source})$`);\n } catch (error) {\n throw new SpawnRuleError(`{${name}} has a pattern that does not compile: ${String(error)}`);\n }\n const option = alternatives(source).every((one) => /^\\^?\\\\?-/.test(one));\n return { kind: 'placeholder', name, pattern, option, repeated: dots !== undefined };\n}\n\n/**\n * Whether a pattern opens a `(?<` group (a named group or a lookbehind) outside an escape or a\n * class. JavaScript compiles one, but the native rules' ECMAScript `std::regex` does not, and a\n * declaration it cannot compile would be dropped there with no error.\n */\nfunction hasLookbehindOrNamedGroup(source: string): boolean {\n let inClass = false;\n for (let at = 0; at < source.length; at++) {\n const char = source[at];\n if (char === '\\\\') at++;\n else if (inClass) inClass = char !== ']';\n else if (char === '[') inClass = true;\n else if (source.startsWith('(?<', at)) return true;\n }\n return false;\n}\n\n/**\n * A pattern's top-level alternatives: `-v|.*` is `-v` and `.*`. A `|` in a group, in a class or\n * escaped is not one. The pattern has compiled, so its groups and classes are balanced.\n */\nfunction alternatives(source: string): string[] {\n const found: string[] = [];\n let depth = 0;\n let inClass = false;\n let start = 0;\n for (let at = 0; at < source.length; at++) {\n const char = source[at];\n if (char === '\\\\') at++;\n else if (inClass) inClass = char !== ']';\n else if (char === '[') inClass = true;\n else if (char === '(') depth++;\n else if (char === ')') depth--;\n else if (char === '|' && depth === 0) {\n found.push(source.slice(start, at));\n start = at + 1;\n }\n }\n found.push(source.slice(start));\n return found;\n}\n\n/** Check and parse one declared capability. Throws `SpawnRuleError` on a bad declaration. */\nexport function compileCapability(capability: SpawnCapability): CompiledCapability {\n const problem = programProblem(capability?.program);\n if (problem) throw new SpawnRuleError(problem);\n if (capability.args !== undefined && !Array.isArray(capability.args)) {\n throw new SpawnRuleError(`${capability.program}: args must be a list`);\n }\n const args = (capability.args ?? []).map(parseArgument);\n const names = new Set<string>();\n let repeated = 0;\n for (const rule of args) {\n if (rule.kind !== 'placeholder') continue;\n if (names.has(rule.name)) {\n throw new SpawnRuleError(`${capability.program}: {${rule.name}} is declared twice`);\n }\n names.add(rule.name);\n if (rule.repeated) repeated++;\n }\n // Two repeated placeholders could share the arguments between them in more than one way.\n if (repeated > 1) {\n throw new SpawnRuleError(`${capability.program}: at most one placeholder may repeat`);\n }\n return { program: capability.program, args };\n}\n\n/** Whether one argument passes a placeholder. */\nfunction passes(rule: Extract<ArgumentRule, { kind: 'placeholder' }>, arg: string): boolean {\n if (arg.startsWith('-') && !rule.option) return false;\n return rule.pattern.test(arg);\n}\n\n/** Whether one argument passes a rule. */\nfunction fits(rule: ArgumentRule, arg: string): boolean {\n return rule.kind === 'literal' ? rule.value === arg : passes(rule, arg);\n}\n\n/**\n * Whether `args` fit a capability's argument rules, and the values its placeholders took; null\n * when they do not. The rules before a repeated placeholder take the first arguments, those after\n * it the last, and it takes what is left between, each by its own pattern.\n */\nexport function matchArguments(\n rules: readonly ArgumentRule[],\n args: readonly string[],\n): PlaceholderValues | null {\n if (args.some((arg) => typeof arg !== 'string' || arg.includes('\\0'))) return null;\n const at = rules.findIndex((rule) => rule.kind === 'placeholder' && rule.repeated);\n const head = at === -1 ? rules : rules.slice(0, at);\n const tail = at === -1 ? [] : rules.slice(at + 1);\n if (at === -1 ? args.length !== rules.length : args.length < head.length + tail.length) {\n return null;\n }\n const values: Record<string, string | readonly string[]> = {};\n const take = (rule: ArgumentRule, arg: string): boolean => {\n if (!fits(rule, arg)) return false;\n if (rule.kind === 'placeholder') values[rule.name] = arg;\n return true;\n };\n for (let index = 0; index < head.length; index++) {\n if (!take(head[index]!, args[index]!)) return null;\n }\n const tailStart = args.length - tail.length;\n for (let index = 0; index < tail.length; index++) {\n if (!take(tail[index]!, args[tailStart + index]!)) return null;\n }\n if (at !== -1) {\n const rule = rules[at] as Extract<ArgumentRule, { kind: 'placeholder' }>;\n const middle = args.slice(head.length, tailStart);\n if (!middle.every((arg) => passes(rule, arg))) return null;\n values[rule.name] = middle;\n }\n return values;\n}\n\n/** What `matchSpawn` answers for a call a capability allows. */\nexport interface SpawnMatch {\n readonly capability: CompiledCapability;\n /** The program to run: the declared absolute path, or the name as it was pinned. */\n readonly path: string;\n readonly values: PlaceholderValues;\n}\n\n/**\n * The capability that allows running `program` with `args`, or null when none does. `program` is\n * the declared path or name exactly: a bare name is never looked up on any `PATH` here, and only\n * runs where `resolved` pinned it.\n *\n * @param resolved where each declared bare name was pinned at startup, by `resolveProgram`\n */\nexport function matchSpawn(\n capabilities: readonly CompiledCapability[],\n program: string,\n args: readonly string[],\n resolved: Readonly<Record<string, string | null>> = {},\n): SpawnMatch | null {\n for (const capability of capabilities) {\n const pinned = capability.program.startsWith('/')\n ? capability.program\n : (resolved[capability.program] ?? null);\n if (pinned === null) continue;\n if (program !== capability.program && program !== pinned) continue;\n const values = matchArguments(capability.args, args);\n if (values) return { capability, path: pinned, values };\n }\n return null;\n}\n\n/** What `resolveProgram` asks of the file system. */\nexport interface ProgramLookup {\n /** Whether an executable file is at `path`. */\n isExecutable(path: string): boolean;\n /**\n * Whether `path` is a developer tool stub that only runs `xcrun`, with no Command Line Tools\n * installed to run. Such a tool reports absent.\n */\n isStub?(path: string): boolean;\n}\n\n/**\n * Where a declared program runs from, pinned once at startup, or null when it is absent: not\n * found, or an `xcrun` stub without the Command Line Tools. A bare name is looked for on\n * `SEARCH_PATH` alone.\n */\nexport function resolveProgram(program: string, lookup: ProgramLookup): string | null {\n if (programProblem(program)) return null;\n const candidates = program.startsWith('/')\n ? [program]\n : SEARCH_PATH.map((dir) => `${dir}/${program}`);\n for (const candidate of candidates) {\n if (!lookup.isExecutable(candidate)) continue;\n return lookup.isStub?.(candidate) ? null : candidate;\n }\n return null;\n}\n\n/** The environment a spawned program gets: only the variables declared, of those given. */\nexport function filterEnvironment(\n env: Readonly<Record<string, string | undefined>>,\n allowed: readonly string[],\n): Record<string, string> {\n const filtered: Record<string, string> = {};\n for (const name of allowed) {\n const value = Object.hasOwn(env, name) ? env[name] : undefined;\n if (typeof value === 'string' && !value.includes('\\0')) filtered[name] = value;\n }\n return filtered;\n}\n"]}
package/dist/tray.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
- * Icons in the macOS menu bar's status area, each with a menu or a press of its own. `<tray-icon>`
3
- * in `@ng-native/components` registers here. Absent on iOS and Android, where nothing is drawn.
2
+ * Icons in the macOS menu bar's status area, or a Linux panel's as StatusNotifierItems, each with
3
+ * a menu or a press of its own. `<tray-icon>` in `@ng-native/components` registers here. Absent on
4
+ * iOS and Android, and on a Linux desktop with no StatusNotifierWatcher, where nothing is drawn.
4
5
  *
5
6
  * The host contract, on the `NgNativeTray` module: `setIcons(icons)` takes every icon each time one
6
7
  * changes, as `{ id, title, sfSymbol, image, tooltip, menu }`, `menu` as `serializeMenu` makes it
@@ -47,9 +48,11 @@ export declare class Tray {
47
48
  /** Overridden in a test with a fake host. */
48
49
  static readonly SOURCE: InjectionToken<NativeTray | null>;
49
50
  private readonly native;
51
+ /** The desktop OS whose shortcuts the menus show: Linux's own, else a Mac's. */
52
+ private readonly menuOs;
50
53
  private readonly icons;
51
54
  private next;
52
- /** Whether the OS has a status area for the app: macOS. */
55
+ /** Whether the OS has a status area for the app: macOS, and Linux with a StatusNotifierWatcher. */
53
56
  readonly available: Signal<boolean>;
54
57
  private readonly sent;
55
58
  private readonly unsubscribe;