@tulcn/tshare 0.0.0-stage → 0.1.3

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/README.md CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # tshare
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Share HTML reports as expiring links。
4
+
5
+ ## 安装与运行
6
+
7
+ 需要 Node.js >=22.12。从 npm 安装:
8
+
9
+ **pwsh / bash**
10
+
11
+ ```sh
12
+ pnpm add -g @tulcn/tshare --allow-build=@tulcn/tshare
13
+ tshare --help
14
+ tshare -h
15
+ ```
16
+
17
+ `--allow-build` 让 pnpm 运行本包安装 Skill 的脚本(pnpm 默认不跑全局安装包的安装脚本)。安装提示里只列出 `@tulcn/lxz` 的 `Ignored build scripts` 时不用处理。如果 Skill 没装上,运行 `tshare install skill` 补装。
18
+
19
+ 使用前请向此 CLI 的维护者获取授权环境和访问权限。
20
+
21
+ 命令和分组均支持 -h(同 --help)。例如运行 tshare install -h 查看安装子命令,tshare init -h 查看初始化参数,tshare share -h 查看分享参数。帮助用于了解命令与参数,可直接调用。
22
+
23
+ ## 配置与登录
24
+
25
+ 请向维护者确认授权环境和访问权限,业务服务由维护者部署并由平台配置网关路由。
26
+
27
+ `tshare config service` 查看当前网关地址。业务地址由 LINKWISE_ISSUER 的域名和项目标识 "share" 推导,默认使用正式环境。登录和续期由随依赖安装的 lxz 主程序办理。
28
+
29
+ 首次使用时完成登录,并查看状态:
30
+
31
+ **pwsh / bash**
32
+
33
+ ```sh
34
+ tshare init
35
+ tshare status
36
+ ```
37
+
38
+ init 会打开默认浏览器,请核对验证码并确认授权;命令在操作总时限和设备码有效期内等待。临时网络故障、请求超时和 5xx 会在原验证码有效期内继续等待。可用 --timeout-ms 调整本次操作总时限,验证码本身仍有有效期。status 显示本机状态;logout 撤销当前 CLI 的本次服务端授权并删除本机令牌,其他会话不受影响。撤销最多等待 10 秒;失败仍清理,并提示服务端授权可能仍有效、需要时联系管理员撤销。
39
+
40
+ ## 使用功能
41
+
42
+ - 分享 HTML:`tshare share --file ./report.html --dry-run` 预览,确认后把 `--dry-run` 换成 `--confirm`。默认 24 小时有效,`--hours` 可设 1–72,`--title` 设置消息标题。
43
+ - 换新链接:`tshare renew --id <id> --hours 48 --confirm`,不超过上传后 72 小时。
44
+ - 作废:`tshare revoke --id <id> --confirm`,所有链接立即失效。
45
+ - 查看:`tshare list`。
46
+
47
+ 链接在公网可访问、无需登录,拿到链接的人都能打开,请只分享可以外发的内容。HTML 要做成单个文件,图片内嵌,不超过 10 MiB。结果里的 `dingtalkUrl` 在钉钉电脑端点开会直接用浏览器打开。
48
+
49
+ 默认输出行数据;Agent 使用 --non-interactive,需要程序解析时加 --json。遇到登录要求时先由用户完成授权;写入失败后先核实实际状态,避免重复提交。所有业务调用都经过配置的后端;数据由服务返回。
50
+
51
+ 结束使用时退出当前授权:
52
+
53
+ **pwsh / bash**
54
+
55
+ ```sh
56
+ tshare logout
57
+ ```
58
+
59
+ ## 中文与文本编码
60
+
61
+ 命令说明、帮助、提示和程序日志使用英文 ASCII;业务数据、用户输入及路径按 UTF-8 输出,中文等字符直接显示。脚本调用使用 `--json --non-interactive`,按 UTF-8 解码,先解析 JSON 再读取字段。
62
+
63
+ 文本文件输入接受 UTF-8(含 BOM)和 GBK,优先 UTF-8;无法解码时报错。导出文件仍使用 UTF-8,上传和下载保持原始字节。
64
+
65
+
66
+ ## Agent 接入与版本切换
67
+
68
+ pnpm 安装提供程序和内置 Skill;依赖的 postinstall 是否运行由 pnpm 的构建脚本授权策略决定。手动使用时运行 tshare init,自然完成授权和 Skill 安装;首次交给 Agent、升级或回滚后,运行下面的命令同步此版本说明。授权和安装均委托依赖中的 lxz 主程序办理。说明写入 Skills 根目录下的 tshare/。
69
+
70
+ **pwsh / bash**
71
+
72
+ ```sh
73
+ tshare install skill --skills-dir '<Agent 的 Skills 根目录>'
74
+ ```
75
+
76
+ 目录优先使用 --skills-dir,其次 LXZ_SKILLS_DIR,首次默认同时安装到 ~/.agents/skills 和 ~/.linkwise/skills(Linkwise)。手动安装的目录会登记;未指定目录时同步此前登记的位置。本地修改默认保留,确认替换时再使用 --skill-conflict replace。LXZ_SKILLS_STATE_DIR 可指定安装位置记录目录。
77
+
78
+ 升级运行 `pnpm add -g @tulcn/tshare@latest --allow-build=@tulcn/tshare`;回滚时指定版本,如 `pnpm add -g @tulcn/tshare@<版本> --allow-build=@tulcn/tshare`。使用 --ignore-scripts 时,随后运行该版本的 install skill。Skill 与对应程序版本一同交付。
@@ -0,0 +1,19 @@
1
+ import { skillCommands } from '@tulcn/lxz/skills';
2
+ import { initCommand, identityCommands, registerCommandModules } from '@tulcn/lxz/cli';
3
+ import { identity, clientId, pkg, invoke } from './config.js';
4
+ import { skill } from './skill.js';
5
+ import { features } from './features.js';
6
+ import { serviceCommands } from './service-config.js';
7
+ export const foundationModules = [
8
+ { id: 'authorization', commands: identityCommands(identity, invoke) },
9
+ { id: 'configuration', commands: serviceCommands },
10
+ { id: 'skill', commands: skillCommands(skill, invoke) },
11
+ { id: 'initialization', commands: { init: initCommand(identity, skill, clientId, invoke + ' init') } },
12
+ ];
13
+ export const application = {
14
+ name: "tshare", packageName: pkg.name, version: pkg.version, description: "Commands for tshare",
15
+ commands: registerCommandModules([
16
+ ...foundationModules,
17
+ ...features,
18
+ ]),
19
+ };
@@ -0,0 +1,2 @@
1
+ import { createLxzAuthorization } from '@tulcn/lxz/auth';
2
+ export const identityFor = createLxzAuthorization();
package/dist/config.js ADDED
@@ -0,0 +1,9 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { identityFor } from './authorization.js';
3
+ import { gatewayAddress } from '@tulcn/lxz/auth';
4
+ export const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
5
+ export const clientId = "share";
6
+ export const identity = () => identityFor(clientId);
7
+ export const serviceAddress = () => gatewayAddress(clientId);
8
+ export const transport = "rest-json";
9
+ export const invoke = "tshare";
@@ -0,0 +1,22 @@
1
+ import { CliError, ask, readText } from '@tulcn/lxz/cli';
2
+ export async function field(input, name, label, context, guided) {
3
+ const value = input[name];
4
+ if (typeof value === 'string' && value.trim())
5
+ return value.trim();
6
+ if (guided && context.interactive)
7
+ return (await ask(label, undefined, context.signal)).trim();
8
+ throw new CliError('INVALID_INPUT', `Provide ${label}.`, `Use --${name} to provide ${label}.`);
9
+ }
10
+ export async function content(input, context, guided) {
11
+ if (input.content !== undefined && input.input !== undefined)
12
+ throw new CliError('INVALID_INPUT', 'Both content and a content file were supplied.', 'Choose either --content or --input.');
13
+ if (input.input) {
14
+ const value = await readText(String(input.input), context.signal);
15
+ if (value.trim())
16
+ return value;
17
+ throw new CliError('INVALID_INPUT', 'The content file is empty.', 'Add content to the file and retry.');
18
+ }
19
+ if (typeof input.content === 'string' && input.content.trim())
20
+ return input.content;
21
+ return field(input, 'content', 'content', context, guided);
22
+ }
@@ -0,0 +1,47 @@
1
+ import { CliError, answer, prompts, rowText } from '@tulcn/lxz/cli';
2
+ export const previewParameters = {
3
+ 'dry-run': { type: 'boolean', description: 'Preview the operation without making changes', default: false },
4
+ confirm: { type: 'boolean', description: 'Confirm this operation; business permissions are still required', default: false },
5
+ };
6
+ export const operationResult = {
7
+ type: 'object', required: ['preview', 'summary'],
8
+ properties: { preview: { type: 'boolean' }, summary: { type: 'object' }, result: {} },
9
+ };
10
+ export async function confirm(input, context, summary) {
11
+ context.log(rowText(summary));
12
+ if (input.confirm)
13
+ return;
14
+ if (!context.interactive)
15
+ throw new CliError('INVALID_INPUT', 'This operation has not been confirmed.', 'Preview with --dry-run, then add --confirm to the same command after reviewing it.');
16
+ const accepted = answer(await prompts.confirm({ message: 'Execute the operation shown above?', initialValue: false, signal: context.signal }));
17
+ if (!accepted)
18
+ throw new CliError('CANCELLED', 'Operation cancelled.', 'Run the command again when needed.');
19
+ }
20
+ export function operationCommands(operations) {
21
+ return Object.fromEntries(Object.entries(operations).map(([name, operation]) => [name, {
22
+ description: operation.description, effects: operation.effects, preview: true,
23
+ parameters: { ...operation.parameters, ...(operation.effects === 'remote' ? previewParameters : { 'dry-run': previewParameters['dry-run'] }) },
24
+ result: operationResult, examples: operation.examples,
25
+ format: (value) => {
26
+ const result = value;
27
+ return `${result.preview ? 'Operation preview (not executed)' : 'Operation completed'}\n${rowText(result.summary)}${result.result === undefined ? '' : '\nResult:\n' + rowText(result.result)}`;
28
+ },
29
+ async run(input, context) {
30
+ context.signal.throwIfAborted();
31
+ const prepared = await operation.prepare(input, context);
32
+ if (input['dry-run'])
33
+ return { preview: true, summary: prepared.summary };
34
+ if (operation.effects === 'remote')
35
+ await confirm(input, context, prepared.summary);
36
+ context.signal.throwIfAborted();
37
+ try {
38
+ return { preview: false, summary: prepared.summary, result: await prepared.execute() };
39
+ }
40
+ catch (error) {
41
+ if (operation.effects === 'remote' && error instanceof CliError)
42
+ error.retryable = false;
43
+ throw error;
44
+ }
45
+ },
46
+ }]));
47
+ }
@@ -0,0 +1,34 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { platformRequest, serviceRequest } from '@tulcn/lxz/auth';
3
+ import { CliError, readJson, secureUrl } from '@tulcn/lxz/cli';
4
+ import { serviceOperations } from './service-results.js';
5
+ export function createServiceClient(options) {
6
+ return {
7
+ async invoke(operation, input, signal) {
8
+ const { write, decode } = serviceOperations[operation];
9
+ const url = secureUrl(String(options.baseUrl()), 'Business service URL', { allowHttp: true });
10
+ const rpc = options.transport === 'json-rpc';
11
+ url.pathname = url.pathname.replace(/\/$/, '') + (rpc ? '/rpc' : '/operations/' + encodeURIComponent(operation));
12
+ const id = randomUUID();
13
+ const body = JSON.stringify(rpc ? { jsonrpc: '2.0', id, method: operation, params: input } : input);
14
+ try {
15
+ const response = await serviceRequest(options.identity(), token => platformRequest(url, { method: 'POST', signal, headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json', 'x-request-id': id }, body }, { replay: !write }), signal, { replay: !write });
16
+ const data = await readJson(response);
17
+ if (!rpc)
18
+ return decode(data);
19
+ if (data.jsonrpc !== '2.0' || data.id !== id || !Object.hasOwn(data, 'result') || data.error)
20
+ throw new CliError('UNAVAILABLE', 'The business service returned an invalid protocol response.', 'Ask the maintainer to check CLI and service transport settings.');
21
+ return decode(data.result);
22
+ }
23
+ catch (error) {
24
+ signal.throwIfAborted();
25
+ // A gateway failure already states whether the operation ran; other write failures leave it uncertain.
26
+ if (write && error instanceof CliError && error.details?.executed === undefined) {
27
+ error.retryable = false;
28
+ error.next = 'Check the actual outcome of this operation first. ' + error.next;
29
+ }
30
+ throw error;
31
+ }
32
+ },
33
+ };
34
+ }
@@ -0,0 +1,42 @@
1
+ import { CliError } from '@tulcn/lxz/cli';
2
+ function invalid() {
3
+ throw new CliError('UNAVAILABLE', 'Cannot read the business service result.', 'Ask the CLI maintainer to check the returned fields and matching CLI and service versions.');
4
+ }
5
+ function object(value) {
6
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : invalid();
7
+ }
8
+ function text(value) { return typeof value === 'string' ? value : invalid(); }
9
+ function time(value) { const result = text(value); return Number.isFinite(Date.parse(result)) ? result : invalid(); }
10
+ function count(value) { return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : invalid(); }
11
+ function share(value) {
12
+ const data = object(value);
13
+ return {
14
+ id: text(data.id), name: text(data.name), ...(data.title === undefined ? {} : { title: text(data.title) }),
15
+ bytes: count(data.bytes), uploadedAt: time(data.uploadedAt), latestExpiresAt: time(data.latestExpiresAt),
16
+ };
17
+ }
18
+ function link(value) {
19
+ const data = object(value);
20
+ const url = text(data.url);
21
+ if (!/^https?:\/\//.test(url))
22
+ invalid();
23
+ return {
24
+ ...share(data), url, expiresAt: time(data.expiresAt),
25
+ hours: typeof data.hours === 'number' && data.hours > 0 ? data.hours : invalid(),
26
+ shortened: typeof data.shortened === 'boolean' ? data.shortened : invalid(),
27
+ ...(data.reused === undefined ? {} : { reused: data.reused === true }),
28
+ ...(data.sameName === undefined ? {} : { sameName: Array.isArray(data.sameName) ? data.sameName.map(item => { const entry = object(item); return { id: text(entry.id), uploadedAt: time(entry.uploadedAt) }; }) : invalid() }),
29
+ };
30
+ }
31
+ export const serviceOperations = {
32
+ 'share.create': { write: true, decode: link },
33
+ 'share.renew': { write: true, decode: link },
34
+ 'share.revoke': { write: true, decode(value) {
35
+ const data = object(value);
36
+ return { id: text(data.id), revoked: typeof data.revoked === 'boolean' ? data.revoked : invalid() };
37
+ } },
38
+ 'share.list': { write: false, decode(value) {
39
+ const data = object(value);
40
+ return { items: Array.isArray(data.items) ? data.items.map(share) : invalid() };
41
+ } },
42
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ import { identity, invoke } from './config.js';
2
+ import { shareModule } from './modules/share.js';
3
+ import { shareService } from './services/share.js';
4
+ export const features = [
5
+ { id: 'share', ...shareModule({ guided: false, invoke, service: shareService, signedIn: signal => identity().status(signal).then(Boolean, () => true) }) },
6
+ ];
package/dist/main.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { applyDeployment, runApplication } from '@tulcn/lxz/cli';
3
+ import { application } from './application.js';
4
+ applyDeployment(new URL('../', import.meta.url));
5
+ await runApplication(application);
@@ -0,0 +1,177 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { basename } from 'node:path';
3
+ import { CliError } from '@tulcn/lxz/cli';
4
+ import { field } from '../core/input.js';
5
+ import { operationCommands } from '../core/operations.js';
6
+ export const DEFAULT_HOURS = 24;
7
+ export const MAX_HOURS = 72;
8
+ export const MAX_BYTES = 10 * 1024 * 1024;
9
+ const hoursParameter = {
10
+ type: 'string', default: String(DEFAULT_HOURS), pattern: '^(?:[1-9]|[1-6][0-9]|7[0-2])$',
11
+ description: `Hours the link stays valid (1-${MAX_HOURS}); default ${DEFAULT_HOURS}`,
12
+ };
13
+ const idParameter = { type: 'string', description: 'Share ID returned by share or list' };
14
+ const shanghai = new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false });
15
+ /** Opens the link in the system browser from DingTalk on desktop; mobile DingTalk still uses its built-in browser. */
16
+ export function dingtalkUrl(url) {
17
+ return 'dingtalk://dingtalkclient/page/link?url=' + encodeURIComponent(url) + '&pc_slide=false';
18
+ }
19
+ /** Keeps a title from breaking the Markdown link syntax or formatting. */
20
+ const plain = (value) => value.replace(/[\[\]()*_`#>\\]/g, ' ').replace(/\s+/g, ' ').trim();
21
+ /** Message heading: the title, else the file name without its extension. */
22
+ export function heading(link) {
23
+ return plain(link.title || link.name.replace(/\.html?$/i, '')) || 'HTML 报告';
24
+ }
25
+ /**
26
+ * The DingTalk message: the title links to the report, so the long signed URL never shows in the chat.
27
+ * Kept on one line: dws asks for an extra confirmation that --yes does not cover when the body has a line break.
28
+ */
29
+ export function messageText(title, link, until) {
30
+ return `[${title}](${link}) 有效期至 ${until}(北京时间),过期后无法打开。`;
31
+ }
32
+ const UTF8 = '[Console]::OutputEncoding = [Text.Encoding]::UTF8; ';
33
+ const SEND_RULES = 'Start every PowerShell command that runs dws with ' + UTF8 + 'dws writes UTF-8, and without it Chinese names come out garbled. '
34
+ + 'Before sending anything to DingTalk, show the user a confirmation and wait for their yes: the recipient or group (for the user themself, take userId from dws contact +me instead of looking up a name; otherwise resolve with dws --dry-run and let the user pick when several match), the title, the expiry in Beijing time, and how the message will look (a clickable title, then one line with the expiry). Change the title or hours if the user asks. ';
35
+ /**
36
+ * Adds what the caller sends to DingTalk: the desktop browser link, a ready-to-send Markdown message and how to confirm
37
+ * and send it without retyping the signed URL.
38
+ */
39
+ export function deliverable(link, invoke = 'tshare') {
40
+ const until = shanghai.format(new Date(link.expiresAt));
41
+ const desktop = dingtalkUrl(link.url);
42
+ return {
43
+ ...link,
44
+ dingtalkUrl: desktop,
45
+ message: messageText(heading(link), desktop, until),
46
+ next: 'Never retype message or url: a single wrong character breaks the signed link. '
47
+ + 'If the user did not name who to send it to, reply with the Markdown link [title](url) using url (not dingtalkUrl) and the expiry in Beijing time, then ask whether to send it to DingTalk and to whom; do not send on your own. '
48
+ + SEND_RULES
49
+ + `After the user confirms, send this share in one PowerShell command so message passes through a variable: ${UTF8}$r = ${invoke} renew --id ${link.id} --hours <hours> --confirm --non-interactive --json | ConvertFrom-Json; if ($r.ok) { dws chat +dm --to <name> --text $r.data.result.message --yes } else { $r.error } `
50
+ + '(to the user themself use dws chat +messages-send --as user --user <userId> --markdown $r.data.result.message --yes; to a group use dws chat +send-to-group --group <group> --text). Do not add 2>&1: stdout is the JSON, stderr is a human-readable summary.'
51
+ + (link.sameName?.length ? ' Earlier shares with the same file name but different content are listed in sameName and their links still work; ask the user whether to revoke them.' : ''),
52
+ };
53
+ }
54
+ /** Longest title or reference value looked at; bounds the regex work on malformed HTML. */
55
+ const SCAN_LIMIT = 2048;
56
+ /**
57
+ * Reads the HTML <title>, used as the message title when --title is not given.
58
+ * Every pattern stops at the next "<", so many unclosed <title tags cost linear time instead of hanging prepare.
59
+ */
60
+ export function htmlTitle(html) {
61
+ const open = /<title\b[^<>]*>/i.exec(html);
62
+ if (!open)
63
+ return undefined;
64
+ const rest = html.slice(open.index + open[0].length);
65
+ const end = rest.search(/<\/title\s*>/i);
66
+ if (end < 0)
67
+ return undefined;
68
+ const text = rest.slice(0, Math.min(end, SCAN_LIMIT * 2)).replace(/<[^<>]*>/g, '').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/\s+/g, ' ').trim();
69
+ return text ? text.slice(0, 200) : undefined;
70
+ }
71
+ /**
72
+ * Finds src/href/url() references that point at local files, which will not load from the shared link.
73
+ * Values are capped at SCAN_LIMIT and an unquoted url( value stops at the next parenthesis, so a run of unclosed "url("
74
+ * costs linear time (before: quadratic, about 10 hours for a 10 MiB file).
75
+ */
76
+ export function localReferences(html) {
77
+ const found = new Set();
78
+ const remote = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#|\{\{|\$\{)/i;
79
+ const pattern = new RegExp(`\\b(?:src|href|poster)\\s*=\\s*(["'])(.{0,${SCAN_LIMIT}}?)\\1|url\\(\\s*(["']?)([^"'()]{1,${SCAN_LIMIT}})\\3\\s*\\)`, 'gis');
80
+ for (const match of html.matchAll(pattern)) {
81
+ const value = (match[2] ?? match[4] ?? '').trim();
82
+ if (value && !remote.test(value))
83
+ found.add(value);
84
+ if (found.size >= 20)
85
+ break;
86
+ }
87
+ return [...found];
88
+ }
89
+ async function htmlFile(path, signal) {
90
+ if (!/\.html?$/i.test(path)) {
91
+ throw new CliError('INVALID_INPUT', 'tshare only shares HTML reports (.html or .htm); PDF, Word, Excel, images and other files are not supported.', 'Tell the user this file type cannot be shared. Do not convert the file to HTML on your own; only if the user asks, build a new HTML report from its content and share that.');
92
+ }
93
+ let content;
94
+ try {
95
+ const info = await stat(path);
96
+ if (!info.isFile())
97
+ throw new Error('not a file');
98
+ if (info.size > MAX_BYTES)
99
+ throw new CliError('INVALID_INPUT', `The HTML file exceeds ${MAX_BYTES / 1024 / 1024} MiB.`, 'Compress or resize embedded images and retry.');
100
+ content = await readFile(path, { signal });
101
+ }
102
+ catch (error) {
103
+ signal.throwIfAborted();
104
+ if (error instanceof CliError)
105
+ throw error;
106
+ throw new CliError('IO_ERROR', 'Cannot read the HTML file.', 'Check the file path and read permissions.');
107
+ }
108
+ if (!content.length)
109
+ throw new CliError('INVALID_INPUT', 'The HTML file is empty.', 'Generate the report again and retry.');
110
+ return { name: basename(path), content };
111
+ }
112
+ /** signedIn reports whether this CLI is authorized, so a preview can ask for authorization before the confirmation. */
113
+ export function shareModule(options) {
114
+ const operations = {
115
+ share: {
116
+ description: 'Upload a local HTML file and create a public link that expires', effects: 'remote',
117
+ parameters: {
118
+ file: { type: 'string', description: 'Local .html or .htm file to share' },
119
+ hours: hoursParameter,
120
+ title: { type: 'string', description: 'Title shown in the generated message; defaults to the HTML <title>, then the file name' },
121
+ },
122
+ examples: [options.invoke + ' share --file ./report.html --dry-run', options.invoke + ' share --file ./report.html --hours 48 --title Weekly-report --confirm'],
123
+ async prepare(input, context) {
124
+ const path = await field(input, 'file', 'HTML file path', context, options.guided);
125
+ const file = await htmlFile(path, context.signal);
126
+ const hours = Number(input.hours ?? DEFAULT_HOURS);
127
+ const html = file.content.toString('utf8');
128
+ const title = typeof input.title === 'string' && input.title.trim() ? input.title.trim() : htmlTitle(html);
129
+ const references = localReferences(html);
130
+ const summary = {
131
+ action: 'Publish HTML as a public link; anyone with the link can open it until it expires',
132
+ file: path, bytes: file.content.length, hours, maxHours: MAX_HOURS, ...(title ? { title } : {}),
133
+ ...(references.length ? { localReferences: references, warning: 'These local files will not load from the link; embed images as data: URLs first' } : {}),
134
+ messagePreview: messageText(heading({ title, name: file.name }), '<link created when shared>', shanghai.format(new Date(Date.now() + hours * 3600000))),
135
+ beforeSending: SEND_RULES + 'If the user did not name a recipient, share first, then show the link and ask whether to send it.',
136
+ };
137
+ // Sharing needs authorization; asking for it now keeps it from interrupting the user after they confirm.
138
+ if (input['dry-run'] && options.signedIn && !await options.signedIn(context.signal)) {
139
+ summary.authorized = false;
140
+ summary.next = `This CLI is not authorized yet. Authorize first, before showing the user any confirmation: run ${options.invoke} init --device-login --non-interactive --json and follow its next; once approved, continue with the confirmation and the share.`;
141
+ }
142
+ return { summary, execute: async () => deliverable(await options.service.create({ ...file, hours, ...(title ? { title } : {}) }, context.signal), options.invoke) };
143
+ },
144
+ },
145
+ renew: {
146
+ description: `Create a new link for a shared file, within ${MAX_HOURS} hours of its upload`, effects: 'remote',
147
+ parameters: { id: idParameter, hours: hoursParameter },
148
+ examples: [options.invoke + ' renew --id <id> --hours 48 --confirm'],
149
+ async prepare(input, context) {
150
+ const id = await field(input, 'id', 'Share ID', context, options.guided);
151
+ const hours = Number(input.hours ?? DEFAULT_HOURS);
152
+ return {
153
+ summary: { action: 'Create a new public link; earlier links keep working until they expire', id, hours },
154
+ execute: async () => deliverable(await options.service.renew(id, hours, context.signal), options.invoke),
155
+ };
156
+ },
157
+ },
158
+ revoke: {
159
+ description: 'Delete a shared file so all of its links stop working', effects: 'remote',
160
+ parameters: { id: idParameter },
161
+ examples: [options.invoke + ' revoke --id <id> --confirm'],
162
+ async prepare(input, context) {
163
+ const id = await field(input, 'id', 'Share ID', context, options.guided);
164
+ return { summary: { action: 'Delete the shared file; every link to it stops working', id }, execute: () => options.service.revoke(id, context.signal) };
165
+ },
166
+ },
167
+ };
168
+ return { operations, commands: {
169
+ ...operationCommands(operations),
170
+ list: {
171
+ description: 'List your shared files that can still get links', effects: 'none',
172
+ result: { type: 'object', required: ['items'], properties: { items: { type: 'array', items: { type: 'object' } } } },
173
+ examples: [options.invoke + ' list'],
174
+ async run(_input, context) { return options.service.list(context.signal); },
175
+ },
176
+ } };
177
+ }
@@ -0,0 +1,9 @@
1
+ import { clientId, invoke, serviceAddress } from './config.js';
2
+ export const serviceCommands = {
3
+ 'config service': {
4
+ description: 'Show the platform gateway URL for this CLI and authorization environment', effects: 'none',
5
+ result: { type: 'object', properties: { serviceUrl: { type: 'string' }, clientId: { type: 'string' } }, required: ['serviceUrl', 'clientId'] },
6
+ examples: [invoke + ' config service'],
7
+ async run() { return { serviceUrl: serviceAddress(), clientId }; },
8
+ },
9
+ };
@@ -0,0 +1,3 @@
1
+ import { createServiceClient } from '../core/service-client.js';
2
+ import { identity, serviceAddress, transport } from '../config.js';
3
+ export const { invoke } = createServiceClient({ identity, baseUrl: serviceAddress, transport });
@@ -0,0 +1,7 @@
1
+ import { invoke } from './http.js';
2
+ export const shareService = {
3
+ create: ({ name, content, hours, title }, signal) => invoke('share.create', { name, content: Buffer.from(content).toString('base64'), hours, ...(title ? { title } : {}) }, signal),
4
+ renew: (id, hours, signal) => invoke('share.renew', { id, hours }, signal),
5
+ revoke: (id, signal) => invoke('share.revoke', { id }, signal),
6
+ list: signal => invoke('share.list', {}, signal),
7
+ };
package/dist/skill.js ADDED
@@ -0,0 +1,2 @@
1
+ import { createLxzSkill } from '@tulcn/lxz/skills';
2
+ export const skill = createLxzSkill(new URL('../', import.meta.url), "tshare");
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@tulcn/tshare",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.3",
4
+ "description": "Share HTML reports as expiring links",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "bin": {
8
+ "tshare": "dist/main.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "skills",
13
+ "scripts"
14
+ ],
15
+ "engines": {
16
+ "node": ">=22.12.0"
17
+ },
18
+ "dependencies": {
19
+ "@tulcn/lxz": "~0.3.1"
20
+ },
21
+ "lianxz": {
22
+ "contractVersion": "1.0.0",
23
+ "generatorVersion": "0.1.5"
24
+ },
25
+ "scripts": {
26
+ "postinstall": "node scripts/install.mjs"
27
+ }
6
28
  }
@@ -0,0 +1,17 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ if (process.env.LXZ_SKIP_SKILLS !== '1') {
6
+ const root = new URL('../', import.meta.url);
7
+ const pkg = JSON.parse(readFileSync(new URL('package.json', root), 'utf8'));
8
+ const [name, entry] = Object.entries(pkg.bin)[0];
9
+ const result = spawnSync(process.execPath, [fileURLToPath(new URL(entry, root)), 'install', 'skill', '--non-interactive'], {
10
+ stdio: 'inherit', windowsHide: true, timeout: 120000,
11
+ });
12
+ if (result.error || result.status !== 0) {
13
+ console.error(`${name} Agent Skill installation is incomplete.`);
14
+ console.error(`Resolve the error above, then run ${name} install skill --skills-dir <writable-directory>. Set LXZ_SKIP_SKILLS=1 to skip the package install hook.`);
15
+ process.exitCode = result.status || 1;
16
+ }
17
+ }