tauri-plugin-live-activity 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/migration.mjs CHANGED
@@ -2,54 +2,49 @@
2
2
  // target compiled the plugin's own Swift: 0.4 takes the widget, the button intent and the custom views registry from
3
3
  // activitykit's Swift package.
4
4
  import { createHash } from 'node:crypto';
5
-
6
5
  /** The SHA-256 of each template as a release of the plugin wrote it into the widget folder. */
7
6
  export const RELEASED = {
8
- // 0.2.0, 0.2.1 and 0.3.0: the button intent, which activitykit's ActivityKitIntent product replaces.
9
- 'LiveActivityActionIntent.swift': ['cd96e40c42aae84b2e76db2f264f8ead892bf77c282e51f7443dc8624bc3ead5'],
10
- // 0.3.0: the base of the custom views, which activitykit's ActivityKitViews product replaces.
11
- 'LiveActivityCustomRegistry.swift': ['75c2275fe63da34234fca039ed459151edb851c1acf1faf0e6a400791345983f'],
12
- // 0.2.x and 0.3.0: the widget bundle on the plugin's own Swift modules.
13
- 'LiveActivityWidget.swift': [
14
- '2a76d033acbbd208c7050e10394c31c120ad96d0ff55189daed11ad5255cbd2c',
15
- 'a8abe58a70300204b1406e5dbcc0d53f6265b525785903d5b2e6e1d2b317476d',
16
- ],
7
+ // 0.2.0, 0.2.1 and 0.3.0: the button intent, which activitykit's ActivityKitIntent product replaces.
8
+ 'LiveActivityActionIntent.swift': ['cd96e40c42aae84b2e76db2f264f8ead892bf77c282e51f7443dc8624bc3ead5'],
9
+ // 0.3.0: the base of the custom views, which activitykit's ActivityKitViews product replaces.
10
+ 'LiveActivityCustomRegistry.swift': ['75c2275fe63da34234fca039ed459151edb851c1acf1faf0e6a400791345983f'],
11
+ // 0.2.x and 0.3.0: the widget bundle on the plugin's own Swift modules.
12
+ 'LiveActivityWidget.swift': [
13
+ '2a76d033acbbd208c7050e10394c31c120ad96d0ff55189daed11ad5255cbd2c',
14
+ 'a8abe58a70300204b1406e5dbcc0d53f6265b525785903d5b2e6e1d2b317476d',
15
+ ],
17
16
  };
18
-
19
17
  /** Files that only the plugin's own Swift needed. */
20
18
  export const RETIRED = ['LiveActivityActionIntent.swift', 'LiveActivityCustomRegistry.swift'];
21
-
22
19
  /** The Swift modules of the plugin before 0.4; a widget file that imports one no longer builds. */
23
20
  export const OLD_MODULES = /\bimport\s+(LiveActivityShared|LiveActivityUI|LiveActivityCore)\b/;
24
-
25
- const sha256 = text => createHash('sha256').update(text).digest('hex');
26
-
21
+ const sha256 = (text) => createHash('sha256').update(text).digest('hex');
27
22
  /** True when `text` is the file `name` exactly as a release wrote it. */
28
23
  export function released(name, text) {
29
- return RELEASED[name]?.includes(sha256(text)) ?? false;
24
+ const hashes = RELEASED[name];
25
+ return hashes.includes(sha256(text));
30
26
  }
31
-
32
27
  // The names of 0.3's custom views file and activitykit's, longest first: `LiveActivityCustomView` is a prefix of the
33
28
  // other two, and the class `LiveActivityCustomViews` keeps its Swift name.
34
29
  const RENAMES = [
35
- ['TauriLiveActivityCustomViews', 'ActivityKitCustomViews'],
36
- ['LiveActivityCustomViewRegistry', 'ActivityKitCustomViewRegistry'],
37
- ['LiveActivityCustomProps', 'ActivityKitCustomProps'],
38
- ['LiveActivityCustomView', 'ActivityKitCustomView'],
30
+ ['TauriLiveActivityCustomViews', 'ActivityKitCustomViews'],
31
+ ['LiveActivityCustomViewRegistry', 'ActivityKitCustomViewRegistry'],
32
+ ['LiveActivityCustomProps', 'ActivityKitCustomProps'],
33
+ ['LiveActivityCustomView', 'ActivityKitCustomView'],
39
34
  ];
40
-
41
35
  /**
42
36
  * The app's custom views file with activitykit's names: the Objective-C name, the registry, the view and props types,
43
37
  * and `import ActivityKitViews`. The app's views stay as they are. Undefined when the file has none of 0.3's names.
44
38
  */
45
39
  export function renameCustomViews(text) {
46
- if (!RENAMES.some(([old]) => new RegExp(`\\b${old}\\b`).test(text))) return undefined;
47
- let next = RENAMES.reduce((current, [old, name]) => current.replace(new RegExp(`\\b${old}\\b`, 'g'), name), text);
48
- if (!/^\s*import\s+ActivityKitViews\b/m.test(next)) {
49
- const swiftUI = /^import SwiftUI[ \t]*$/m.exec(next);
50
- next = swiftUI
51
- ? `${next.slice(0, swiftUI.index)}import ActivityKitViews\n${next.slice(swiftUI.index)}`
52
- : `import ActivityKitViews\n${next}`;
53
- }
54
- return next;
40
+ if (!RENAMES.some(([old]) => new RegExp(`\\b${old}\\b`).test(text)))
41
+ return undefined;
42
+ let next = RENAMES.reduce((current, [old, name]) => current.replace(new RegExp(`\\b${old}\\b`, 'g'), name), text);
43
+ if (!/^\s*import\s+ActivityKitViews\b/m.test(next)) {
44
+ const swiftUI = /^import SwiftUI[ \t]*$/m.exec(next);
45
+ next = swiftUI
46
+ ? `${next.slice(0, swiftUI.index)}import ActivityKitViews\n${next.slice(swiftUI.index)}`
47
+ : `import ActivityKitViews\n${next}`;
48
+ }
49
+ return next;
55
50
  }
package/cli/plist.mjs CHANGED
@@ -1,10 +1,8 @@
1
1
  // Just enough of XML property lists to set one Boolean key of the root dictionary.
2
-
3
2
  const TAG = /<(\/?)([A-Za-z]+)[^>]*?(\/?)>/g;
4
-
5
3
  /** A new plist whose root dictionary holds `key` = true. */
6
4
  export function newPlist(key) {
7
- return `<?xml version="1.0" encoding="UTF-8"?>
5
+ return `<?xml version="1.0" encoding="UTF-8"?>
8
6
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
9
7
  <plist version="1.0">
10
8
  <dict>
@@ -14,70 +12,74 @@ export function newPlist(key) {
14
12
  </plist>
15
13
  `;
16
14
  }
17
-
18
15
  /** Comments become spaces of the same length, so that positions still match the original text. */
19
16
  function blankComments(text) {
20
- return text.replace(/<!--[\s\S]*?-->/g, comment => ' '.repeat(comment.length));
17
+ return text.replace(/<!--[\s\S]*?-->/g, comment => ' '.repeat(comment.length));
21
18
  }
22
-
23
19
  /** Where the root dictionary opens and closes, and the value tag of each key at its top level. */
24
20
  function scanRoot(scan) {
25
- const plist = scan.indexOf('<plist');
26
- if (plist === -1) return undefined;
27
- const tags = [...scan.slice(plist).matchAll(TAG)].map(match => ({
28
- index: plist + match.index, end: plist + match.index + match[0].length,
29
- closing: match[1] === '/', name: match[2], empty: match[3] === '/',
30
- }));
31
- const root = tags.find(tag => tag.name !== 'plist');
32
- if (root?.name !== 'dict' || root.closing) return undefined;
33
- if (root.empty) return { root, close: undefined, keys: new Map() };
34
- return { root, ...rootEntries(scan, tags.slice(tags.indexOf(root) + 1)) };
21
+ const plist = scan.indexOf('<plist');
22
+ if (plist === -1)
23
+ return undefined;
24
+ const tags = [...scan.slice(plist).matchAll(TAG)].map((match) => ({
25
+ index: plist + match.index, end: plist + match.index + match[0].length,
26
+ closing: match[1] === '/', name: match[2] ?? '', empty: match[3] === '/',
27
+ }));
28
+ const root = tags.find(tag => tag.name !== 'plist');
29
+ if (root?.name !== 'dict' || root.closing)
30
+ return undefined;
31
+ if (root.empty)
32
+ return { root, close: undefined, keys: new Map() };
33
+ return { root, ...rootEntries(scan, tags.slice(tags.indexOf(root) + 1)) };
35
34
  }
36
-
37
35
  function rootEntries(scan, tags) {
38
- const keys = new Map();
39
- let depth = 0;
40
- let pendingKey;
41
- for (const tag of tags) {
42
- if (depth === 0 && tag.closing && tag.name === 'dict') return { close: tag, keys };
43
- if (depth === 0 && !tag.closing && tag.name === 'key') {
44
- pendingKey = scan.slice(tag.end, scan.indexOf('</key>', tag.end)).trim();
45
- } else if (depth === 0 && !tag.closing && pendingKey !== undefined) {
46
- keys.set(pendingKey, tag);
47
- pendingKey = undefined;
36
+ const keys = new Map();
37
+ let depth = 0;
38
+ let pendingKey;
39
+ for (const tag of tags) {
40
+ if (depth === 0 && tag.closing && tag.name === 'dict')
41
+ return { close: tag, keys };
42
+ if (depth === 0 && !tag.closing && tag.name === 'key') {
43
+ pendingKey = scan.slice(tag.end, scan.indexOf('</key>', tag.end)).trim();
44
+ }
45
+ else if (depth === 0 && !tag.closing && pendingKey !== undefined) {
46
+ keys.set(pendingKey, tag);
47
+ pendingKey = undefined;
48
+ }
49
+ if ((tag.name === 'dict' || tag.name === 'array') && !tag.empty)
50
+ depth += tag.closing ? -1 : 1;
48
51
  }
49
- if ((tag.name === 'dict' || tag.name === 'array') && !tag.empty) depth += tag.closing ? -1 : 1;
50
- }
51
- return { close: undefined, keys };
52
+ return { close: undefined, keys };
52
53
  }
53
-
54
54
  /**
55
55
  * Inserts the entry before the root's `</dict>`: on its own line when that tag starts a line, indented
56
56
  * like the first key of the root (`afterRoot` is the text after the root's opening tag).
57
57
  */
58
58
  function insertEntry(text, afterRoot, close, key) {
59
- const lineStart = text.lastIndexOf('\n', close.index - 1) + 1;
60
- if (!/^[ \t]*$/.test(text.slice(lineStart, close.index))) {
61
- return `${text.slice(0, close.index)}<key>${key}</key><true/>${text.slice(close.index)}`;
62
- }
63
- const indent = afterRoot.match(/\n([ \t]*)<key>/)?.[1] || '\t';
64
- return `${text.slice(0, lineStart)}${indent}<key>${key}</key>\n${indent}<true/>\n${text.slice(lineStart)}`;
59
+ const lineStart = text.lastIndexOf('\n', close.index - 1) + 1;
60
+ if (!/^[ \t]*$/.test(text.slice(lineStart, close.index))) {
61
+ return `${text.slice(0, close.index)}<key>${key}</key><true/>${text.slice(close.index)}`;
62
+ }
63
+ const indent = afterRoot.match(/\n([ \t]*)<key>/)?.[1] || '\t';
64
+ return `${text.slice(0, lineStart)}${indent}<key>${key}</key>\n${indent}<true/>\n${text.slice(lineStart)}`;
65
65
  }
66
-
67
66
  /**
68
67
  * Makes `key` true in the root dictionary of an XML plist. Status: `present` (already true), `added`
69
68
  * (with the new `text`), `false` or `other` (the key has another value, left as it is) or `unreadable`.
70
69
  */
71
70
  export function setTrueKey(text, key) {
72
- const scan = blankComments(text);
73
- const root = scanRoot(scan);
74
- if (!root) return { status: 'unreadable' };
75
- const value = root.keys.get(key);
76
- if (value) return { status: value.name === 'true' ? 'present' : value.name === 'false' ? 'false' : 'other' };
77
- if (root.root.empty) {
78
- const opened = `<dict>\n\t<key>${key}</key>\n\t<true/>\n</dict>`;
79
- return { status: 'added', text: text.slice(0, root.root.index) + opened + text.slice(root.root.end) };
80
- }
81
- if (!root.close) return { status: 'unreadable' };
82
- return { status: 'added', text: insertEntry(text, scan.slice(root.root.end), root.close, key) };
71
+ const scan = blankComments(text);
72
+ const root = scanRoot(scan);
73
+ if (!root)
74
+ return { status: 'unreadable' };
75
+ const value = root.keys.get(key);
76
+ if (value)
77
+ return { status: value.name === 'true' ? 'present' : value.name === 'false' ? 'false' : 'other' };
78
+ if (root.root.empty) {
79
+ const opened = `<dict>\n\t<key>${key}</key>\n\t<true/>\n</dict>`;
80
+ return { status: 'added', text: text.slice(0, root.root.index) + opened + text.slice(root.root.end) };
81
+ }
82
+ if (!root.close)
83
+ return { status: 'unreadable' };
84
+ return { status: 'added', text: insertEntry(text, scan.slice(root.root.end), root.close, key) };
83
85
  }
package/cli/report.mjs CHANGED
@@ -1,26 +1,32 @@
1
- // The summary that setup prints.
2
-
3
- const DONE = { created: 'created', updated: 'updated', removed: 'removed', ran: 'ran', kept: 'kept', skipped: 'skipped' };
4
- const WOULD = { created: 'would create', updated: 'would update', removed: 'would remove', ran: 'would run', kept: 'would keep', skipped: 'would skip' };
5
-
1
+ const DONE = {
2
+ created: 'created', updated: 'updated', removed: 'removed', ran: 'ran', kept: 'kept', skipped: 'skipped',
3
+ };
4
+ const WOULD = {
5
+ created: 'would create', updated: 'would update', removed: 'would remove', ran: 'would run', kept: 'would keep', skipped: 'would skip',
6
+ };
7
+ const isListed = (item) => Object.hasOwn(DONE, item.status);
6
8
  function line(item, dryRun) {
7
- const label = (dryRun ? WOULD : DONE)[item.status];
8
- return ` ${label.padEnd(dryRun ? 12 : 8)} ${item.path}${item.detail ? ` (${item.detail})` : ''}`;
9
+ const label = (dryRun ? WOULD : DONE)[item.status];
10
+ return ` ${label.padEnd(dryRun ? 12 : 8)} ${item.path}${item.detail ? ` (${item.detail})` : ''}`;
9
11
  }
10
-
11
12
  export function formatReport({ dryRun, version, steps, notes }) {
12
- const shown = steps.filter(item => Object.hasOwn(DONE, item.status));
13
- const todo = steps.filter(item => item.status === 'todo');
14
- const unchanged = steps.length - shown.length - todo.length;
15
- const lines = [`tauri-plugin-live-activity ${version} setup`, ''];
16
- if (dryRun) lines.push('Dry run: nothing was written.', '');
17
- if (shown.length === 0 && todo.length === 0) lines.push('Everything was set up already.');
18
- lines.push(...shown.map(item => line(item, dryRun)));
19
- if (shown.length > 0 && unchanged > 0) lines.push(` ${unchanged} other ${unchanged === 1 ? 'step' : 'steps'} needed no change.`);
20
- if (todo.length > 0) lines.push('', 'To do:', ...todo.map(item => ` ${item.path}: ${item.detail}`));
21
- if (steps.some(item => item.status === 'updated' && item.path.endsWith('project.yml'))) {
22
- lines.push('', 'If src-tauri/gen/apple is ever made from scratch, run setup again: the new project.yml lacks the include.');
23
- }
24
- for (const note of notes) lines.push('', note.kind === 'register' ? `Next: ${note.text}` : note.text);
25
- return `${lines.join('\n')}\n`;
13
+ const shown = steps.filter(isListed);
14
+ const todo = steps.filter(item => item.status === 'todo');
15
+ const unchanged = steps.length - shown.length - todo.length;
16
+ const lines = [`tauri-plugin-live-activity ${version} setup`, ''];
17
+ if (dryRun)
18
+ lines.push('Dry run: nothing was written.', '');
19
+ if (shown.length === 0 && todo.length === 0)
20
+ lines.push('Everything was set up already.');
21
+ lines.push(...shown.map(item => line(item, dryRun)));
22
+ if (shown.length > 0 && unchanged > 0)
23
+ lines.push(` ${unchanged} other ${unchanged === 1 ? 'step' : 'steps'} needed no change.`);
24
+ if (todo.length > 0)
25
+ lines.push('', 'To do:', ...todo.map(item => ` ${item.path}: ${item.detail}`));
26
+ if (steps.some(item => item.status === 'updated' && item.path.endsWith('project.yml'))) {
27
+ lines.push('', 'If src-tauri/gen/apple is ever made from scratch, run setup again: the new project.yml lacks the include.');
28
+ }
29
+ for (const note of notes)
30
+ lines.push('', note.kind === 'register' ? `Next: ${note.text}` : note.text);
31
+ return `${lines.join('\n')}\n`;
26
32
  }
package/cli/setup.mjs CHANGED
@@ -4,11 +4,9 @@ import { spawnSync } from 'node:child_process';
4
4
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
5
5
  import { dirname, join } from 'node:path';
6
6
  import { iosSteps } from './ios.mjs';
7
- import { SetupError, display, jsonLike, parseJson, readText, step, tail, writeFile } from './steps.mjs';
7
+ import { SetupError, display, errorCode, isList, isRecord, jsonLike, member, parseJson, readText, step, tail, writeFile, } from './steps.mjs';
8
8
  import { widgetFiles } from './widget-files.mjs';
9
-
10
9
  export { SetupError } from './steps.mjs';
11
-
12
10
  export const CRATE = 'tauri-plugin-live-activity';
13
11
  /** The crate whose Swift package the widget extension and the app target link. */
14
12
  export const ACTIVITYKIT = 'activitykit';
@@ -17,142 +15,174 @@ export const ACTIVITYKIT = 'activitykit';
17
15
  * Android's dialog, and in its setting for exact alarms.
18
16
  */
19
17
  export const PERMISSIONS = [
20
- 'live-activity:default',
21
- ...['request-permissions', 'open-exact-alarm-settings', 'start', 'update', 'end', 'start-layout', 'update-layout', 'end-layout',
22
- 'write-image']
23
- .map(command => `live-activity:allow-${command}`),
18
+ 'live-activity:default',
19
+ ...['request-permissions', 'open-exact-alarm-settings', 'start', 'update', 'end', 'start-layout', 'update-layout', 'end-layout',
20
+ 'write-image']
21
+ .map(command => `live-activity:allow-${command}`),
24
22
  ];
25
23
  // The plugin's Android library needs API 26: Tauri's Jackson runtime fails below it.
26
24
  const MIN_SDK = 26;
27
- const NPM_VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
28
-
25
+ const NPM_MANIFEST = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
26
+ const NPM_VERSION = String(member(NPM_MANIFEST, 'version'));
29
27
  /**
30
28
  * Sets up the app in `cwd` (its folder or its src-tauri folder) and returns the steps with their
31
29
  * status, and notes for the person who runs it. `fonts` and `assets` are files for the widget
32
30
  * extension; `appGroup` is true or the name of an App Group; with `smallFamily` the widget draws a layout's small
33
31
  * region. Throws SetupError when it cannot start.
34
32
  */
35
- export function setup({
36
- cwd = process.cwd(), env = process.env, dryRun = false, iosOnly = false, platform = process.platform,
37
- fonts = [], assets = [], appGroup = undefined, smallFamily = false,
38
- } = {}) {
39
- const files = widgetFiles(cwd, { fonts, assets });
40
- const app = findApp(cwd);
41
- const { plugin, activitykit } = findCrates(app, env);
42
- const context = { ...app, plugin, activitykit, env, platform, files, appGroup, smallFamily, show: path => display(cwd, path) };
43
- const planned = [...(iosOnly ? [] : [capabilitiesStep(context), ...androidSteps(context)]), ...iosSteps(context)];
44
- const steps = dryRun ? planned : planned.map(apply);
45
- return { dryRun, version: plugin.version, steps: steps.map(({ effect, ...rest }) => rest), notes: notes(context) };
33
+ export function setup({ cwd = process.cwd(), env = process.env, dryRun = false, iosOnly = false, platform = process.platform, fonts = [], assets = [], appGroup = undefined, smallFamily = false, } = {}) {
34
+ const files = widgetFiles(cwd, { fonts, assets });
35
+ const app = findApp(cwd);
36
+ const { plugin, activitykit } = findCrates(app, env);
37
+ const context = { ...app, plugin, activitykit, env, platform, files, appGroup, smallFamily, show: path => display(cwd, path) };
38
+ const planned = [...(iosOnly ? [] : [capabilitiesStep(context), ...androidSteps(context)]), ...iosSteps(context)];
39
+ const steps = dryRun ? planned : planned.map(apply);
40
+ return { dryRun, version: plugin.version, steps: steps.map(({ effect, ...rest }) => rest), notes: notes(context) };
46
41
  }
47
-
48
42
  function apply(planned) {
49
- if (!planned.effect) return planned;
50
- try {
51
- return planned.effect() ?? planned;
52
- } catch (error) {
53
- return step('todo', planned.path, `could not write it: ${error.message}`);
54
- }
43
+ if (!planned.effect)
44
+ return planned;
45
+ try {
46
+ return planned.effect() ?? planned;
47
+ }
48
+ catch (error) {
49
+ return step('todo', planned.path, `could not write it: ${error instanceof Error ? error.message : String(error)}`);
50
+ }
55
51
  }
56
-
57
52
  function findApp(cwd) {
58
- const srcTauri = [join(cwd, 'src-tauri'), cwd].find(folder => existsSync(join(folder, 'tauri.conf.json')));
59
- if (!srcTauri) {
60
- const other = [join(cwd, 'src-tauri'), cwd].flatMap(folder => ['tauri.conf.json5', 'Tauri.toml'].map(name => join(folder, name)))
61
- .find(existsSync);
62
- if (other) throw new SetupError(`Setup reads tauri.conf.json, and this app has ${display(cwd, other)}. docs/usage.md has the steps by hand.`);
63
- throw new SetupError('No src-tauri/tauri.conf.json here. Run this in the folder of a Tauri 2 app.');
64
- }
65
- const configPath = join(srcTauri, 'tauri.conf.json');
66
- const configText = readFileSync(configPath, 'utf8');
67
- const config = parseJson(configText);
68
- if (typeof config !== 'object' || config === null) throw new SetupError(`${display(cwd, configPath)} is not valid JSON.`);
69
- if (!existsSync(join(srcTauri, 'Cargo.toml'))) throw new SetupError('No src-tauri/Cargo.toml next to tauri.conf.json.');
70
- return { srcTauri, configPath, configText, config };
53
+ const srcTauri = [join(cwd, 'src-tauri'), cwd].find(folder => existsSync(join(folder, 'tauri.conf.json')));
54
+ if (!srcTauri) {
55
+ const other = [join(cwd, 'src-tauri'), cwd].flatMap(folder => ['tauri.conf.json5', 'Tauri.toml'].map(name => join(folder, name)))
56
+ .find(existsSync);
57
+ if (other)
58
+ throw new SetupError(`Setup reads tauri.conf.json, and this app has ${display(cwd, other)}. docs/usage.md has the steps by hand.`);
59
+ throw new SetupError('No src-tauri/tauri.conf.json here. Run this in the folder of a Tauri 2 app.');
60
+ }
61
+ const configPath = join(srcTauri, 'tauri.conf.json');
62
+ const configText = readFileSync(configPath, 'utf8');
63
+ const config = parseJson(configText);
64
+ if (!isRecord(config))
65
+ throw new SetupError(`${display(cwd, configPath)} is not valid JSON.`);
66
+ if (!existsSync(join(srcTauri, 'Cargo.toml')))
67
+ throw new SetupError('No src-tauri/Cargo.toml next to tauri.conf.json.');
68
+ return { srcTauri, configPath, configText, config };
69
+ }
70
+ /** A package of cargo's metadata, or undefined for an entry that lacks a member setup reads. */
71
+ function cargoPackage(item) {
72
+ const id = member(item, 'id');
73
+ const name = member(item, 'name');
74
+ const version = member(item, 'version');
75
+ const manifestPath = member(item, 'manifest_path');
76
+ return typeof id === 'string' && typeof name === 'string' && typeof version === 'string' && typeof manifestPath === 'string'
77
+ ? { id, name, version, manifestPath } : undefined;
78
+ }
79
+ /** The packages of cargo's metadata, or undefined when the text is not what `cargo metadata` prints. */
80
+ function cargoPackages(metadata) {
81
+ const listed = member(metadata, 'packages');
82
+ if (!isList(listed))
83
+ return undefined;
84
+ const packages = listed.map(cargoPackage).filter(item => item !== undefined);
85
+ return packages.length === listed.length ? packages : undefined;
86
+ }
87
+ /** The id of the package that `crate` takes its dependency `name` from, where cargo's resolve graph says. */
88
+ function dependencyId(metadata, crate, name) {
89
+ const nodes = member(metadata, 'resolve', 'nodes');
90
+ const deps = member(isList(nodes) ? nodes.find(node => member(node, 'id') === crate.id) : undefined, 'deps');
91
+ const id = member(isList(deps) ? deps.find(dep => member(dep, 'name') === name) : undefined, 'pkg');
92
+ return typeof id === 'string' ? id : undefined;
71
93
  }
72
-
73
94
  /**
74
95
  * The plugin crate's version and the folder of the activitykit crate it depends on, from `cargo metadata`: the widget
75
96
  * extension and the app target link activitykit's Swift package, which lies in that folder.
76
97
  */
77
98
  export function findCrates({ srcTauri }, env) {
78
- const args = ['metadata', '--format-version', '1', '--manifest-path', join(srcTauri, 'Cargo.toml')];
79
- const result = spawnSync(env.CARGO || 'cargo', args, { env, encoding: 'utf8', maxBuffer: 1024 ** 3 });
80
- if (result.error?.code === 'ENOENT') throw new SetupError('cargo was not found. Install Rust from https://rustup.rs, then run this again.');
81
- if (result.error) throw new SetupError(`cargo metadata could not run: ${result.error.message}`);
82
- if (result.status !== 0) throw new SetupError(`cargo metadata failed: ${tail(result.stderr)}`);
83
- const metadata = parseJson(result.stdout);
84
- if (!Array.isArray(metadata?.packages)) throw new SetupError('cargo metadata printed something that is not its JSON.');
85
- const crate = metadata.packages.find(item => item.name === CRATE);
86
- if (!crate) {
87
- throw new SetupError(`${CRATE} is not a dependency of src-tauri/Cargo.toml yet. Add it first:\n cargo add ${CRATE} --manifest-path src-tauri/Cargo.toml`);
88
- }
89
- const kitId = metadata.resolve?.nodes?.find(node => node.id === crate.id)?.deps?.find(dep => dep.name === ACTIVITYKIT)?.pkg;
90
- const kit = metadata.packages.find(item => (kitId ? item.id === kitId : item.name === ACTIVITYKIT));
91
- if (!kit) {
92
- throw new SetupError(`${CRATE} ${crate.version} does not depend on ${ACTIVITYKIT}, whose Swift package the widget extension links: use the crate of the npm package's version, ${NPM_VERSION}.`);
93
- }
94
- return {
95
- plugin: { version: crate.version, dir: dirname(crate.manifest_path) },
96
- activitykit: { version: kit.version, dir: dirname(kit.manifest_path) },
97
- };
99
+ const args = ['metadata', '--format-version', '1', '--manifest-path', join(srcTauri, 'Cargo.toml')];
100
+ const result = spawnSync(env.CARGO || 'cargo', args, { env, encoding: 'utf8', maxBuffer: 1024 ** 3 });
101
+ if (errorCode(result.error) === 'ENOENT')
102
+ throw new SetupError('cargo was not found. Install Rust from https://rustup.rs, then run this again.');
103
+ if (result.error)
104
+ throw new SetupError(`cargo metadata could not run: ${result.error.message}`);
105
+ if (result.status !== 0)
106
+ throw new SetupError(`cargo metadata failed: ${tail(result.stderr)}`);
107
+ const metadata = parseJson(result.stdout);
108
+ const packages = cargoPackages(metadata);
109
+ if (!packages)
110
+ throw new SetupError('cargo metadata printed something that is not its JSON.');
111
+ const crate = packages.find(item => item.name === CRATE);
112
+ if (!crate) {
113
+ throw new SetupError(`${CRATE} is not a dependency of src-tauri/Cargo.toml yet. Add it first:\n cargo add ${CRATE} --manifest-path src-tauri/Cargo.toml`);
114
+ }
115
+ const kitId = dependencyId(metadata, crate, ACTIVITYKIT);
116
+ const kit = packages.find(item => (kitId ? item.id === kitId : item.name === ACTIVITYKIT));
117
+ if (!kit) {
118
+ throw new SetupError(`${CRATE} ${crate.version} does not depend on ${ACTIVITYKIT}, whose Swift package the widget extension links: use the crate of the npm package's version, ${NPM_VERSION}.`);
119
+ }
120
+ return {
121
+ plugin: { version: crate.version, dir: dirname(crate.manifestPath) },
122
+ activitykit: { version: kit.version, dir: dirname(kit.manifestPath) },
123
+ };
98
124
  }
99
-
100
125
  /** Adds the plugin's permissions to the app's capability: default.json, or the only capability file. */
101
126
  function capabilitiesStep({ srcTauri, show }) {
102
- const folder = join(srcTauri, 'capabilities');
103
- const files = existsSync(folder) ? readdirSync(folder).filter(name => name.endsWith('.json')) : [];
104
- const name = files.includes('default.json') ? 'default.json' : files.length === 1 ? files[0] : undefined;
105
- const list = PERMISSIONS.join(', ');
106
- if (!name) return step('todo', show(folder), `add these permissions to the capability of your window: ${list}`);
107
- const path = join(folder, name);
108
- const text = readFileSync(path, 'utf8');
109
- const capability = parseJson(text);
110
- const valid = typeof capability === 'object' && capability !== null && Array.isArray(capability.permissions ?? []);
111
- if (!valid) return step('todo', show(path), `not valid JSON with a permissions list; add these permissions to it: ${list}`);
112
- const present = new Set((capability.permissions ?? []).map(item => (typeof item === 'string' ? item : item?.identifier)));
113
- const missing = PERMISSIONS.filter(permission => !present.has(permission));
114
- if (missing.length === 0) return step('unchanged', show(path));
115
- const next = { ...capability, permissions: [...(capability.permissions ?? []), ...missing] };
116
- return step('updated', show(path), `${missing.length} permissions added`, writeFile(path, jsonLike(text, next)));
127
+ const folder = join(srcTauri, 'capabilities');
128
+ const files = existsSync(folder) ? readdirSync(folder).filter(name => name.endsWith('.json')) : [];
129
+ const name = files.includes('default.json') ? 'default.json' : files.length === 1 ? files[0] : undefined;
130
+ const list = PERMISSIONS.join(', ');
131
+ if (!name)
132
+ return step('todo', show(folder), `add these permissions to the capability of your window: ${list}`);
133
+ const path = join(folder, name);
134
+ const text = readFileSync(path, 'utf8');
135
+ const capability = parseJson(text);
136
+ const permissions = member(capability, 'permissions') ?? [];
137
+ if (!isRecord(capability) || !isList(permissions))
138
+ return step('todo', show(path), `not valid JSON with a permissions list; add these permissions to it: ${list}`);
139
+ const present = new Set(permissions.map(item => (typeof item === 'string' ? item : member(item, 'identifier'))));
140
+ const missing = PERMISSIONS.filter(permission => !present.has(permission));
141
+ if (missing.length === 0)
142
+ return step('unchanged', show(path));
143
+ const next = { ...capability, permissions: [...permissions, ...missing] };
144
+ return step('updated', show(path), `${missing.length} permissions added`, writeFile(path, jsonLike(text, next)));
117
145
  }
118
-
119
146
  /** Tauri writes minSdk into gen/android when it creates it, from bundle.android.minSdkVersion (24 by default). */
120
147
  function androidSteps(context) {
121
- const gradle = gradleStep(context);
122
- return [minSdkConfigStep(context), ...(gradle ? [gradle] : [])];
148
+ const gradle = gradleStep(context);
149
+ return [minSdkConfigStep(context), ...(gradle ? [gradle] : [])];
123
150
  }
124
-
151
+ /** The members of a JSON object, to spread into its next form; a value that is no object has none. */
152
+ const members = (value) => (isRecord(value) ? value : {});
125
153
  function minSdkConfigStep({ configPath, configText, config, show }) {
126
- const current = config.bundle?.android?.minSdkVersion;
127
- if (Number.isInteger(current) && current >= MIN_SDK) return step('unchanged', show(configPath));
128
- const android = { ...config.bundle?.android, minSdkVersion: MIN_SDK };
129
- const text = jsonLike(configText, { ...config, bundle: { ...config.bundle, android } });
130
- return step('updated', show(configPath), `bundle.android.minSdkVersion = ${MIN_SDK}, as the plugin needs Android 8`, writeFile(configPath, text));
154
+ const current = member(config.bundle, 'android', 'minSdkVersion');
155
+ if (typeof current === 'number' && Number.isInteger(current) && current >= MIN_SDK)
156
+ return step('unchanged', show(configPath));
157
+ const android = { ...members(member(config.bundle, 'android')), minSdkVersion: MIN_SDK };
158
+ const text = jsonLike(configText, { ...config, bundle: { ...members(config.bundle), android } });
159
+ return step('updated', show(configPath), `bundle.android.minSdkVersion = ${MIN_SDK}, as the plugin needs Android 8`, writeFile(configPath, text));
131
160
  }
132
-
133
161
  function gradleStep({ srcTauri, show }) {
134
- const path = join(srcTauri, 'gen', 'android', 'app', 'build.gradle.kts');
135
- const gradle = readText(path);
136
- if (gradle === undefined) return undefined;
137
- const match = /^([ \t]*minSdk[ \t]*=[ \t]*)(\d+)[ \t]*$/m.exec(gradle);
138
- if (!match) return step('todo', show(path), `set minSdk to ${MIN_SDK}`);
139
- if (Number(match[2]) >= MIN_SDK) return step('unchanged', show(path));
140
- const at = match.index + match[1].length;
141
- return step('updated', show(path), `minSdk = ${MIN_SDK}`, writeFile(path, `${gradle.slice(0, at)}${MIN_SDK}${gradle.slice(at + match[2].length)}`));
162
+ const path = join(srcTauri, 'gen', 'android', 'app', 'build.gradle.kts');
163
+ const gradle = readText(path);
164
+ if (gradle === undefined)
165
+ return undefined;
166
+ const match = /^([ \t]*minSdk[ \t]*=[ \t]*)(\d+)[ \t]*$/m.exec(gradle);
167
+ if (!match)
168
+ return step('todo', show(path), `set minSdk to ${MIN_SDK}`);
169
+ const [, before = '', value = ''] = match;
170
+ if (Number(value) >= MIN_SDK)
171
+ return step('unchanged', show(path));
172
+ const at = match.index + before.length;
173
+ return step('updated', show(path), `minSdk = ${MIN_SDK}`, writeFile(path, `${gradle.slice(0, at)}${MIN_SDK}${gradle.slice(at + value.length)}`));
142
174
  }
143
-
144
- const minor = version => /^\d+\.\d+/.exec(version)?.[0];
145
-
175
+ const minor = (version) => /^\d+\.\d+/.exec(version)?.[0];
146
176
  function notes({ srcTauri, plugin }) {
147
- const sources = join(srcTauri, 'src');
148
- const registered = existsSync(sources) && readdirSync(sources, { recursive: true })
149
- .filter(name => String(name).endsWith('.rs'))
150
- .some(name => readFileSync(join(sources, String(name)), 'utf8').includes('tauri_plugin_live_activity::init'));
151
- return [
152
- ...(registered ? [] : [{ kind: 'register', text: 'add .plugin(tauri_plugin_live_activity::init()) to tauri::Builder in src-tauri/src/lib.rs.' }]),
153
- ...(minor(plugin.version) === minor(NPM_VERSION) ? [] : [{
154
- kind: 'version',
155
- text: `The npm package ${NPM_VERSION} and the crate ${plugin.version} differ: use the same minor version of both.`,
156
- }]),
157
- ];
177
+ const sources = join(srcTauri, 'src');
178
+ const registered = existsSync(sources) && readdirSync(sources, { recursive: true })
179
+ .filter(name => String(name).endsWith('.rs'))
180
+ .some(name => readFileSync(join(sources, String(name)), 'utf8').includes('tauri_plugin_live_activity::init'));
181
+ return [
182
+ ...(registered ? [] : [{ kind: 'register', text: 'add .plugin(tauri_plugin_live_activity::init()) to tauri::Builder in src-tauri/src/lib.rs.' }]),
183
+ ...(minor(plugin.version) === minor(NPM_VERSION) ? [] : [{
184
+ kind: 'version',
185
+ text: `The npm package ${NPM_VERSION} and the crate ${plugin.version} differ: use the same minor version of both.`,
186
+ }]),
187
+ ];
158
188
  }