@seavideo/cli 0.0.0-stage → 0.3.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 (110) hide show
  1. package/LICENSE +12 -0
  2. package/README.md +528 -2
  3. package/dist/bin/seavideo.js +11 -0
  4. package/dist/src/atomic-write.js +14 -0
  5. package/dist/src/canvas/api.js +172 -0
  6. package/dist/src/canvas/browser.js +40 -0
  7. package/dist/src/canvas/chrome-binary.js +109 -0
  8. package/dist/src/canvas/daemon.js +264 -0
  9. package/dist/src/canvas/engine-install.js +46 -0
  10. package/dist/src/canvas/engine-log.js +9 -0
  11. package/dist/src/canvas/engine.js +99 -0
  12. package/dist/src/canvas/entry.js +16 -0
  13. package/dist/src/canvas/env-lock.js +164 -0
  14. package/dist/src/canvas/launch.js +97 -0
  15. package/dist/src/canvas/lifecycle.js +65 -0
  16. package/dist/src/canvas/names.js +61 -0
  17. package/dist/src/canvas/params.js +38 -0
  18. package/dist/src/canvas/puppeteer.js +153 -0
  19. package/dist/src/canvas/screenshot.js +23 -0
  20. package/dist/src/canvas/session-record.js +77 -0
  21. package/dist/src/canvas/team.js +97 -0
  22. package/dist/src/canvas/tool-args.js +47 -0
  23. package/dist/src/canvas/tool-session.js +165 -0
  24. package/dist/src/canvas/tool-specs.js +54 -0
  25. package/dist/src/canvas/url.js +38 -0
  26. package/dist/src/cli/args.js +16 -0
  27. package/dist/src/cli/commands/auth.js +51 -0
  28. package/dist/src/cli/commands/canvas/common.js +31 -0
  29. package/dist/src/cli/commands/canvas/engine-choice.js +41 -0
  30. package/dist/src/cli/commands/canvas/index.js +5 -0
  31. package/dist/src/cli/commands/canvas/item.js +233 -0
  32. package/dist/src/cli/commands/canvas/list.js +168 -0
  33. package/dist/src/cli/commands/canvas/register.js +106 -0
  34. package/dist/src/cli/commands/canvas/render.js +229 -0
  35. package/dist/src/cli/commands/canvas/screenshot.js +52 -0
  36. package/dist/src/cli/commands/canvas/session.js +249 -0
  37. package/dist/src/cli/commands/canvas/teams.js +142 -0
  38. package/dist/src/cli/commands/config.js +74 -0
  39. package/dist/src/cli/commands/doctor.js +261 -0
  40. package/dist/src/cli/commands/engine.js +96 -0
  41. package/dist/src/cli/commands/env/create.js +160 -0
  42. package/dist/src/cli/commands/env/fields.js +26 -0
  43. package/dist/src/cli/commands/env/index.js +4 -0
  44. package/dist/src/cli/commands/env/list.js +44 -0
  45. package/dist/src/cli/commands/env/mutate.js +118 -0
  46. package/dist/src/cli/commands/login/flow-token.js +41 -0
  47. package/dist/src/cli/commands/login/index.js +12 -0
  48. package/dist/src/cli/commands/login/oauth.js +69 -0
  49. package/dist/src/cli/commands/login/save.js +26 -0
  50. package/dist/src/cli/commands/logout.js +92 -0
  51. package/dist/src/cli/commands/skill.js +185 -0
  52. package/dist/src/cli/commands/tool.js +279 -0
  53. package/dist/src/cli/commands/update.js +117 -0
  54. package/dist/src/cli/commands/wallet.js +69 -0
  55. package/dist/src/cli/commands/whoami.js +147 -0
  56. package/dist/src/cli/context.js +41 -0
  57. package/dist/src/cli/credential.js +93 -0
  58. package/dist/src/cli/elapsed.js +25 -0
  59. package/dist/src/cli/failure-screenshot.js +24 -0
  60. package/dist/src/cli/flags.js +1 -0
  61. package/dist/src/cli/hints.js +7 -0
  62. package/dist/src/cli/main.js +44 -0
  63. package/dist/src/cli/output-error.js +23 -0
  64. package/dist/src/cli/output.js +47 -0
  65. package/dist/src/cli/program.js +261 -0
  66. package/dist/src/cli/run.js +11 -0
  67. package/dist/src/cli/session.js +63 -0
  68. package/dist/src/config/base-url.js +26 -0
  69. package/dist/src/config/credential-vault.js +115 -0
  70. package/dist/src/config/dotenv.js +59 -0
  71. package/dist/src/config/envname.js +41 -0
  72. package/dist/src/config/paths.js +22 -0
  73. package/dist/src/config/preset-schema.js +67 -0
  74. package/dist/src/config/presets.js +132 -0
  75. package/dist/src/config/resolve.js +41 -0
  76. package/dist/src/config/secret-key.js +63 -0
  77. package/dist/src/config/store-schema.js +143 -0
  78. package/dist/src/config/store.js +273 -0
  79. package/dist/src/config/vault-crypto.js +44 -0
  80. package/dist/src/deps.js +191 -0
  81. package/dist/src/deps.types.js +1 -0
  82. package/dist/src/errors.js +24 -0
  83. package/dist/src/fs-retry.js +34 -0
  84. package/dist/src/i18n.js +1214 -0
  85. package/dist/src/loopback.js +134 -0
  86. package/dist/src/sdk/auth.js +20 -0
  87. package/dist/src/sdk/credential-expiry.js +67 -0
  88. package/dist/src/sdk/discovery.js +90 -0
  89. package/dist/src/sdk/http.js +98 -0
  90. package/dist/src/sdk/identity.js +17 -0
  91. package/dist/src/sdk/jwks.js +119 -0
  92. package/dist/src/sdk/oauth-protocol.js +226 -0
  93. package/dist/src/sdk/oauth.js +179 -0
  94. package/dist/src/sdk/provider/cn.js +34 -0
  95. package/dist/src/sdk/provider/index.js +16 -0
  96. package/dist/src/sdk/provider/oversea.js +41 -0
  97. package/dist/src/sdk/provider/types.js +1 -0
  98. package/dist/src/sdk/refresh.js +66 -0
  99. package/dist/src/semver.js +89 -0
  100. package/dist/src/skill/api.js +176 -0
  101. package/dist/src/text.js +3 -0
  102. package/dist/src/types.js +1 -0
  103. package/dist/src/update/check-cache.js +56 -0
  104. package/dist/src/update/install-layout.js +79 -0
  105. package/dist/src/update/notify.js +15 -0
  106. package/dist/src/update/npm-install.js +64 -0
  107. package/dist/src/update/passive.js +53 -0
  108. package/dist/src/update/registry.js +59 -0
  109. package/dist/src/wallet/api.js +107 -0
  110. package/package.json +67 -4
@@ -0,0 +1,176 @@
1
+ import { CliError } from "../errors.js";
2
+ import { SKILL_SUCCESS_CODE, requestJson } from "../sdk/http.js";
3
+ import { t } from "../i18n.js";
4
+ export const SKILL_PAGE_SIZE_LIMIT = 20;
5
+ export const SKILL_FILES_PER_ITEM_LIMIT = 100;
6
+ export const SKILL_MAX_KEYWORDS = 20;
7
+ export const SKILL_KEYWORD_MAX_LENGTH = 256;
8
+ export function subjectOf(token) {
9
+ const parts = token.split('.');
10
+ let result;
11
+ if (parts.length !== 3) {
12
+ result = null;
13
+ }
14
+ else {
15
+ const payload = parts[1];
16
+ let claims = null;
17
+ try {
18
+ claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
19
+ }
20
+ catch {
21
+ claims = null;
22
+ }
23
+ if (typeof claims === 'object' && claims !== null) {
24
+ const sub = claims['sub'];
25
+ result = typeof sub === 'string' && sub !== '' ? sub : null;
26
+ }
27
+ else {
28
+ result = null;
29
+ }
30
+ }
31
+ return result;
32
+ }
33
+ function str(v) {
34
+ return typeof v === 'string' && v !== '' ? v : null;
35
+ }
36
+ function num(v) {
37
+ return typeof v === 'number' ? v : 0;
38
+ }
39
+ function normalizeSkill(raw) {
40
+ const s = (raw ?? {});
41
+ const id = str(s['id']);
42
+ const name = s['name'];
43
+ if (id === null || typeof name !== 'string') {
44
+ throw new CliError('server', t('skill.malformed', {}));
45
+ }
46
+ const files = Array.isArray(s['files']) ? s['files'] : [];
47
+ return {
48
+ id,
49
+ name,
50
+ description: str(s['description']),
51
+ source: s['source'] === 'user' ? 'user' : 'global',
52
+ files: files
53
+ .map((f) => typeof f === 'object' && f !== null ? str(f['path']) : null)
54
+ .filter((p) => p !== null),
55
+ };
56
+ }
57
+ function errorOf(raw) {
58
+ let result;
59
+ if (raw === null || raw === undefined) {
60
+ result = null;
61
+ }
62
+ else {
63
+ const o = raw;
64
+ result = { code: str(o['code']) ?? 'unknown', message: str(o['message']) ?? '' };
65
+ }
66
+ return result;
67
+ }
68
+ function normalizeFile(raw, envMap) {
69
+ const f = (raw ?? {});
70
+ const path = str(f['path']);
71
+ if (path === null)
72
+ throw new CliError('server', t('skill.malformedFile', {}, envMap));
73
+ const error = errorOf(f['error']);
74
+ return {
75
+ path,
76
+ ok: f['ok'] === true,
77
+ content: str(f['content']),
78
+ error,
79
+ };
80
+ }
81
+ function normalizeReadItem(raw, envMap) {
82
+ const item = (raw ?? {});
83
+ const identifier = str(item['identifier']);
84
+ if (identifier === null)
85
+ throw new CliError('server', t('skill.malformedItem', {}, envMap));
86
+ const files = Array.isArray(item['files']) ? item['files'] : [];
87
+ return {
88
+ by: item['by'] === 'name' ? 'name' : 'id',
89
+ identifier,
90
+ ok: item['ok'] === true,
91
+ skill: normalizeSkillMeta(item['skill'], envMap),
92
+ files: files.map((f) => normalizeFile(f, envMap)),
93
+ error: errorOf(item['error']),
94
+ };
95
+ }
96
+ function normalizeSkillMeta(raw, envMap) {
97
+ let result;
98
+ if (raw === null || raw === undefined) {
99
+ result = null;
100
+ }
101
+ else {
102
+ const s = raw;
103
+ const id = str(s['id']);
104
+ const name = s['name'];
105
+ if (id === null || typeof name !== 'string') {
106
+ throw new CliError('server', t('skill.malformedSkillMeta', {}, envMap));
107
+ }
108
+ result = { id, name, description: str(s['description']), source: str(s['source']) ?? 'global' };
109
+ }
110
+ return result;
111
+ }
112
+ export function createSkillApi(deps, config, token) {
113
+ const subject = subjectOf(token);
114
+ if (subject === null) {
115
+ throw new CliError('config', t('skill.noSubject', {}, deps.env), {
116
+ detail: t('skill.noSubjectDetail', {}, deps.env),
117
+ });
118
+ }
119
+ const http = { fetch: deps.fetch, env: deps.env, baseUrl: config.aiVideoApiBaseUrl };
120
+ const headers = { authorization: `Bearer ${token}` };
121
+ return {
122
+ async search(params) {
123
+ const body = {
124
+ page: params.page,
125
+ page_size: params.pageSize,
126
+ };
127
+ if (params.keywords !== undefined && params.keywords.length > 0) {
128
+ body['keywords'] = [...params.keywords];
129
+ }
130
+ else {
131
+ }
132
+ const data = await requestJson(http, {
133
+ method: 'POST',
134
+ path: `/api/${encodeURIComponent(subject)}/skills/search`,
135
+ headers,
136
+ body,
137
+ successCode: SKILL_SUCCESS_CODE,
138
+ });
139
+ const summary = (data['summary'] ?? {});
140
+ const rawSkills = Array.isArray(data['skills']) ? data['skills'] : [];
141
+ const keywords = Array.isArray(data['keywords']) ? data['keywords'] : [];
142
+ return {
143
+ keywords: keywords.filter((k) => typeof k === 'string'),
144
+ total: num(summary['total']),
145
+ page: num(summary['page']),
146
+ pageSize: num(summary['page_size']),
147
+ skills: rawSkills.map(normalizeSkill),
148
+ };
149
+ },
150
+ async read(items) {
151
+ const data = await requestJson(http, {
152
+ method: 'POST',
153
+ path: `/api/${encodeURIComponent(subject)}/skills/read`,
154
+ headers,
155
+ body: {
156
+ items: items.map((item) => ({
157
+ ...(item.by === undefined ? {} : { by: item.by }),
158
+ identifier: item.identifier,
159
+ ...(item.files === undefined ? {} : { files: [...item.files] }),
160
+ })),
161
+ },
162
+ successCode: SKILL_SUCCESS_CODE,
163
+ });
164
+ const rawItems = Array.isArray(data['items']) ? data['items'] : [];
165
+ return {
166
+ requested: num(data['requested']),
167
+ succeeded: num(data['succeeded']),
168
+ failed: num(data['failed']),
169
+ filesRequested: num(data['files_requested']),
170
+ filesSucceeded: num(data['files_succeeded']),
171
+ filesFailed: num(data['files_failed']),
172
+ items: rawItems.map((i) => normalizeReadItem(i, deps.env)),
173
+ };
174
+ },
175
+ };
176
+ }
@@ -0,0 +1,3 @@
1
+ export function sanitizeText(value) {
2
+ return value.replace(/[\x00-\x1f\x7f-\x9f]/g, '');
3
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,56 @@
1
+ import { writeFileAtomic } from "../atomic-write.js";
2
+ export const SUCCESS_TTL_MS = 10 * 60 * 1000;
3
+ export const FAILURE_TTL_MS = 5 * 60 * 1000;
4
+ const MINUTE_MS = 60 * 1000;
5
+ export const INTERVAL_ENV = 'SEAVIDEO_UPDATE_CHECK_MINUTES';
6
+ export const DISABLE_ENV = 'SEAVIDEO_NO_UPDATE_CHECK';
7
+ export function successTtlOf(env) {
8
+ const raw = env[INTERVAL_ENV];
9
+ const minutes = raw === undefined || raw === '' ? Number.NaN : Number(raw);
10
+ return Number.isFinite(minutes) && minutes > 0 ? minutes * MINUTE_MS : SUCCESS_TTL_MS;
11
+ }
12
+ export function checkDisabled(env) {
13
+ return env[DISABLE_ENV] === '1';
14
+ }
15
+ export async function readCheckCache(fs, path) {
16
+ let result;
17
+ try {
18
+ const parsed = JSON.parse(await fs.readFile(path, 'utf8'));
19
+ const checkedAt = parsed['checkedAt'];
20
+ result =
21
+ typeof checkedAt === 'string' && Number.isFinite(Date.parse(checkedAt))
22
+ ? {
23
+ checkedAt,
24
+ latest: stringOrNull(parsed['latest']),
25
+ channel: stringOrNull(parsed['channel']),
26
+ notified: stringOrNull(parsed['notified']),
27
+ }
28
+ : null;
29
+ }
30
+ catch {
31
+ result = null;
32
+ }
33
+ return result;
34
+ }
35
+ function stringOrNull(value) {
36
+ return typeof value === 'string' ? value : null;
37
+ }
38
+ export async function writeCheckCache(deps, path, cache) {
39
+ try {
40
+ await writeFileAtomic(deps, path, `${JSON.stringify(cache, null, 2)}\n`, 0o600);
41
+ }
42
+ catch {
43
+ }
44
+ }
45
+ export function cacheUsable(cache, now, ttlMs) {
46
+ let result;
47
+ if (cache === null) {
48
+ result = false;
49
+ }
50
+ else {
51
+ const age = now.getTime() - Date.parse(cache.checkedAt);
52
+ const ttl = cache.latest === null ? FAILURE_TTL_MS : ttlMs;
53
+ result = Number.isFinite(age) && age >= 0 && age < ttl;
54
+ }
55
+ return result;
56
+ }
@@ -0,0 +1,79 @@
1
+ import { posix, win32 } from 'node:path';
2
+ const PACKAGE_SEGMENTS = ['node_modules', '@seavideo', 'cli'];
3
+ function pathOf(platform) {
4
+ return platform === 'win32' ? win32 : posix;
5
+ }
6
+ export function shimPathOf(platform, prefix) {
7
+ const path = pathOf(platform);
8
+ return platform === 'win32'
9
+ ? path.join(prefix, 'seavideo.cmd')
10
+ : path.join(prefix, 'bin', 'seavideo');
11
+ }
12
+ export async function detectInstallLayout(deps, scriptPath) {
13
+ const resolved = await realpathOrSelf(deps, scriptPath);
14
+ const sep = pathOf(deps.platform).sep;
15
+ const segments = resolved.split(sep);
16
+ const at = indexOfSegments(segments, PACKAGE_SEGMENTS);
17
+ let result;
18
+ if (at < 0) {
19
+ result = {
20
+ kind: 'unsupported',
21
+ reason: resolved.includes(`${sep}node_modules${sep}`) ? 'unknown-layout' : 'not-installed',
22
+ };
23
+ }
24
+ else {
25
+ result = await layoutFrom(deps, segments.slice(0, at), segments.slice(at));
26
+ }
27
+ return result;
28
+ }
29
+ async function realpathOrSelf(deps, path) {
30
+ let result;
31
+ try {
32
+ result = await deps.realpath(path);
33
+ }
34
+ catch {
35
+ result = path;
36
+ }
37
+ return result;
38
+ }
39
+ function indexOfSegments(haystack, needle) {
40
+ let found = -1;
41
+ for (let i = 0; i + needle.length <= haystack.length && found < 0; i += 1) {
42
+ const matches = needle.every((seg, k) => haystack[i + k] === seg);
43
+ found = matches ? i : -1;
44
+ }
45
+ return found;
46
+ }
47
+ async function layoutFrom(deps, before, rest) {
48
+ const path = pathOf(deps.platform);
49
+ const last = before[before.length - 1];
50
+ const prefixSegments = last === 'lib' ? before.slice(0, -1) : before;
51
+ const prefix = prefixSegments.join(path.sep) === '' ? path.sep : prefixSegments.join(path.sep);
52
+ let result;
53
+ if (await exists(deps, shimPathOf(deps.platform, prefix))) {
54
+ result = { kind: 'global', prefix };
55
+ }
56
+ else {
57
+ result = await unsupportedReason(deps, prefix, rest);
58
+ }
59
+ return result;
60
+ }
61
+ async function unsupportedReason(deps, prefix, rest) {
62
+ const packageJson = pathOf(deps.platform).join(prefix, ...PACKAGE_SEGMENTS, 'package.json');
63
+ const known = rest.length > 0 && (await exists(deps, packageJson));
64
+ return {
65
+ kind: 'unsupported',
66
+ reason: known ? 'local-dependency' : 'unknown-layout',
67
+ };
68
+ }
69
+ async function exists(deps, path) {
70
+ let result;
71
+ try {
72
+ await deps.fs.stat(path);
73
+ result = true;
74
+ }
75
+ catch {
76
+ result = false;
77
+ }
78
+ return result;
79
+ }
@@ -0,0 +1,15 @@
1
+ import { compareVersions } from "../semver.js";
2
+ import { t } from "../i18n.js";
3
+ import { DISABLE_ENV } from "./check-cache.js";
4
+ export function shouldConsiderPassive(env, stderrIsTTY) {
5
+ return stderrIsTTY && env[DISABLE_ENV] !== '1';
6
+ }
7
+ export function decideNotice(current, latest, cache) {
8
+ const newer = latest !== null && compareVersions(latest, current) === 1;
9
+ const alreadyNotified = cache?.notified === latest;
10
+ return newer && !alreadyNotified ? latest : null;
11
+ }
12
+ export function printNotice(deps, current, latest) {
13
+ deps.stderr(`\n${t('update.available', { current, latest }, deps.env)}\n` +
14
+ `${t('update.hint', {}, deps.env)}\n`);
15
+ }
@@ -0,0 +1,64 @@
1
+ import { spawn } from 'node:child_process';
2
+ export function npmInstallArgs(spec, prefix, registry) {
3
+ return [
4
+ 'install',
5
+ '-g',
6
+ spec,
7
+ '--prefix',
8
+ prefix,
9
+ '--registry',
10
+ registry,
11
+ '--no-audit',
12
+ '--no-fund',
13
+ ];
14
+ }
15
+ export function npmCommandOf(platform) {
16
+ return platform === 'win32' ? 'npm.cmd' : 'npm';
17
+ }
18
+ export function scriptPathOf(argv) {
19
+ return argv[1] ?? '';
20
+ }
21
+ const OUTPUT_TAIL = 2000;
22
+ export function exitCodeOf(code) {
23
+ return typeof code === 'number' ? code : 1;
24
+ }
25
+ export function makeNpmInstall(command, spawnFn = runProcess, useShell = false) {
26
+ return async (spec, prefix, registry) => {
27
+ const result = await spawnFn(command, npmInstallArgs(spec, prefix, registry), useShell);
28
+ return { code: result.code, output: result.output.slice(-OUTPUT_TAIL) };
29
+ };
30
+ }
31
+ export async function runProcess(command, args, useShell, spawnFn = spawn) {
32
+ let child = null;
33
+ let spawnError = null;
34
+ try {
35
+ child = spawnFn(command, [...args], {
36
+ shell: useShell,
37
+ windowsHide: true,
38
+ stdio: ['ignore', 'pipe', 'pipe'],
39
+ });
40
+ }
41
+ catch (err) {
42
+ spawnError = err;
43
+ }
44
+ return child === null ? spawnFailed(spawnError) : collectFrom(child);
45
+ }
46
+ function spawnFailed(err) {
47
+ return { code: 127, output: err instanceof Error ? err.message : String(err) };
48
+ }
49
+ async function collectFrom(child) {
50
+ const chunks = [];
51
+ const collect = (data) => {
52
+ chunks.push(data.toString('utf8'));
53
+ };
54
+ child.stdout?.on('data', collect);
55
+ child.stderr?.on('data', collect);
56
+ return new Promise((resolve) => {
57
+ child.on('error', (err) => {
58
+ resolve({ code: 127, output: err.message });
59
+ });
60
+ child.on('close', (code) => {
61
+ resolve({ code: exitCodeOf(code), output: chunks.join('') });
62
+ });
63
+ });
64
+ }
@@ -0,0 +1,53 @@
1
+ import { VERSION } from "../cli/program.js";
2
+ import { cacheUsable, readCheckCache, successTtlOf, writeCheckCache, } from "./check-cache.js";
3
+ import { decideNotice, printNotice, shouldConsiderPassive } from "./notify.js";
4
+ import { DEFAULT_CHANNEL, fetchVersionInfo, PACKAGE_NAME } from "./registry.js";
5
+ export async function checkVersionBeforeCommand(deps, paths) {
6
+ if (shouldConsiderPassive(deps.env, deps.stderrIsTTY)) {
7
+ const cache = await readCheckCache(deps.fs, paths.versionCheckFile);
8
+ const latest = decideNotice(VERSION, cache?.latest ?? null, cache);
9
+ if (latest !== null) {
10
+ printNotice(deps, VERSION, latest);
11
+ await writeCheckCache(deps, paths.versionCheckFile, {
12
+ ...cache,
13
+ notified: latest,
14
+ });
15
+ }
16
+ else {
17
+ }
18
+ }
19
+ else {
20
+ }
21
+ }
22
+ export async function refreshVersionAfterCommand(deps, paths) {
23
+ if (shouldConsiderPassive(deps.env, deps.stderrIsTTY)) {
24
+ const cache = await readCheckCache(deps.fs, paths.versionCheckFile);
25
+ if (!cacheUsable(cache, deps.clock(), successTtlOf(deps.env))) {
26
+ await refreshCache(deps, paths, cache);
27
+ }
28
+ else {
29
+ }
30
+ }
31
+ else {
32
+ }
33
+ }
34
+ async function refreshCache(deps, paths, cache) {
35
+ const channel = cache?.channel ?? DEFAULT_CHANNEL;
36
+ try {
37
+ const info = await fetchVersionInfo({ fetch: deps.fetch, env: deps.env }, PACKAGE_NAME, VERSION, channel);
38
+ await writeCheckCache(deps, paths.versionCheckFile, {
39
+ checkedAt: deps.clock().toISOString(),
40
+ latest: info.latest,
41
+ channel,
42
+ notified: cache?.notified ?? null,
43
+ });
44
+ }
45
+ catch {
46
+ await writeCheckCache(deps, paths.versionCheckFile, {
47
+ checkedAt: deps.clock().toISOString(),
48
+ latest: cache?.latest ?? null,
49
+ channel,
50
+ notified: cache?.notified ?? null,
51
+ });
52
+ }
53
+ }
@@ -0,0 +1,59 @@
1
+ import { CliError } from "../errors.js";
2
+ import { t } from "../i18n.js";
3
+ import { compareVersions } from "../semver.js";
4
+ export const DEFAULT_REGISTRY = 'https://registry.npmjs.org';
5
+ export const PACKAGE_NAME = '@seavideo/cli';
6
+ export const REGISTRY_ENV = 'SEAVIDEO_REGISTRY';
7
+ export const DEFAULT_CHANNEL = 'latest';
8
+ export const PASSIVE_TIMEOUT_MS = 800;
9
+ export const EXPLICIT_TIMEOUT_MS = 5_000;
10
+ export function registryOf(env, explicit) {
11
+ let result;
12
+ if (explicit !== undefined && explicit !== '') {
13
+ result = explicit;
14
+ }
15
+ else {
16
+ const override = env[REGISTRY_ENV];
17
+ result = override === undefined || override === '' ? DEFAULT_REGISTRY : override;
18
+ }
19
+ return result;
20
+ }
21
+ export function assertRegistryUrl(value, envMap) {
22
+ if (value === '')
23
+ return;
24
+ let ok = false;
25
+ try {
26
+ const url = new URL(value);
27
+ ok = url.protocol === 'http:' || url.protocol === 'https:';
28
+ }
29
+ catch {
30
+ ok = false;
31
+ }
32
+ if (!ok) {
33
+ throw new CliError('usage', t('update.badRegistry', { value }, envMap));
34
+ }
35
+ }
36
+ function packageUrl(registry, name) {
37
+ const base = registry.replace(/\/+$/u, '');
38
+ return `${base}/${name.replace('/', '%2f')}`;
39
+ }
40
+ export async function fetchVersionInfo(deps, name, current, channel = DEFAULT_CHANNEL, timeoutMs = PASSIVE_TIMEOUT_MS, explicitRegistry) {
41
+ const registry = registryOf(deps.env, explicitRegistry);
42
+ const response = await deps.fetch(packageUrl(registry, name), {
43
+ headers: { accept: 'application/vnd.npm.install-v1+json' },
44
+ signal: AbortSignal.timeout(timeoutMs),
45
+ });
46
+ if (!response.ok)
47
+ throw new Error(`registry responded ${response.status}`);
48
+ const body = (await response.json());
49
+ const tags = body['dist-tags'] ?? {};
50
+ const raw = tags[channel];
51
+ const latest = typeof raw === 'string' ? raw : null;
52
+ return {
53
+ current,
54
+ channel,
55
+ latest,
56
+ updateAvailable: latest !== null && compareVersions(latest, current) === 1,
57
+ registry,
58
+ };
59
+ }
@@ -0,0 +1,107 @@
1
+ import { CliError } from "../errors.js";
2
+ import { t } from "../i18n.js";
3
+ export const WALLET_PATH = '/api/payment/tokens/wallet';
4
+ export async function fetchWallet(deps, config, token) {
5
+ const response = await deps.fetch(`${config.flowApiBaseUrl}${WALLET_PATH}`, {
6
+ headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
7
+ signal: AbortSignal.timeout(WALLET_TIMEOUT_MS),
8
+ });
9
+ if (!response.ok) {
10
+ throw new CliError('server', t('http.serverStatus', { status: response.status }, deps.env), {
11
+ detail: response.headers.get('x-request-id') ?? undefined,
12
+ });
13
+ }
14
+ let body;
15
+ try {
16
+ body = await response.json();
17
+ }
18
+ catch (err) {
19
+ throw new CliError('server', t('http.notJson', { status: response.status, url: WALLET_PATH }, deps.env), {
20
+ detail: err instanceof Error ? err.message : String(err),
21
+ });
22
+ }
23
+ return normalizeWallet(body, deps.env);
24
+ }
25
+ export const WALLET_TIMEOUT_MS = 10_000;
26
+ export function normalizeWallet(body, envMap) {
27
+ const envelope = (typeof body === 'object' && body !== null ? body : {});
28
+ const status = envelope['status'];
29
+ const code = status?.code;
30
+ if (code !== 20000) {
31
+ throw new CliError('server', t('wallet.businessError', { code: String(code ?? 'missing') }, envMap), { detail: typeof status?.msg === 'string' ? status.msg : undefined });
32
+ }
33
+ const data = envelope['data'];
34
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
35
+ throw new CliError('server', t('wallet.malformed', {}, envMap));
36
+ }
37
+ const walletData = data;
38
+ return {
39
+ availablePaid: balanceOf(walletData['available_paid_balance']),
40
+ availableBonus: balanceOf(walletData['available_bonus_balance']),
41
+ frozenPaid: balanceOf(walletData['frozen_paid_balance']),
42
+ frozenBonus: balanceOf(walletData['frozen_bonus_balance']),
43
+ totalConsumed: balanceOf(walletData['total_consumed']),
44
+ totalRecharged: balanceOf(walletData['total_recharged']),
45
+ totalRefunded: balanceOf(walletData['total_refunded']),
46
+ totalExpired: balanceOf(walletData['total_expired']),
47
+ productClassBalances: balancesOf(walletData['product_class_balances']),
48
+ lots: lotsOf(walletData['lots']),
49
+ };
50
+ }
51
+ function balanceOf(value) {
52
+ return typeof value === 'string' && /^\d+(\.\d+)?$/u.test(value) ? value : '0';
53
+ }
54
+ function balancesOf(value) {
55
+ const result = {};
56
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
57
+ for (const [key, raw] of Object.entries(value)) {
58
+ result[key] = balanceOf(raw);
59
+ }
60
+ }
61
+ else {
62
+ }
63
+ return result;
64
+ }
65
+ function lotsOf(value) {
66
+ const list = Array.isArray(value) ? value : [];
67
+ return list.map((item) => {
68
+ const raw = (typeof item === 'object' && item !== null ? item : {});
69
+ return {
70
+ lotId: strOf(raw['lot_id']),
71
+ category: strOf(raw['category']),
72
+ productClass: strOf(raw['product_class']),
73
+ initialAmount: balanceOf(raw['initial_amount']),
74
+ availableAmount: balanceOf(raw['available_amount']),
75
+ frozenAmount: balanceOf(raw['frozen_amount']),
76
+ consumedAmount: balanceOf(raw['consumed_amount']),
77
+ expiredAmount: balanceOf(raw['expired_amount']),
78
+ createdAt: strOf(raw['created_at']),
79
+ expireAt: strOf(raw['expire_at']),
80
+ remark: strOf(raw['remark']),
81
+ };
82
+ });
83
+ }
84
+ function strOf(value) {
85
+ return typeof value === 'string' ? value : '';
86
+ }
87
+ export function availableTotal(wallet) {
88
+ return addBalances(wallet.availablePaid, wallet.availableBonus);
89
+ }
90
+ export function frozenTotal(wallet) {
91
+ return addBalances(wallet.frozenPaid, wallet.frozenBonus);
92
+ }
93
+ export function addBalances(a, b) {
94
+ const [aInt, aFrac = ''] = a.split('.');
95
+ const [bInt, bFrac = ''] = b.split('.');
96
+ const scale = Math.max(aFrac.length, bFrac.length);
97
+ const unit = 10n ** BigInt(scale);
98
+ const total = BigInt(aInt) * unit +
99
+ BigInt(aFrac.padEnd(scale, '0') || '0') +
100
+ BigInt(bInt) * unit +
101
+ BigInt(bFrac.padEnd(scale, '0') || '0');
102
+ const intPart = total / unit;
103
+ const fracPart = total % unit;
104
+ return fracPart === 0n
105
+ ? intPart.toString()
106
+ : `${intPart}.${fracPart.toString().padStart(scale, '0').replace(/0+$/u, '')}`;
107
+ }