@swipt/cli 0.1.0-nightly.94 → 0.1.0-nightly.98
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/dist/cli/cli.js +1 -1
- package/dist/cli/cli.js.map +1 -1
- package/dist/cli/commands/data/read.js +4 -6
- package/dist/cli/commands/data/read.js.map +1 -1
- package/dist/cli/commands/device/stop.js +3 -3
- package/dist/cli/commands/device/stop.js.map +1 -1
- package/dist/cli/commands/driver/driver.js +28 -0
- package/dist/cli/commands/driver/driver.js.map +1 -0
- package/dist/cli/commands/driver/index.js +1 -0
- package/dist/cli/commands/flags.js +8 -7
- package/dist/cli/commands/flags.js.map +1 -1
- package/dist/cli/commands/index.js +3 -0
- package/dist/cli/commands/index.js.map +1 -1
- package/dist/cli/commands/project/create.js +2 -2
- package/dist/cli/commands/project/create.js.map +1 -1
- package/dist/cli/commands/project/source.js +10 -9
- package/dist/cli/commands/project/source.js.map +1 -1
- package/dist/cli/commands/swiplet/remove.js +1 -1
- package/dist/cli/commands/swiplet/remove.js.map +1 -1
- package/dist/client.js +27 -6
- package/dist/client.js.map +1 -1
- package/dist/connection.d.ts +3 -1
- package/dist/connection.js +41 -52
- package/dist/connection.js.map +1 -1
- package/dist/directories.d.ts +2 -0
- package/dist/directories.js +9 -0
- package/dist/directories.js.map +1 -0
- package/dist/driver.d.ts +39 -0
- package/dist/driver.js +199 -0
- package/dist/driver.js.map +1 -0
- package/dist/i18n.d.ts +1 -1
- package/dist/i18n.js +43 -7
- package/dist/i18n.js.map +1 -1
- package/dist/mdns.d.ts +7 -0
- package/dist/mdns.js +44 -0
- package/dist/mdns.js.map +1 -0
- package/dist/output.js +6 -6
- package/dist/output.js.map +1 -1
- package/dist/passcode.d.ts +9 -0
- package/dist/passcode.js +81 -0
- package/dist/passcode.js.map +1 -0
- package/dist/project.js +38 -32
- package/dist/project.js.map +1 -1
- package/dist/serve.d.ts +1 -0
- package/dist/serve.js +124 -0
- package/dist/serve.js.map +1 -0
- package/dist/sideload.d.ts +0 -1
- package/dist/sideload.js +82 -340
- package/dist/sideload.js.map +1 -1
- package/dist/swipt-app.d.ts +14 -0
- package/dist/swipt-app.js +51 -0
- package/dist/swipt-app.js.map +1 -0
- package/locales/ar.json +52 -28
- package/locales/bg.json +58 -34
- package/locales/bn.json +49 -25
- package/locales/ca.json +55 -31
- package/locales/cs.json +55 -31
- package/locales/da.json +50 -26
- package/locales/de.json +50 -26
- package/locales/el.json +60 -36
- package/locales/es-419.json +51 -27
- package/locales/es.json +51 -27
- package/locales/fi.json +51 -27
- package/locales/fr-CA.json +53 -29
- package/locales/fr.json +56 -32
- package/locales/gu.json +69 -45
- package/locales/he.json +51 -27
- package/locales/hi.json +50 -26
- package/locales/hr.json +51 -27
- package/locales/hu.json +62 -38
- package/locales/id.json +50 -26
- package/locales/it.json +69 -45
- package/locales/ja.json +50 -26
- package/locales/kk.json +49 -25
- package/locales/kn.json +49 -25
- package/locales/ko.json +79 -55
- package/locales/lt.json +50 -26
- package/locales/ml.json +49 -25
- package/locales/mr.json +56 -32
- package/locales/ms.json +50 -26
- package/locales/nb.json +50 -26
- package/locales/nl.json +56 -32
- package/locales/or.json +50 -26
- package/locales/pa.json +49 -25
- package/locales/pl.json +68 -44
- package/locales/pt-BR.json +51 -27
- package/locales/pt-PT.json +52 -28
- package/locales/ro.json +52 -28
- package/locales/ru.json +54 -30
- package/locales/sk.json +80 -56
- package/locales/sl.json +50 -26
- package/locales/sv.json +52 -28
- package/locales/ta.json +49 -25
- package/locales/te.json +49 -25
- package/locales/th.json +54 -30
- package/locales/tr.json +50 -26
- package/locales/uk.json +53 -29
- package/locales/ur.json +49 -25
- package/locales/vi.json +49 -25
- package/locales/zh-HK.json +54 -30
- package/locales/zh-Hans.json +54 -30
- package/locales/zh-Hant.json +60 -36
- package/package.json +13 -4
- package/dist/coredevice.d.ts +0 -22
- package/dist/coredevice.js +0 -329
- package/dist/coredevice.js.map +0 -1
package/dist/cli/cli.js
CHANGED
|
@@ -147,7 +147,7 @@ function printError(error, target, operation) {
|
|
|
147
147
|
});
|
|
148
148
|
break;
|
|
149
149
|
case Code.Unauthenticated:
|
|
150
|
-
message = tr("{message}; connect with the URL
|
|
150
|
+
message = tr("{message}; connect with the URL that Swipt › Developer or \"swipt driver\" shows: swipt device add {url}", {
|
|
151
151
|
message,
|
|
152
152
|
url: withToken(target.url)
|
|
153
153
|
});
|
package/dist/cli/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":["connection.withToken"],"sources":["../../src/cli/cli.ts"],"sourcesContent":["import { parseArgs } from \"node:util\";\n\nimport { Code, RpcError, UsageError } from \"../client\";\nimport * as connection from \"../connection\";\nimport { tr } from \"../i18n\";\nimport { FalseResult } from \"../output\";\nimport type { Command, Options } from \"./command\";\nimport { root } from \"./commands\";\n\nconst globalOptions: Options = {\n help: { type: \"boolean\", short: \"h\", help: tr(\"help\") },\n};\n\nconst parseOptions = (options: Options) =>\n Object.fromEntries(\n Object.entries(options ?? {}).map(([name, option]) => [\n name,\n { type: option.type, ...(option.short ? { short: option.short } : {}) },\n ]),\n );\n\nfunction allOptions(command: Command, collected = {}) {\n Object.assign(collected, parseOptions(command.options));\n for (const child of command.commands ?? []) {\n allOptions(child, collected);\n }\n return collected;\n}\n\nfunction usage(trail: Command[]) {\n const command = trail.at(-1);\n const name = trail.map((it) => it.name).join(\" \");\n const lines = [command.short, \"\"];\n if (command.commands) {\n lines.push(\n tr(\"usage: {usage}\", { usage: `${name} COMMAND` }),\n \"\",\n tr(\"commands:\"),\n );\n lines.push(\n ...columns(\n command.commands.map((child) => [\n ` ${child.use ?? child.name}`,\n child.short,\n ]),\n ).split(\"\\n\"),\n );\n } else {\n lines.push(\n tr(\"usage: {usage}\", {\n usage: `${trail\n .slice(0, -1)\n .map((it) => it.name)\n .join(\" \")} ${command.use ?? command.name}`.replace(/ +/g, \" \"),\n }),\n );\n }\n if (command.description) {\n lines.push(\"\", ...command.description);\n }\n const options: Options = {\n ...trail.reduce((found, it) => ({ ...found, ...it.options }), {}),\n ...globalOptions,\n };\n lines.push(\"\", tr(\"options:\"));\n lines.push(\n ...columns(\n Object.entries(options).map(([option, it]) => [\n ` ${it.short ? `-${it.short}, ` : \"\"}--${option}${it.value ? ` ${it.value}` : \"\"}`,\n it.help,\n ]),\n ).split(\"\\n\"),\n );\n return lines.join(\"\\n\");\n}\n\nfunction columns(rows) {\n const width = Math.max(...rows.map((row) => row[0].length));\n return rows.map((row) => `${row[0].padEnd(width + 2)}${row[1]}`).join(\"\\n\");\n}\n\nfunction resolve(argv) {\n const loose = parseArgs({\n args: argv,\n options: { ...parseOptions(globalOptions), ...allOptions(root) },\n allowPositionals: true,\n strict: false,\n tokens: true,\n });\n const positionals = loose.tokens.filter(\n (token) => token.kind === \"positional\",\n );\n const trail = [root];\n let consumed = 0;\n let help = positionals[0]?.value === \"help\";\n if (help) {\n consumed++;\n }\n while (trail.at(-1).commands) {\n const current = trail.at(-1);\n const word = positionals[consumed]?.value;\n if (word === undefined) {\n if (help || loose.values.help || current !== root || argv.length === 0) {\n return { trail, help: true };\n }\n throw new UsageError(tr(\"A command is missing.\"));\n }\n const found = current.commands.find((it) => it.name === word);\n if (!found) {\n throw new UsageError(\n tr(\"unknown command {name} for {parent}\", {\n name: JSON.stringify(word),\n parent: JSON.stringify(trail.map((it) => it.name).join(\" \")),\n }),\n );\n }\n trail.push(found);\n consumed++;\n }\n const command = trail.at(-1);\n const options: Options = trail.reduce(\n (found, it) => ({ ...found, ...it.options }),\n {},\n );\n const first = positionals[consumed];\n const verbatim =\n first !== undefined && command.passthrough?.(first.value)\n ? first.index + 1\n : argv.length;\n let parsed;\n try {\n parsed = parseArgs({\n args: argv.slice(0, verbatim),\n options: { ...parseOptions(globalOptions), ...parseOptions(options) },\n allowPositionals: true,\n strict: true,\n });\n } catch (error) {\n const option = error.message.match(/^Unknown option '(-[^']*)'/)?.[1];\n throw new UsageError(\n option === undefined\n ? error.message\n : tr(\"{option} isn't an option of {command}.\", {\n option,\n command: JSON.stringify(trail.map((it) => it.name).join(\" \")),\n }),\n );\n }\n if (parsed.values.help) {\n help = true;\n }\n const args = [...parsed.positionals.slice(consumed), ...argv.slice(verbatim)];\n if (\n !help &&\n (args.length < command.args[0] || args.length > command.args[1])\n ) {\n const [least, most] = command.args;\n throw new UsageError(\n least === most\n ? tr(\n {\n one: \"accepts {count} arg, received {received}\",\n other: \"accepts {count} args, received {received}\",\n },\n {\n count: least,\n received: args.length,\n },\n )\n : most === Infinity\n ? tr(\n {\n one: \"accepts at least {count} arg, received {received}\",\n other: \"accepts at least {count} args, received {received}\",\n },\n {\n count: least,\n received: args.length,\n },\n )\n : tr(\n {\n one: \"accepts between {least} and {count} arg, received {received}\",\n other:\n \"accepts between {least} and {count} args, received {received}\",\n },\n { least, count: most, received: args.length },\n ),\n );\n }\n return { trail, help, args, values: parsed.values };\n}\n\nfunction printError(error, target, operation?) {\n let exit = 1;\n let message = error.message;\n if (error instanceof UsageError) {\n exit = 2;\n } else if (error instanceof RpcError) {\n switch (error.code) {\n case Code.Unavailable:\n exit = 5;\n message = tr(\"Swipt at {url} is unreachable: {message}\", {\n url: target.url,\n message,\n });\n break;\n case Code.Unauthenticated:\n message = tr(\n \"{message}; connect with the URL from Swipt › Developer: swipt device add {url}\",\n { message, url: connection.withToken(target.url) },\n );\n break;\n case Code.Unimplemented:\n message = tr(\n \"Swipt at {url} doesn't have this command; update Swipt.\",\n { url: target.url },\n );\n break;\n }\n }\n console.error(\n tr(\"error: {message}\", {\n message: operation === undefined ? message : `${operation}: ${message}`,\n }),\n );\n if (exit === 2) {\n console.error(tr('Run \"swipt help\" for usage.'));\n }\n return exit;\n}\n\nexport async function main() {\n const interrupt = new AbortController();\n const interrupted = () => interrupt.abort();\n process.once(\"SIGINT\", interrupted);\n process.once(\"SIGTERM\", interrupted);\n const target = { url: \"\" };\n try {\n const resolved = resolve(process.argv.slice(2));\n if (resolved.help) {\n console.log(usage(resolved.trail));\n return;\n }\n const command = resolved.trail.at(-1);\n const values = command.parse\n ? command.parse(resolved.values)\n : resolved.values;\n await command.run({\n args: resolved.args,\n options: values,\n target,\n signal: interrupt.signal,\n printError: (error, operation) => printError(error, target, operation),\n });\n } catch (error) {\n if (error instanceof FalseResult) {\n process.exitCode = 1;\n } else if (interrupt.signal.aborted || error.name === \"ExitPromptError\") {\n process.exitCode = 130;\n } else {\n process.exitCode = printError(error, target);\n }\n } finally {\n process.off(\"SIGINT\", interrupted);\n process.off(\"SIGTERM\", interrupted);\n }\n}\n"],"mappings":";;;;;;;AASA,MAAM,gBAAyB,EAC7B,MAAM;CAAE,MAAM;CAAW,OAAO;CAAK,MAAM,GAAG,MAAM;AAAE,EACxD;AAEA,MAAM,gBAAgB,YACpB,OAAO,YACL,OAAO,QAAQ,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,YAAY,CACpD,MACA;CAAE,MAAM,OAAO;CAAM,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;AAAG,CACxE,CAAC,CACH;AAEF,SAAS,WAAW,SAAkB,YAAY,CAAC,GAAG;CACpD,OAAO,OAAO,WAAW,aAAa,QAAQ,OAAO,CAAC;CACtD,KAAK,MAAM,SAAS,QAAQ,YAAY,CAAC,GACvC,WAAW,OAAO,SAAS;CAE7B,OAAO;AACT;AAEA,SAAS,MAAM,OAAkB;CAC/B,MAAM,UAAU,MAAM,GAAG,EAAE;CAC3B,MAAM,OAAO,MAAM,KAAK,OAAO,GAAG,IAAI,CAAC,CAAC,KAAK,GAAG;CAChD,MAAM,QAAQ,CAAC,QAAQ,OAAO,EAAE;CAChC,IAAI,QAAQ,UAAU;EACpB,MAAM,KACJ,GAAG,kBAAkB,EAAE,OAAO,GAAG,KAAK,UAAU,CAAC,GACjD,IACA,GAAG,WAAW,CAChB;EACA,MAAM,KACJ,GAAG,QACD,QAAQ,SAAS,KAAK,UAAU,CAC9B,KAAK,M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QAAQ,MACN,GAAG,oBAAoB,EACrB,SAAS,cAAc,KAAA,IAAY,UAAU,GAAG,UAAU,IAAI,UAChE,CAAC,CACH;CACA,IAAI,SAAS,GACX,QAAQ,MAAM,GAAG,+BAA6B,CAAC;CAEjD,OAAO;AACT;AAEA,eAAsB,OAAO;CAC3B,MAAM,YAAY,IAAI,gBAAgB;CACtC,MAAM,oBAAoB,UAAU,MAAM;CAC1C,QAAQ,KAAK,UAAU,WAAW;CAClC,QAAQ,KAAK,WAAW,WAAW;CACnC,MAAM,SAAS,EAAE,KAAK,GAAG;CACzB,IAAI;EACF,MAAM,WAAW,QAAQ,QAAQ,KAAK,MAAM,CAAC,CAAC;EAC9C,IAAI,SAAS,MAAM;GACjB,QAAQ,IAAI,MAAM,SAAS,KAAK,CAAC;GACjC;EACF;EACA,MAAM,UAAU,SAAS,MAAM,GAAG,EAAE;EACpC,MAAM,SAAS,QAAQ,QACnB,QAAQ,MAAM,SAAS,MAAM,IAC7B,SAAS;EACb,MAAM,QAAQ,IAAI;GAChB,MAAM,SAAS;GACf,SAAS;GACT;GACA,QAAQ,UAAU;GAClB,aAAa,OAAO,cAAc,WAAW,OAAO,QAAQ,SAAS;EACvE,CAAC;CACH,SAAS,OAAO;EACd,IAAI,iBAAiB,aACnB,QAAQ,WAAW;OACd,IAAI,UAAU,OAAO,WAAW,MAAM,SAAS,mBACpD,QAAQ,WAAW;OAEnB,QAAQ,WAAW,WAAW,OAAO,MAAM;CAE/C,UAAU;EACR,QAAQ,IAAI,UAAU,WAAW;EACjC,QAAQ,IAAI,WAAW,WAAW;CACpC;AACF"}
|
|
1
|
+
{"version":3,"file":"cli.js","names":["connection.withToken"],"sources":["../../src/cli/cli.ts"],"sourcesContent":["import { parseArgs } from \"node:util\";\n\nimport { Code, RpcError, UsageError } from \"../client\";\nimport * as connection from \"../connection\";\nimport { tr } from \"../i18n\";\nimport { FalseResult } from \"../output\";\nimport type { Command, Options } from \"./command\";\nimport { root } from \"./commands\";\n\nconst globalOptions: Options = {\n help: { type: \"boolean\", short: \"h\", help: tr(\"help\") },\n};\n\nconst parseOptions = (options: Options) =>\n Object.fromEntries(\n Object.entries(options ?? {}).map(([name, option]) => [\n name,\n { type: option.type, ...(option.short ? { short: option.short } : {}) },\n ]),\n );\n\nfunction allOptions(command: Command, collected = {}) {\n Object.assign(collected, parseOptions(command.options));\n for (const child of command.commands ?? []) {\n allOptions(child, collected);\n }\n return collected;\n}\n\nfunction usage(trail: Command[]) {\n const command = trail.at(-1);\n const name = trail.map((it) => it.name).join(\" \");\n const lines = [command.short, \"\"];\n if (command.commands) {\n lines.push(\n tr(\"usage: {usage}\", { usage: `${name} COMMAND` }),\n \"\",\n tr(\"commands:\"),\n );\n lines.push(\n ...columns(\n command.commands.map((child) => [\n ` ${child.use ?? child.name}`,\n child.short,\n ]),\n ).split(\"\\n\"),\n );\n } else {\n lines.push(\n tr(\"usage: {usage}\", {\n usage: `${trail\n .slice(0, -1)\n .map((it) => it.name)\n .join(\" \")} ${command.use ?? command.name}`.replace(/ +/g, \" \"),\n }),\n );\n }\n if (command.description) {\n lines.push(\"\", ...command.description);\n }\n const options: Options = {\n ...trail.reduce((found, it) => ({ ...found, ...it.options }), {}),\n ...globalOptions,\n };\n lines.push(\"\", tr(\"options:\"));\n lines.push(\n ...columns(\n Object.entries(options).map(([option, it]) => [\n ` ${it.short ? `-${it.short}, ` : \"\"}--${option}${it.value ? ` ${it.value}` : \"\"}`,\n it.help,\n ]),\n ).split(\"\\n\"),\n );\n return lines.join(\"\\n\");\n}\n\nfunction columns(rows) {\n const width = Math.max(...rows.map((row) => row[0].length));\n return rows.map((row) => `${row[0].padEnd(width + 2)}${row[1]}`).join(\"\\n\");\n}\n\nfunction resolve(argv) {\n const loose = parseArgs({\n args: argv,\n options: { ...parseOptions(globalOptions), ...allOptions(root) },\n allowPositionals: true,\n strict: false,\n tokens: true,\n });\n const positionals = loose.tokens.filter(\n (token) => token.kind === \"positional\",\n );\n const trail = [root];\n let consumed = 0;\n let help = positionals[0]?.value === \"help\";\n if (help) {\n consumed++;\n }\n while (trail.at(-1).commands) {\n const current = trail.at(-1);\n const word = positionals[consumed]?.value;\n if (word === undefined) {\n if (help || loose.values.help || current !== root || argv.length === 0) {\n return { trail, help: true };\n }\n throw new UsageError(tr(\"A command is missing.\"));\n }\n const found = current.commands.find((it) => it.name === word);\n if (!found) {\n throw new UsageError(\n tr(\"unknown command {name} for {parent}\", {\n name: JSON.stringify(word),\n parent: JSON.stringify(trail.map((it) => it.name).join(\" \")),\n }),\n );\n }\n trail.push(found);\n consumed++;\n }\n const command = trail.at(-1);\n const options: Options = trail.reduce(\n (found, it) => ({ ...found, ...it.options }),\n {},\n );\n const first = positionals[consumed];\n const verbatim =\n first !== undefined && command.passthrough?.(first.value)\n ? first.index + 1\n : argv.length;\n let parsed;\n try {\n parsed = parseArgs({\n args: argv.slice(0, verbatim),\n options: { ...parseOptions(globalOptions), ...parseOptions(options) },\n allowPositionals: true,\n strict: true,\n });\n } catch (error) {\n const option = error.message.match(/^Unknown option '(-[^']*)'/)?.[1];\n throw new UsageError(\n option === undefined\n ? error.message\n : tr(\"{option} isn't an option of {command}.\", {\n option,\n command: JSON.stringify(trail.map((it) => it.name).join(\" \")),\n }),\n );\n }\n if (parsed.values.help) {\n help = true;\n }\n const args = [...parsed.positionals.slice(consumed), ...argv.slice(verbatim)];\n if (\n !help &&\n (args.length < command.args[0] || args.length > command.args[1])\n ) {\n const [least, most] = command.args;\n throw new UsageError(\n least === most\n ? tr(\n {\n one: \"accepts {count} arg, received {received}\",\n other: \"accepts {count} args, received {received}\",\n },\n {\n count: least,\n received: args.length,\n },\n )\n : most === Infinity\n ? tr(\n {\n one: \"accepts at least {count} arg, received {received}\",\n other: \"accepts at least {count} args, received {received}\",\n },\n {\n count: least,\n received: args.length,\n },\n )\n : tr(\n {\n one: \"accepts between {least} and {count} arg, received {received}\",\n other:\n \"accepts between {least} and {count} args, received {received}\",\n },\n { least, count: most, received: args.length },\n ),\n );\n }\n return { trail, help, args, values: parsed.values };\n}\n\nfunction printError(error, target, operation?) {\n let exit = 1;\n let message = error.message;\n if (error instanceof UsageError) {\n exit = 2;\n } else if (error instanceof RpcError) {\n switch (error.code) {\n case Code.Unavailable:\n exit = 5;\n message = tr(\"Swipt at {url} is unreachable: {message}\", {\n url: target.url,\n message,\n });\n break;\n case Code.Unauthenticated:\n message = tr(\n '{message}; connect with the URL that Swipt › Developer or \"swipt driver\" shows: swipt device add {url}',\n { message, url: connection.withToken(target.url) },\n );\n break;\n case Code.Unimplemented:\n message = tr(\n \"Swipt at {url} doesn't have this command; update Swipt.\",\n { url: target.url },\n );\n break;\n }\n }\n console.error(\n tr(\"error: {message}\", {\n message: operation === undefined ? message : `${operation}: ${message}`,\n }),\n );\n if (exit === 2) {\n console.error(tr('Run \"swipt help\" for usage.'));\n }\n return exit;\n}\n\nexport async function main() {\n const interrupt = new AbortController();\n const interrupted = () => interrupt.abort();\n process.once(\"SIGINT\", interrupted);\n process.once(\"SIGTERM\", interrupted);\n const target = { url: \"\" };\n try {\n const resolved = resolve(process.argv.slice(2));\n if (resolved.help) {\n console.log(usage(resolved.trail));\n return;\n }\n const command = resolved.trail.at(-1);\n const values = command.parse\n ? command.parse(resolved.values)\n : resolved.values;\n await command.run({\n args: resolved.args,\n options: values,\n target,\n signal: interrupt.signal,\n printError: (error, operation) => printError(error, target, operation),\n });\n } catch (error) {\n if (error instanceof FalseResult) {\n process.exitCode = 1;\n } else if (interrupt.signal.aborted || error.name === \"ExitPromptError\") {\n process.exitCode = 130;\n } else {\n process.exitCode = printError(error, target);\n }\n } finally {\n process.off(\"SIGINT\", interrupted);\n process.off(\"SIGTERM\", interrupted);\n }\n}\n"],"mappings":";;;;;;;AASA,MAAM,gBAAyB,EAC7B,MAAM;CAAE,MAAM;CAAW,OAAO;CAAK,MAAM,GAAG,MAAM;AAAE,EACxD;AAEA,MAAM,gBAAgB,YACpB,OAAO,YACL,OAAO,QAAQ,WAAW,CAAC,CAAC,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AG,EAAE;EACpC,MAAM,SAAS,QAAQ,QACnB,QAAQ,MAAM,SAAS,MAAM,IAC7B,SAAS;EACb,MAAM,QAAQ,IAAI;GAChB,MAAM,SAAS;GACf,SAAS;GACT;GACA,QAAQ,UAAU;GAClB,aAAa,OAAO,cAAc,WAAW,OAAO,QAAQ,SAAS;EACvE,CAAC;CACH,SAAS,OAAO;EACd,IAAI,iBAAiB,aACnB,QAAQ,WAAW;OACd,IAAI,UAAU,OAAO,WAAW,MAAM,SAAS,mBACpD,QAAQ,WAAW;OAEnB,QAAQ,WAAW,WAAW,OAAO,MAAM;CAE/C,UAAU;EACR,QAAQ,IAAI,UAAU,WAAW;EACjC,QAAQ,IAAI,WAAW,WAAW;CACpC;AACF"}
|
|
@@ -6,10 +6,6 @@ import { operandCount } from "./operand.js";
|
|
|
6
6
|
import fs from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
// src/cli/commands/data/read.ts
|
|
9
|
-
const isLocal = (name) => {
|
|
10
|
-
const normalized = path.posix.normalize(name);
|
|
11
|
-
return !path.posix.isAbsolute(normalized) && normalized !== ".." && !normalized.startsWith("../");
|
|
12
|
-
};
|
|
13
9
|
var FileSink = class {
|
|
14
10
|
files = /* @__PURE__ */ new Map();
|
|
15
11
|
saved = 0;
|
|
@@ -17,8 +13,10 @@ var FileSink = class {
|
|
|
17
13
|
this.root = root;
|
|
18
14
|
}
|
|
19
15
|
target(name) {
|
|
20
|
-
|
|
21
|
-
|
|
16
|
+
const target = path.resolve(this.root, ...name.split("/"));
|
|
17
|
+
const relative = path.relative(path.resolve(this.root), target);
|
|
18
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new Error(`the server sent the path ${name}, which leaves the output directory`);
|
|
19
|
+
return target;
|
|
22
20
|
}
|
|
23
21
|
begin(name, directory) {
|
|
24
22
|
const target = this.target(name);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.js","names":[],"sources":["../../../../src/cli/commands/data/read.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { UsageError } from \"../../../client\";\nimport { tr } from \"../../../i18n\";\nimport { defineCommand } from \"../../command\";\nimport { session } from \"../../session\";\nimport { operandCount } from \"./operand\";\n\
|
|
1
|
+
{"version":3,"file":"read.js","names":[],"sources":["../../../../src/cli/commands/data/read.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { UsageError } from \"../../../client\";\nimport { tr } from \"../../../i18n\";\nimport { defineCommand } from \"../../command\";\nimport { session } from \"../../session\";\nimport { operandCount } from \"./operand\";\n\nclass FileSink {\n declare root: string;\n files = new Map();\n saved = 0;\n\n constructor(root) {\n this.root = root;\n }\n\n target(name) {\n const target = path.resolve(this.root, ...name.split(\"/\"));\n const relative = path.relative(path.resolve(this.root), target);\n if (\n relative === \"..\" ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n ) {\n throw new Error(\n `the server sent the path ${name}, which leaves the output directory`,\n );\n }\n return target;\n }\n\n begin(name, directory) {\n const target = this.target(name);\n if (directory) {\n fs.mkdirSync(target, { recursive: true });\n return;\n }\n fs.mkdirSync(path.dirname(target), { recursive: true });\n const previous = this.files.get(name);\n if (previous !== undefined) {\n fs.closeSync(previous);\n }\n this.files.set(name, fs.openSync(target, \"w\"));\n this.saved++;\n }\n\n write(name, offset, data) {\n const file = this.files.get(name);\n if (file === undefined) {\n throw new Error(`the server sent data for ${name} before announcing it`);\n }\n fs.writeSync(file, data, 0, data.length, Number(offset));\n }\n\n close() {\n for (const file of this.files.values()) {\n fs.closeSync(file);\n }\n }\n}\n\nconst printSaved = (target, count) =>\n console.error(\n tr(\n {\n one: \"saved {count} file to {path}\",\n other: \"saved {count} files to {path}\",\n },\n { count, path: target },\n ),\n );\n\nconst readFile = (target) => (context) =>\n session(context, async (client) => {\n const {\n id,\n wholeDirectory,\n subdirectory,\n args: [given],\n } = target(context.args);\n const output = context.options.output ?? \"\";\n const requested = path.posix\n .normalize(`/${given}`)\n .replace(/^\\/+|\\/+$/g, \"\");\n const printing = output === \"\" || output === \"-\";\n const directory = () =>\n new UsageError(\n requested === \"\"\n ? wholeDirectory(JSON.stringify(given))\n : subdirectory(JSON.stringify(requested)),\n );\n const relativeTo = (name) =>\n name.slice(requested.length).replace(/^\\//, \"\");\n let sink;\n let single;\n const contents = [];\n try {\n for await (const response of client.swiplets.readDataFile(\n { swipletId: id, path: given },\n { signal: context.signal },\n )) {\n if (response.part.case === \"file\") {\n const file = response.part.value;\n if (file.path === requested && !file.directory) {\n single = file;\n continue;\n }\n if (!sink) {\n if (printing) {\n throw directory();\n }\n sink = new FileSink(output);\n }\n sink.begin(relativeTo(file.path), file.directory);\n } else if (response.part.case === \"chunk\") {\n const chunk = response.part.value;\n if (single && chunk.path === single.path) {\n contents.push(chunk.data);\n continue;\n }\n if (!sink) {\n throw new Error(\n `the server sent data for ${chunk.path} before announcing it`,\n );\n }\n sink.write(relativeTo(chunk.path), chunk.offset, chunk.data);\n }\n }\n } finally {\n sink?.close();\n }\n if (sink) {\n printSaved(sink.root, sink.saved);\n return;\n }\n if (!single) {\n if (printing) {\n throw directory();\n }\n fs.mkdirSync(output, { recursive: true });\n printSaved(output, 0);\n return;\n }\n const data = Buffer.concat(contents);\n if (printing) {\n process.stdout.write(data);\n return;\n }\n let destination = output;\n if (fs.existsSync(destination) && fs.statSync(destination).isDirectory()) {\n destination = path.join(destination, path.posix.basename(single.path));\n }\n fs.writeFileSync(destination, data);\n printSaved(destination, 1);\n });\n\nexport const read = (operand, target) => {\n const before = operandCount(operand);\n return defineCommand({\n name: \"read\",\n use: `read ${operand}PATH`,\n short: tr(\"Read a data file or directory\"),\n args: [before + 1, before + 1],\n options: {\n output: { type: \"string\", value: \"PATH\", help: tr(\"destination\") },\n },\n run: readFile(target),\n });\n};\n"],"mappings":";;;;;;;;AASA,IAAM,WAAN,MAAe;CAEb,wBAAQ,IAAI,IAAI;CAChB,QAAQ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,IAAI,CAAC,QAAQ;EACX,IAAI,UACF,MAAM,UAAU;EAElB,GAAG,UAAU,QAAQ,EAAE,WAAW,KAAK,CAAC;EACxC,WAAW,QAAQ,CAAC;EACpB;CACF;CACA,MAAM,OAAO,OAAO,OAAO,QAAQ;CACnC,IAAI,UAAU;EACZ,QAAQ,OAAO,MAAM,IAAI;EACzB;CACF;CACA,IAAI,cAAc;CAClB,IAAI,GAAG,WAAW,WAAW,KAAK,GAAG,SAAS,WAAW,CAAC,CAAC,YAAY,GACrE,cAAc,KAAK,KAAK,aAAa,KAAK,MAAM,SAAS,OAAO,IAAI,CAAC;CAEvE,GAAG,cAAc,aAAa,IAAI;CAClC,WAAW,aAAa,CAAC;AAC3B,CAAC;AAEH,MAAa,QAAQ,SAAS,WAAW;CACvC,MAAM,SAAS,aAAa,OAAO;CACnC,OAAO,cAAc;EACnB,MAAM;EACN,KAAK,QAAQ,QAAQ;EACrB,OAAO,GAAG,+BAA+B;EACzC,MAAM,CAAC,SAAS,GAAG,SAAS,CAAC;EAC7B,SAAS,EACP,QAAQ;GAAE,MAAM;GAAU,OAAO;GAAQ,MAAM,GAAG,aAAa;EAAE,EACnE;EACA,KAAK,SAAS,MAAM;CACtB,CAAC;AACH"}
|
|
@@ -3,16 +3,16 @@ import { defineCommand } from "../../command.js";
|
|
|
3
3
|
import { session } from "../../session.js";
|
|
4
4
|
import { deviceOption } from "../flags.js";
|
|
5
5
|
// src/cli/commands/device/stop.ts
|
|
6
|
-
const
|
|
6
|
+
const stopServing = (context) => session(context, async (client) => {
|
|
7
7
|
await client.system.shutdown({}, { signal: context.signal });
|
|
8
8
|
console.log(tr("stopped"));
|
|
9
9
|
});
|
|
10
10
|
const stop = defineCommand({
|
|
11
11
|
name: "stop",
|
|
12
|
-
short: tr("Stop the Swipt
|
|
12
|
+
short: tr("Stop serving the Swipt API"),
|
|
13
13
|
args: [0, 0],
|
|
14
14
|
options: deviceOption,
|
|
15
|
-
run:
|
|
15
|
+
run: stopServing
|
|
16
16
|
});
|
|
17
17
|
export { stop };
|
|
18
18
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stop.js","names":[],"sources":["../../../../src/cli/commands/device/stop.ts"],"sourcesContent":["import { tr } from \"../../../i18n\";\nimport { defineCommand } from \"../../command\";\nimport { session } from \"../../session\";\nimport { deviceOption } from \"../flags\";\n\nconst
|
|
1
|
+
{"version":3,"file":"stop.js","names":[],"sources":["../../../../src/cli/commands/device/stop.ts"],"sourcesContent":["import { tr } from \"../../../i18n\";\nimport { defineCommand } from \"../../command\";\nimport { session } from \"../../session\";\nimport { deviceOption } from \"../flags\";\n\nconst stopServing = (context) =>\n session(context, async (client) => {\n await client.system.shutdown({}, { signal: context.signal });\n console.log(tr(\"stopped\"));\n });\n\nexport const stop = defineCommand({\n name: \"stop\",\n short: tr(\"Stop serving the Swipt API\"),\n args: [0, 0],\n options: deviceOption,\n run: stopServing,\n});\n"],"mappings":";;;;;AAKA,MAAM,eAAe,YACnB,QAAQ,SAAS,OAAO,WAAW;CACjC,MAAM,OAAO,OAAO,SAAS,CAAC,GAAG,EAAE,QAAQ,QAAQ,OAAO,CAAC;CAC3D,QAAQ,IAAI,GAAG,SAAS,CAAC;AAC3B,CAAC;AAEH,MAAa,OAAO,cAAc;CAChC,MAAM;CACN,OAAO,GAAG,4BAA4B;CACtC,MAAM,CAAC,GAAG,CAAC;CACX,SAAS;CACT,KAAK;AACP,CAAC"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { run } from "../../../serve.js";
|
|
2
|
+
import { tr } from "../../../i18n.js";
|
|
3
|
+
import { defineCommand } from "../../command.js";
|
|
4
|
+
import { passcodeOptions, udidDeviceOption } from "../flags.js";
|
|
5
|
+
// src/cli/commands/driver/driver.ts
|
|
6
|
+
const driver = defineCommand({
|
|
7
|
+
name: "driver",
|
|
8
|
+
short: tr("Serve the Swipt API and MCP for a device from this computer"),
|
|
9
|
+
description: [tr("Only one can control the device at a time: Swipt on it, or the driver on one computer.")],
|
|
10
|
+
args: [0, 0],
|
|
11
|
+
options: {
|
|
12
|
+
...udidDeviceOption,
|
|
13
|
+
...passcodeOptions(tr("passcode to unlock the device automatically; empty turns that off")),
|
|
14
|
+
token: {
|
|
15
|
+
type: "string",
|
|
16
|
+
value: "TOKEN",
|
|
17
|
+
help: tr("require this token from API clients")
|
|
18
|
+
},
|
|
19
|
+
"random-token": {
|
|
20
|
+
type: "boolean",
|
|
21
|
+
help: tr("require a random token from API clients")
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
run
|
|
25
|
+
});
|
|
26
|
+
export { driver };
|
|
27
|
+
|
|
28
|
+
//# sourceMappingURL=driver.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"driver.js","names":["serving.run"],"sources":["../../../../src/cli/commands/driver/driver.ts"],"sourcesContent":["import * as serving from \"../../../serve\";\nimport { tr } from \"../../../i18n\";\nimport { defineCommand } from \"../../command\";\nimport { passcodeOptions, udidDeviceOption } from \"../flags\";\n\nexport const driver = defineCommand({\n name: \"driver\",\n short: tr(\"Serve the Swipt API and MCP for a device from this computer\"),\n description: [\n tr(\n \"Only one can control the device at a time: Swipt on it, or the driver on one computer.\",\n ),\n ],\n args: [0, 0],\n options: {\n ...udidDeviceOption,\n ...passcodeOptions(\n tr(\"passcode to unlock the device automatically; empty turns that off\"),\n ),\n token: {\n type: \"string\",\n value: \"TOKEN\",\n help: tr(\"require this token from API clients\"),\n },\n \"random-token\": {\n type: \"boolean\",\n help: tr(\"require a random token from API clients\"),\n },\n },\n run: serving.run,\n});\n"],"mappings":";;;;;AAKA,MAAa,SAAS,cAAc;CAClC,MAAM;CACN,OAAO,GAAG,6DAA6D;CACvE,aAAa,CACX,GACE,wFACF,CACF;CACA,MAAM,CAAC,GAAG,CAAC;CACX,SAAS;EACP,GAAG;EACH,GAAG,gBACD,GAAG,mEAAmE,CACxE;EACA,OAAO;GACL,MAAM;GACN,OAAO;GACP,MAAM,GAAG,qCAAqC;EAChD;EACA,gBAAgB;GACd,MAAM;GACN,MAAM,GAAG,yCAAyC;EACpD;CACF;CACKA;AACP,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { driver } from "./driver.js";
|
|
@@ -6,13 +6,14 @@ const deviceOption = { device: {
|
|
|
6
6
|
value: "NAME|URL",
|
|
7
7
|
help: tr("the device to use")
|
|
8
8
|
} };
|
|
9
|
+
const udidDeviceOption = { device: {
|
|
10
|
+
type: "string",
|
|
11
|
+
short: "d",
|
|
12
|
+
value: "NAME|UDID",
|
|
13
|
+
help: tr("the device to use")
|
|
14
|
+
} };
|
|
9
15
|
const sideloadOptions = {
|
|
10
|
-
|
|
11
|
-
type: "string",
|
|
12
|
-
short: "d",
|
|
13
|
-
value: "NAME|UDID",
|
|
14
|
-
help: tr("the device to use")
|
|
15
|
-
},
|
|
16
|
+
...udidDeviceOption,
|
|
16
17
|
team: {
|
|
17
18
|
type: "string",
|
|
18
19
|
value: "ID",
|
|
@@ -52,6 +53,6 @@ const setupOptions = {
|
|
|
52
53
|
},
|
|
53
54
|
...setupStepOptions
|
|
54
55
|
};
|
|
55
|
-
export { deviceOption, nightlyOption, passcodeOptions, setupOptions, setupStepOptions, sideloadOptions };
|
|
56
|
+
export { deviceOption, nightlyOption, passcodeOptions, setupOptions, setupStepOptions, sideloadOptions, udidDeviceOption };
|
|
56
57
|
|
|
57
58
|
//# sourceMappingURL=flags.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flags.js","names":[],"sources":["../../../src/cli/commands/flags.ts"],"sourcesContent":["import { tr } from \"../../i18n\";\nimport type { Options } from \"../command\";\n\nexport const deviceOption: Options = {\n device: {\n type: \"string\",\n short: \"d\",\n value: \"NAME|URL\",\n help: tr(\"the device to use\"),\n },\n};\n\nexport const
|
|
1
|
+
{"version":3,"file":"flags.js","names":[],"sources":["../../../src/cli/commands/flags.ts"],"sourcesContent":["import { tr } from \"../../i18n\";\nimport type { Options } from \"../command\";\n\nexport const deviceOption: Options = {\n device: {\n type: \"string\",\n short: \"d\",\n value: \"NAME|URL\",\n help: tr(\"the device to use\"),\n },\n};\n\nexport const udidDeviceOption: Options = {\n device: {\n type: \"string\",\n short: \"d\",\n value: \"NAME|UDID\",\n help: tr(\"the device to use\"),\n },\n};\n\nexport const sideloadOptions: Options = {\n ...udidDeviceOption,\n team: {\n type: \"string\",\n value: \"ID\",\n help: tr(\"team ID, required if more than one\"),\n },\n};\n\nexport const passcodeOptions = (help): Options => ({\n passcode: { type: \"string\", value: \"CODE\", help },\n \"passcode-type\": {\n type: \"string\",\n value: \"TYPE\",\n help: tr(\"pin (4 or 6 digits, default), numeric or alphanumeric\"),\n },\n});\n\nexport const nightlyOption: Options = {\n nightly: { type: \"boolean\", help: tr(\"use nightly build\") },\n};\n\nexport const setupStepOptions: Options = {\n \"no-setup-pair\": { type: \"boolean\", help: tr(\"don't pair Swipt\") },\n \"no-setup-api\": {\n type: \"boolean\",\n help: tr(\"don't publish the API to the local network\"),\n },\n};\n\nexport const setupOptions: Options = {\n \"no-setup\": {\n type: \"boolean\",\n help: tr(\"don't pair Swipt, trust its developer or publish its API\"),\n },\n ...setupStepOptions,\n};\n"],"mappings":";;AAGA,MAAa,eAAwB,EACnC,QAAQ;CACN,MAAM;CACN,OAAO;CACP,OAAO;CACP,MAAM,GAAG,mBAAmB;AAC9B,EACF;AAEA,MAAa,mBAA4B,EACvC,QAAQ;CACN,MAAM;CACN,OAAO;CACP,OAAO;CACP,MAAM,GAAG,mBAAmB;AAC9B,EACF;AAEA,MAAa,kBAA2B;CACtC,GAAG;CACH,MAAM;EACJ,MAAM;EACN,OAAO;EACP,MAAM,GAAG,oCAAoC;CAC/C;AACF;AAEA,MAAa,mBAAmB,UAAmB;CACjD,UAAU;EAAE,MAAM;EAAU,OAAO;EAAQ;CAAK;CAChD,iBAAiB;EACf,MAAM;EACN,OAAO;EACP,MAAM,GAAG,uDAAuD;CAClE;AACF;AAEA,MAAa,gBAAyB,EACpC,SAAS;CAAE,MAAM;CAAW,MAAM,GAAG,mBAAmB;AAAE,EAC5D;AAEA,MAAa,mBAA4B;CACvC,iBAAiB;EAAE,MAAM;EAAW,MAAM,GAAG,kBAAkB;CAAE;CACjE,gBAAgB;EACd,MAAM;EACN,MAAM,GAAG,4CAA4C;CACvD;AACF;AAEA,MAAa,eAAwB;CACnC,YAAY;EACV,MAAM;EACN,MAAM,GAAG,0DAA0D;CACrE;CACA,GAAG;AACL"}
|
|
@@ -2,6 +2,8 @@ import { tr } from "../../i18n.js";
|
|
|
2
2
|
import { defineCommand } from "../command.js";
|
|
3
3
|
import { device } from "./device/device.js";
|
|
4
4
|
import "./device/index.js";
|
|
5
|
+
import { driver } from "./driver/driver.js";
|
|
6
|
+
import "./driver/index.js";
|
|
5
7
|
import { project } from "./project/project.js";
|
|
6
8
|
import "./project/index.js";
|
|
7
9
|
import { repl } from "./repl/repl.js";
|
|
@@ -21,6 +23,7 @@ const root = defineCommand({
|
|
|
21
23
|
device,
|
|
22
24
|
swiplet,
|
|
23
25
|
repl,
|
|
26
|
+
driver,
|
|
24
27
|
sideload,
|
|
25
28
|
version
|
|
26
29
|
]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/cli/commands/index.ts"],"sourcesContent":["import { tr } from \"../../i18n\";\nimport { defineCommand } from \"../command\";\nimport { device } from \"./device\";\nimport { project } from \"./project\";\nimport { repl } from \"./repl\";\nimport { sideload } from \"./sideload\";\nimport { swiplet } from \"./swiplet\";\nimport { version } from \"./version\";\n\nexport const root = defineCommand({\n name: \"swipt\",\n short: tr(\"Swipt CLI\"),\n commands: [project, device, swiplet, repl, sideload, version],\n});\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/cli/commands/index.ts"],"sourcesContent":["import { tr } from \"../../i18n\";\nimport { defineCommand } from \"../command\";\nimport { device } from \"./device\";\nimport { driver } from \"./driver\";\nimport { project } from \"./project\";\nimport { repl } from \"./repl\";\nimport { sideload } from \"./sideload\";\nimport { swiplet } from \"./swiplet\";\nimport { version } from \"./version\";\n\nexport const root = defineCommand({\n name: \"swipt\",\n short: tr(\"Swipt CLI\"),\n commands: [project, device, swiplet, repl, driver, sideload, version],\n});\n"],"mappings":";;;;;;;;;;;;;;;;;AAUA,MAAa,OAAO,cAAc;CAChC,MAAM;CACN,OAAO,GAAG,WAAW;CACrB,UAAU;EAAC;EAAS;EAAQ;EAAS;EAAM;EAAQ;EAAU;CAAO;AACtE,CAAC"}
|
|
@@ -86,7 +86,7 @@ export default function App() {
|
|
|
86
86
|
}
|
|
87
87
|
`
|
|
88
88
|
};
|
|
89
|
-
const quote = (value) => /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
|
|
89
|
+
const quote = (value) => process.platform === "win32" ? /^[\w.:\\/-]+$/.test(value) ? value : `"${value}"` : /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
|
|
90
90
|
function createCommand(directory) {
|
|
91
91
|
const root = path.resolve(directory);
|
|
92
92
|
if (fs.existsSync(root) && fs.readdirSync(root).length > 0) throw new Error(tr("{directory} isn't empty.", { directory }));
|
|
@@ -95,7 +95,7 @@ function createCommand(directory) {
|
|
|
95
95
|
fs.writeFileSync(path.join(root, file), template(path.basename(root)));
|
|
96
96
|
}
|
|
97
97
|
const manager = process.env.npm_config_user_agent?.split("/")[0] ?? "npm";
|
|
98
|
-
console.log(`cd ${quote(directory)}
|
|
98
|
+
console.log(`cd ${quote(directory)}\n${manager} install\n${manager} run build`);
|
|
99
99
|
}
|
|
100
100
|
const create = defineCommand({
|
|
101
101
|
name: "create",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.js","names":[],"sources":["../../../../src/cli/commands/project/create.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport { tr } from \"../../../i18n\";\nimport { defineCommand } from \"../../command\";\n\nconst { version } = JSON.parse(\n fs.readFileSync(new URL(\"../../../../package.json\", import.meta.url), \"utf8\"),\n);\nconst require = createRequire(import.meta.url);\nconst { peerDependencies } = require(\"@swipt/api/package.json\");\n\nconst swiptRange = version.includes(\"-\")\n ? version\n : `>=${version}-0 <=${version}`;\n\nconst idOf = (name) =>\n name\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^[._-]+/, \"\")\n .slice(0, 128)\n .replace(/[._-]+$/, \"\") || \"swiplet\";\n\nconst templates = {\n \"package.json\": (name) =>\n `${JSON.stringify(\n {\n name: idOf(name),\n version: \"0.1.0\",\n private: true,\n swiplet: {\n id: idOf(name),\n name,\n versionCode: 1,\n icon: { color: \"blue\", symbol: \"sparkles\" },\n app: \"./src/App.tsx\",\n extension: \"./src/extension.ts\",\n },\n scripts: { build: \"swipt project build\", check: \"tsc\" },\n dependencies: { zod: \"^4.6.7\" },\n devDependencies: {\n \"@swipt/api\": swiptRange,\n \"@swipt/cli\": swiptRange,\n typescript: \"^7.0.2\",\n ...Object.fromEntries(\n [\"@expo/ui\", \"@types/react\", \"react\"].map((name) => [\n name,\n peerDependencies[name],\n ]),\n ),\n },\n },\n null,\n 2,\n )}\\n`,\n \"tsconfig.json\": () =>\n `${JSON.stringify(\n {\n compilerOptions: {\n target: \"ES2022\",\n module: \"ESNext\",\n moduleResolution: \"Bundler\",\n jsx: \"react-jsx\",\n lib: [\"ES2023\", \"DOM\"],\n strict: true,\n noEmit: true,\n skipLibCheck: true,\n },\n },\n null,\n 2,\n )}\\n`,\n \".gitignore\": () => \"node_modules/\\ndist/\\n\",\n \"src/extension.ts\": () => `import * as device from \"@swipt/api/device\";\nimport { defineAction, defineExtension } from \"@swipt/api/swiplet\";\n\nexport default defineExtension({\n actions: {\n frontApp: defineAction({\n title: \"Find the App in Front\",\n run: (_, { signal }) => device.foregroundApplication.get({ signal }),\n }),\n },\n});\n`,\n \"src/App.tsx\":\n () => `import { Button, Form, Host, Section, Text } from \"@expo/ui/swift-ui\";\nimport { useState } from \"react\";\nimport { actions } from \"@swipt/api/swiplet\";\n\nimport type extension from \"./extension\";\n\nconst { frontApp } = actions<typeof extension>();\n\nexport default function App() {\n const [app, setApp] = useState(\"\");\n return (\n <Host style={{ flex: 1 }}>\n <Form>\n <Section>\n <Button label=\"Find the App in Front\" onPress={async () => setApp(await frontApp())} />\n {app === \"\" ? null : <Text>{app}</Text>}\n </Section>\n </Form>\n </Host>\n );\n}\n`,\n};\n\nconst quote = (value) =>\n /^[\\w
|
|
1
|
+
{"version":3,"file":"create.js","names":[],"sources":["../../../../src/cli/commands/project/create.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport { tr } from \"../../../i18n\";\nimport { defineCommand } from \"../../command\";\n\nconst { version } = JSON.parse(\n fs.readFileSync(new URL(\"../../../../package.json\", import.meta.url), \"utf8\"),\n);\nconst require = createRequire(import.meta.url);\nconst { peerDependencies } = require(\"@swipt/api/package.json\");\n\nconst swiptRange = version.includes(\"-\")\n ? version\n : `>=${version}-0 <=${version}`;\n\nconst idOf = (name) =>\n name\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^[._-]+/, \"\")\n .slice(0, 128)\n .replace(/[._-]+$/, \"\") || \"swiplet\";\n\nconst templates = {\n \"package.json\": (name) =>\n `${JSON.stringify(\n {\n name: idOf(name),\n version: \"0.1.0\",\n private: true,\n swiplet: {\n id: idOf(name),\n name,\n versionCode: 1,\n icon: { color: \"blue\", symbol: \"sparkles\" },\n app: \"./src/App.tsx\",\n extension: \"./src/extension.ts\",\n },\n scripts: { build: \"swipt project build\", check: \"tsc\" },\n dependencies: { zod: \"^4.6.7\" },\n devDependencies: {\n \"@swipt/api\": swiptRange,\n \"@swipt/cli\": swiptRange,\n typescript: \"^7.0.2\",\n ...Object.fromEntries(\n [\"@expo/ui\", \"@types/react\", \"react\"].map((name) => [\n name,\n peerDependencies[name],\n ]),\n ),\n },\n },\n null,\n 2,\n )}\\n`,\n \"tsconfig.json\": () =>\n `${JSON.stringify(\n {\n compilerOptions: {\n target: \"ES2022\",\n module: \"ESNext\",\n moduleResolution: \"Bundler\",\n jsx: \"react-jsx\",\n lib: [\"ES2023\", \"DOM\"],\n strict: true,\n noEmit: true,\n skipLibCheck: true,\n },\n },\n null,\n 2,\n )}\\n`,\n \".gitignore\": () => \"node_modules/\\ndist/\\n\",\n \"src/extension.ts\": () => `import * as device from \"@swipt/api/device\";\nimport { defineAction, defineExtension } from \"@swipt/api/swiplet\";\n\nexport default defineExtension({\n actions: {\n frontApp: defineAction({\n title: \"Find the App in Front\",\n run: (_, { signal }) => device.foregroundApplication.get({ signal }),\n }),\n },\n});\n`,\n \"src/App.tsx\":\n () => `import { Button, Form, Host, Section, Text } from \"@expo/ui/swift-ui\";\nimport { useState } from \"react\";\nimport { actions } from \"@swipt/api/swiplet\";\n\nimport type extension from \"./extension\";\n\nconst { frontApp } = actions<typeof extension>();\n\nexport default function App() {\n const [app, setApp] = useState(\"\");\n return (\n <Host style={{ flex: 1 }}>\n <Form>\n <Section>\n <Button label=\"Find the App in Front\" onPress={async () => setApp(await frontApp())} />\n {app === \"\" ? null : <Text>{app}</Text>}\n </Section>\n </Form>\n </Host>\n );\n}\n`,\n};\n\nconst quote = (value) =>\n process.platform === \"win32\"\n ? /^[\\w.:\\\\/-]+$/.test(value)\n ? value\n : `\"${value}\"`\n : /^[\\w@%+=:,./-]+$/.test(value)\n ? value\n : `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n\nfunction createCommand(directory) {\n const root = path.resolve(directory);\n if (fs.existsSync(root) && fs.readdirSync(root).length > 0) {\n throw new Error(tr(\"{directory} isn't empty.\", { directory }));\n }\n for (const [file, template] of Object.entries(templates)) {\n fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });\n fs.writeFileSync(path.join(root, file), template(path.basename(root)));\n }\n const manager = process.env.npm_config_user_agent?.split(\"/\")[0] ?? \"npm\";\n console.log(\n `cd ${quote(directory)}\\n${manager} install\\n${manager} run build`,\n );\n}\n\nexport const create = defineCommand({\n name: \"create\",\n use: \"create DIRECTORY\",\n short: tr(\"Make a swiplet project in a new or empty directory\"),\n args: [1, 1],\n run: ({ args }) => createCommand(args[0]),\n});\n"],"mappings":";;;;;;AAOA,MAAM,EAAE,YAAY,KAAK,MACvB,GAAG,aAAa,IAAI,IAAI,4BAA4B,YAAY,GAAG,GAAG,MAAM,CAC9E;AAEA,MAAM,EAAE,qBADQ,cAAc,YAAY,GACP,CAAC,CAAC,yBAAyB;AAE9D,MAAM,aAAa,QAAQ,SAAS,GAAG,IACnC,UACA,KAAK,QAAQ,OAAO;AAExB,MAAM,QAAQ,SACZ,KACG,YAAY,CAAC,CACb,QAAQ,kBAAkB,GAAG,CAAC,CAC9B,QAAQ,WAAW,EAAE,CAAC,CACtB,MAAM,GAAG,GAAG,CAAC,CACb,QAAQ,WAAW,EAAE,KAAK;AAE/B,MAAM,YAAY;CAChB,iBAAiB,SACf,GAAG,KAAK,UACN;EACE,MAAM,KAAK,IAAI;EACf,SAAS;EACT,SAAS;EACT,SAAS;GACP,IAAI,KAAK,IAAI;GACb;GACA,aAAa;GACb,MAAM;IAAE,OAAO;IAAQ,QAAQ;GAAW;GAC1C,KAAK;GACL,WAAW;EACb;EACA,SAAS;GAAE,OAAO;GAAuB,OAAO;EAAM;EACtD,cAAc,EAAE,KAAK,SAAS;EAC9B,iBAAiB;GACf,cAAc;GACd,cAAc;GACd,YAAY;GACZ,GAAG,OAAO,YACR;IAAC;IAAY;IAAgB;GAAO,CAAC,CAAC,KAAK,SAAS,CAClD,MACA,iBAAiB,KACnB,CAAC,CACH;EACF;CACF,GACA,MACA,CACF,EAAE;CACJ,uBACE,GAAG,KAAK,UACN,EACE,iBAAiB;EACf,QAAQ;EACR,QAAQ;EACR,kBAAkB;EAClB,KAAK;EACL,KAAK,CAAC,UAAU,KAAK;EACrB,QAAQ;EACR,QAAQ;EACR,cAAc;CAChB,EACF,GACA,MACA,CACF,EAAE;CACJ,oBAAoB;CACpB,0BAA0B;;;;;;;;;;;;CAY1B,qBACQ;;;;;;;;;;;;;;;;;;;;;;AAsBV;AAEA,MAAM,SAAS,UACb,QAAQ,aAAa,UACjB,gBAAgB,KAAK,KAAK,IACxB,QACA,IAAI,MAAM,KACZ,mBAAmB,KAAK,KAAK,IAC3B,QACA,IAAI,MAAM,WAAW,KAAK,OAAO,EAAE;AAE3C,SAAS,cAAc,WAAW;CAChC,MAAM,OAAO,KAAK,QAAQ,SAAS;CACnC,IAAI,GAAG,WAAW,IAAI,KAAK,GAAG,YAAY,IAAI,CAAC,CAAC,SAAS,GACvD,MAAM,IAAI,MAAM,GAAG,4BAA4B,EAAE,UAAU,CAAC,CAAC;CAE/D,KAAK,MAAM,CAAC,MAAM,aAAa,OAAO,QAAQ,SAAS,GAAG;EACxD,GAAG,UAAU,KAAK,QAAQ,KAAK,KAAK,MAAM,IAAI,CAAC,GAAG,EAAE,WAAW,KAAK,CAAC;EACrE,GAAG,cAAc,KAAK,KAAK,MAAM,IAAI,GAAG,SAAS,KAAK,SAAS,IAAI,CAAC,CAAC;CACvE;CACA,MAAM,UAAU,QAAQ,IAAI,uBAAuB,MAAM,GAAG,CAAC,CAAC,MAAM;CACpE,QAAQ,IACN,MAAM,MAAM,SAAS,EAAE,IAAI,QAAQ,YAAY,QAAQ,WACzD;AACF;AAEA,MAAa,SAAS,cAAc;CAClC,MAAM;CACN,KAAK;CACL,OAAO,GAAG,oDAAoD;CAC9D,MAAM,CAAC,GAAG,CAAC;CACX,MAAM,EAAE,WAAW,cAAc,KAAK,EAAE;AAC1C,CAAC"}
|
|
@@ -3,10 +3,9 @@ import { idPattern } from "../../../project.js";
|
|
|
3
3
|
import { defineCommand } from "../../command.js";
|
|
4
4
|
import fs from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
|
-
import { execFileSync } from "node:child_process";
|
|
7
6
|
import { createHash } from "node:crypto";
|
|
7
|
+
import { strFromU8, unzipSync } from "fflate";
|
|
8
8
|
// src/cli/commands/project/source.ts
|
|
9
|
-
const manifestEntry = /^(?:[^/]+\/)?manifest\.json$/;
|
|
10
9
|
function loadSource(root) {
|
|
11
10
|
const manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
|
12
11
|
const config = manifest.source ?? {};
|
|
@@ -51,18 +50,20 @@ function workspaceSwiplets(source) {
|
|
|
51
50
|
return files;
|
|
52
51
|
}
|
|
53
52
|
function readSwiplet(file) {
|
|
54
|
-
const
|
|
53
|
+
const data = fs.readFileSync(file);
|
|
54
|
+
let entry;
|
|
55
|
+
try {
|
|
56
|
+
entry = unzipSync(data, { filter: ({ name }) => name === "manifest.json" })["manifest.json"];
|
|
57
|
+
} catch (error) {
|
|
58
|
+
throw new Error(`${file}: ${error.message}`);
|
|
59
|
+
}
|
|
55
60
|
if (entry === void 0) throw new Error(`${file} has no manifest.json`);
|
|
56
|
-
const manifest = JSON.parse(
|
|
57
|
-
"-p",
|
|
58
|
-
file,
|
|
59
|
-
entry
|
|
60
|
-
], { encoding: "utf8" }));
|
|
61
|
+
const manifest = JSON.parse(strFromU8(entry));
|
|
61
62
|
if (typeof manifest.id !== "string" || !idPattern.test(manifest.id)) throw new Error(`${file} has no valid swiplet id in its manifest`);
|
|
62
63
|
return {
|
|
63
64
|
file,
|
|
64
65
|
manifest,
|
|
65
|
-
data
|
|
66
|
+
data
|
|
66
67
|
};
|
|
67
68
|
}
|
|
68
69
|
function sourceCommand(root, given) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source.js","names":[],"sources":["../../../../src/cli/commands/project/source.ts"],"sourcesContent":["import { execFileSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { tr } from \"../../../i18n\";\nimport { idPattern } from \"../../../project\";\nimport { defineCommand } from \"../../command\";\n\nconst manifestEntry = /^(?:[^/]+\\/)?manifest\\.json$/;\n\nfunction loadSource(root) {\n const manifest = JSON.parse(\n fs.readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n );\n const config = manifest.source ?? {};\n for (const field of [\"name\", \"image\", \"url\"]) {\n if (config[field] !== undefined && typeof config[field] !== \"string\") {\n throw new Error(\n tr('\"{field}\" in package.json must be a string.', {\n field: `source.${field}`,\n }),\n );\n }\n }\n const localizedNames = config.localizedNames ?? {};\n if (\n localizedNames === null ||\n typeof localizedNames !== \"object\" ||\n !Object.values(localizedNames).every((name) => typeof name === \"string\")\n ) {\n throw new Error(\n tr(\n '\"source.localizedNames\" in package.json must map languages to names.',\n ),\n );\n }\n if (\n config.icon !== undefined &&\n (typeof config.icon?.symbol !== \"string\" ||\n (config.icon.color !== undefined &&\n typeof config.icon.color !== \"string\"))\n ) {\n throw new Error(\n tr(\n '\"source.icon\" in package.json must have a symbol and may have a color.',\n ),\n );\n }\n if (\n config.icon?.symbolColor !== undefined &&\n typeof config.icon.symbolColor !== \"string\"\n ) {\n throw new Error(\n tr('\"{field}\" in package.json must be a string.', {\n field: \"source.icon.symbolColor\",\n }),\n );\n }\n let prefix;\n if (config.url !== undefined) {\n try {\n prefix = new URL(\n config.url.endsWith(\"/\") ? config.url : `${config.url}/`,\n );\n } catch {\n throw new Error(\n tr('\"source.url\" in package.json isn\\'t an absolute URL.'),\n );\n }\n }\n const workspaces = Array.isArray(manifest.workspaces)\n ? manifest.workspaces\n : (manifest.workspaces?.packages ?? []);\n return { root, config, localizedNames, prefix, workspaces };\n}\n\nfunction workspaceSwiplets(source) {\n const files = [];\n for (const pattern of source.workspaces) {\n for (const directory of fs.globSync(pattern, { cwd: source.root }).sort()) {\n const project = path.join(source.root, directory, \"package.json\");\n if (!fs.existsSync(project)) {\n continue;\n }\n const id = JSON.parse(fs.readFileSync(project, \"utf8\")).swiplet?.id;\n if (typeof id !== \"string\") {\n continue;\n }\n const built = path.join(source.root, directory, \"dist\", `${id}.swiplet`);\n if (!fs.existsSync(built)) {\n throw new Error(\n tr(\"{file} is missing; build {directory} first.\", {\n file: path.relative(source.root, built),\n directory,\n }),\n );\n }\n files.push(built);\n }\n }\n return files;\n}\n\nfunction readSwiplet(file) {\n const entry = execFileSync(\"unzip\", [\"-Z1\", file], { encoding: \"utf8\" })\n .split(\"\\n\")\n .filter((name) => manifestEntry.test(name))\n .sort((a, b) => a.length - b.length)[0];\n if (entry === undefined) {\n throw new Error(`${file} has no manifest.json`);\n }\n const manifest = JSON.parse(\n execFileSync(\"unzip\", [\"-p\", file, entry], { encoding: \"utf8\" }),\n );\n if (typeof manifest.id !== \"string\" || !idPattern.test(manifest.id)) {\n throw new Error(`${file} has no valid swiplet id in its manifest`);\n }\n return { file, manifest, data: fs.readFileSync(file) };\n}\n\nfunction sourceCommand(root, given) {\n const source = loadSource(root);\n const files =\n given.length > 0\n ? given.map((file) => path.resolve(file))\n : workspaceSwiplets(source);\n if (files.length === 0) {\n throw new Error(\n tr(\n \"package.json lists no workspaces with swiplets; name the swiplets to list.\",\n ),\n );\n }\n const swiplets = new Map();\n for (const read of files.map(readSwiplet)) {\n const { id } = read.manifest;\n if (swiplets.has(id)) {\n throw new Error(\n tr(\"{id} is both {first} and {second}\", {\n id,\n first: swiplets.get(id).file,\n second: read.file,\n }),\n );\n }\n swiplets.set(id, read);\n }\n const image =\n source.config.image === undefined\n ? undefined\n : {\n name: path.basename(source.config.image),\n data: fs.readFileSync(path.resolve(root, source.config.image)),\n };\n const located = (name) =>\n source.prefix ? new URL(name, source.prefix).href : name;\n const dist = path.join(root, \"dist\");\n fs.rmSync(dist, { recursive: true, force: true });\n fs.mkdirSync(dist, { recursive: true });\n const entries = [...swiplets.keys()].map((id) => {\n const { manifest, data } = swiplets.get(id);\n const name = `${id}.swiplet`;\n fs.writeFileSync(path.join(dist, name), data);\n return {\n ...manifest,\n url: located(name),\n size: data.length,\n sha256: createHash(\"sha256\").update(data).digest(\"hex\"),\n };\n });\n if (image) {\n fs.writeFileSync(path.join(dist, image.name), image.data);\n }\n const index = {\n ...(source.config.name ? { name: source.config.name } : {}),\n ...(Object.keys(source.localizedNames).length > 0\n ? { localizedNames: source.localizedNames }\n : {}),\n ...(source.config.icon\n ? {\n icon: {\n symbol: source.config.icon.symbol,\n ...(source.config.icon.color\n ? { color: source.config.icon.color }\n : {}),\n ...(source.config.icon.symbolColor\n ? { symbolColor: source.config.icon.symbolColor }\n : {}),\n },\n }\n : {}),\n ...(image ? { image: located(image.name) } : {}),\n swiplets: entries,\n };\n fs.writeFileSync(\n path.join(dist, \"swiplets.json\"),\n `${JSON.stringify(index, null, 2)}\\n`,\n );\n console.log(path.relative(process.cwd(), path.join(dist, \"swiplets.json\")));\n}\n\nexport const source = defineCommand({\n name: \"source\",\n use: \"source [SWIPLET...]\",\n short: tr(\"Collect the built swiplets into dist/ with a swiplets.json\"),\n args: [0, Infinity],\n run: ({ args }) => sourceCommand(process.cwd(), args),\n});\n"],"mappings":";;;;;;;;AASA,MAAM,gBAAgB;AAEtB,SAAS,WAAW,MAAM;CACxB,MAAM,WAAW,KAAK,MACpB,GAAG,aAAa,KAAK,KAAK,MAAM,cAAc,GAAG,MAAM,CACzD;CACA,MAAM,SAAS,SAAS,UAAU,CAAC;CACnC,KAAK,MAAM,SAAS;EAAC;EAAQ;EAAS;CAAK,GACzC,IAAI,OAAO,WAAW,KAAA,KAAa,OAAO,OAAO,WAAW,UAC1D,MAAM,IAAI,MACR,GAAG,iDAA+C,EAChD,OAAO,UAAU,QACnB,CAAC,CACH;CAGJ,MAAM,iBAAiB,OAAO,kBAAkB,CAAC;CACjD,IACE,mBAAmB,QACnB,OAAO,mBAAmB,YAC1B,CAAC,OAAO,OAAO,cAAc,CAAC,CAAC,OAAO,SAAS,OAAO,SAAS,QAAQ,GAEvE,MAAM,IAAI,MACR,GACE,wEACF,CACF;CAEF,IACE,OAAO,SAAS,KAAA,MACf,OAAO,OAAO,MAAM,WAAW,YAC7B,OAAO,KA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UAAU;CACZ;CACA,GAAG,cACD,KAAK,KAAK,MAAM,eAAe,GAC/B,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE,GACpC;CACA,QAAQ,IAAI,KAAK,SAAS,QAAQ,IAAI,GAAG,KAAK,KAAK,MAAM,eAAe,CAAC,CAAC;AAC5E;AAEA,MAAa,SAAS,cAAc;CAClC,MAAM;CACN,KAAK;CACL,OAAO,GAAG,4DAA4D;CACtE,MAAM,CAAC,GAAG,QAAQ;CAClB,MAAM,EAAE,WAAW,cAAc,QAAQ,IAAI,GAAG,IAAI;AACtD,CAAC"}
|
|
1
|
+
{"version":3,"file":"source.js","names":[],"sources":["../../../../src/cli/commands/project/source.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { strFromU8, unzipSync } from \"fflate\";\n\nimport { tr } from \"../../../i18n\";\nimport { idPattern } from \"../../../project\";\nimport { defineCommand } from \"../../command\";\n\nfunction loadSource(root) {\n const manifest = JSON.parse(\n fs.readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n );\n const config = manifest.source ?? {};\n for (const field of [\"name\", \"image\", \"url\"]) {\n if (config[field] !== undefined && typeof config[field] !== \"string\") {\n throw new Error(\n tr('\"{field}\" in package.json must be a string.', {\n field: `source.${field}`,\n }),\n );\n }\n }\n const localizedNames = config.localizedNames ?? {};\n if (\n localizedNames === null ||\n typeof localizedNames !== \"object\" ||\n !Object.values(localizedNames).every((name) => typeof name === \"string\")\n ) {\n throw new Error(\n tr(\n '\"source.localizedNames\" in package.json must map languages to names.',\n ),\n );\n }\n if (\n config.icon !== undefined &&\n (typeof config.icon?.symbol !== \"string\" ||\n (config.icon.color !== undefined &&\n typeof config.icon.color !== \"string\"))\n ) {\n throw new Error(\n tr(\n '\"source.icon\" in package.json must have a symbol and may have a color.',\n ),\n );\n }\n if (\n config.icon?.symbolColor !== undefined &&\n typeof config.icon.symbolColor !== \"string\"\n ) {\n throw new Error(\n tr('\"{field}\" in package.json must be a string.', {\n field: \"source.icon.symbolColor\",\n }),\n );\n }\n let prefix;\n if (config.url !== undefined) {\n try {\n prefix = new URL(\n config.url.endsWith(\"/\") ? config.url : `${config.url}/`,\n );\n } catch {\n throw new Error(\n tr('\"source.url\" in package.json isn\\'t an absolute URL.'),\n );\n }\n }\n const workspaces = Array.isArray(manifest.workspaces)\n ? manifest.workspaces\n : (manifest.workspaces?.packages ?? []);\n return { root, config, localizedNames, prefix, workspaces };\n}\n\nfunction workspaceSwiplets(source) {\n const files = [];\n for (const pattern of source.workspaces) {\n for (const directory of fs.globSync(pattern, { cwd: source.root }).sort()) {\n const project = path.join(source.root, directory, \"package.json\");\n if (!fs.existsSync(project)) {\n continue;\n }\n const id = JSON.parse(fs.readFileSync(project, \"utf8\")).swiplet?.id;\n if (typeof id !== \"string\") {\n continue;\n }\n const built = path.join(source.root, directory, \"dist\", `${id}.swiplet`);\n if (!fs.existsSync(built)) {\n throw new Error(\n tr(\"{file} is missing; build {directory} first.\", {\n file: path.relative(source.root, built),\n directory,\n }),\n );\n }\n files.push(built);\n }\n }\n return files;\n}\n\nfunction readSwiplet(file) {\n const data = fs.readFileSync(file);\n let entry;\n try {\n entry = unzipSync(data, {\n filter: ({ name }) => name === \"manifest.json\",\n })[\"manifest.json\"];\n } catch (error) {\n throw new Error(`${file}: ${error.message}`);\n }\n if (entry === undefined) {\n throw new Error(`${file} has no manifest.json`);\n }\n const manifest = JSON.parse(strFromU8(entry));\n if (typeof manifest.id !== \"string\" || !idPattern.test(manifest.id)) {\n throw new Error(`${file} has no valid swiplet id in its manifest`);\n }\n return { file, manifest, data };\n}\n\nfunction sourceCommand(root, given) {\n const source = loadSource(root);\n const files =\n given.length > 0\n ? given.map((file) => path.resolve(file))\n : workspaceSwiplets(source);\n if (files.length === 0) {\n throw new Error(\n tr(\n \"package.json lists no workspaces with swiplets; name the swiplets to list.\",\n ),\n );\n }\n const swiplets = new Map();\n for (const read of files.map(readSwiplet)) {\n const { id } = read.manifest;\n if (swiplets.has(id)) {\n throw new Error(\n tr(\"{id} is both {first} and {second}\", {\n id,\n first: swiplets.get(id).file,\n second: read.file,\n }),\n );\n }\n swiplets.set(id, read);\n }\n const image =\n source.config.image === undefined\n ? undefined\n : {\n name: path.basename(source.config.image),\n data: fs.readFileSync(path.resolve(root, source.config.image)),\n };\n const located = (name) =>\n source.prefix ? new URL(name, source.prefix).href : name;\n const dist = path.join(root, \"dist\");\n fs.rmSync(dist, { recursive: true, force: true });\n fs.mkdirSync(dist, { recursive: true });\n const entries = [...swiplets.keys()].map((id) => {\n const { manifest, data } = swiplets.get(id);\n const name = `${id}.swiplet`;\n fs.writeFileSync(path.join(dist, name), data);\n return {\n ...manifest,\n url: located(name),\n size: data.length,\n sha256: createHash(\"sha256\").update(data).digest(\"hex\"),\n };\n });\n if (image) {\n fs.writeFileSync(path.join(dist, image.name), image.data);\n }\n const index = {\n ...(source.config.name ? { name: source.config.name } : {}),\n ...(Object.keys(source.localizedNames).length > 0\n ? { localizedNames: source.localizedNames }\n : {}),\n ...(source.config.icon\n ? {\n icon: {\n symbol: source.config.icon.symbol,\n ...(source.config.icon.color\n ? { color: source.config.icon.color }\n : {}),\n ...(source.config.icon.symbolColor\n ? { symbolColor: source.config.icon.symbolColor }\n : {}),\n },\n }\n : {}),\n ...(image ? { image: located(image.name) } : {}),\n swiplets: entries,\n };\n fs.writeFileSync(\n path.join(dist, \"swiplets.json\"),\n `${JSON.stringify(index, null, 2)}\\n`,\n );\n console.log(path.relative(process.cwd(), path.join(dist, \"swiplets.json\")));\n}\n\nexport const source = defineCommand({\n name: \"source\",\n use: \"source [SWIPLET...]\",\n short: tr(\"Collect the built swiplets into dist/ with a swiplets.json\"),\n args: [0, Infinity],\n run: ({ args }) => sourceCommand(process.cwd(), args),\n});\n"],"mappings":";;;;;;;;AAUA,SAAS,WAAW,MAAM;CACxB,MAAM,WAAW,KAAK,MACpB,GAAG,aAAa,KAAK,KAAK,MAAM,cAAc,GAA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KAAK,OAAO,cAAc,CAAC,CAAC,SAAS,IAC5C,EAAE,gBAAgB,OAAO,eAAe,IACxC,CAAC;EACL,GAAI,OAAO,OAAO,OACd,EACE,MAAM;GACJ,QAAQ,OAAO,OAAO,KAAK;GAC3B,GAAI,OAAO,OAAO,KAAK,QACnB,EAAE,OAAO,OAAO,OAAO,KAAK,MAAM,IAClC,CAAC;GACL,GAAI,OAAO,OAAO,KAAK,cACnB,EAAE,aAAa,OAAO,OAAO,KAAK,YAAY,IAC9C,CAAC;EACP,EACF,IACA,CAAC;EACL,GAAI,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,EAAE,IAAI,CAAC;EAC9C,UAAU;CACZ;CACA,GAAG,cACD,KAAK,KAAK,MAAM,eAAe,GAC/B,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE,GACpC;CACA,QAAQ,IAAI,KAAK,SAAS,QAAQ,IAAI,GAAG,KAAK,KAAK,MAAM,eAAe,CAAC,CAAC;AAC5E;AAEA,MAAa,SAAS,cAAc;CAClC,MAAM;CACN,KAAK;CACL,OAAO,GAAG,4DAA4D;CACtE,MAAM,CAAC,GAAG,QAAQ;CAClB,MAAM,EAAE,WAAW,cAAc,QAAQ,IAAI,GAAG,IAAI;AACtD,CAAC"}
|
|
@@ -4,7 +4,7 @@ import { session } from "../../session.js";
|
|
|
4
4
|
// src/cli/commands/swiplet/remove.ts
|
|
5
5
|
const removeSwiplet = (context) => session(context, async (client) => {
|
|
6
6
|
await client.swiplets.removeSwiplet({ swipletId: context.args[0] }, { signal: context.signal });
|
|
7
|
-
console.log(tr("removed {name}", { name: context.args[0] }));
|
|
7
|
+
console.log(tr("removed {name}", { name: context.args[0] }, "Swiplet"));
|
|
8
8
|
});
|
|
9
9
|
const remove = defineCommand({
|
|
10
10
|
name: "remove",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remove.js","names":[],"sources":["../../../../src/cli/commands/swiplet/remove.ts"],"sourcesContent":["import { tr } from \"../../../i18n\";\nimport { defineCommand } from \"../../command\";\nimport { session } from \"../../session\";\n\nconst removeSwiplet = (context) =>\n session(context, async (client) => {\n await client.swiplets.removeSwiplet(\n { swipletId: context.args[0] },\n { signal: context.signal },\n );\n console.log(tr(\"removed {name}\", { name: context.args[0] }));\n });\n\nexport const remove = defineCommand({\n name: \"remove\",\n use: \"remove ID\",\n short: tr(\"Remove a swiplet\"),\n args: [1, 1],\n run: removeSwiplet,\n});\n"],"mappings":";;;;AAIA,MAAM,iBAAiB,YACrB,QAAQ,SAAS,OAAO,WAAW;CACjC,MAAM,OAAO,SAAS,cACpB,EAAE,WAAW,QAAQ,KAAK,GAAG,GAC7B,EAAE,QAAQ,QAAQ,OAAO,CAC3B;CACA,QAAQ,IAAI,GAAG,kBAAkB,EAAE,MAAM,QAAQ,KAAK,GAAG,
|
|
1
|
+
{"version":3,"file":"remove.js","names":[],"sources":["../../../../src/cli/commands/swiplet/remove.ts"],"sourcesContent":["import { tr } from \"../../../i18n\";\nimport { defineCommand } from \"../../command\";\nimport { session } from \"../../session\";\n\nconst removeSwiplet = (context) =>\n session(context, async (client) => {\n await client.swiplets.removeSwiplet(\n { swipletId: context.args[0] },\n { signal: context.signal },\n );\n console.log(tr(\"removed {name}\", { name: context.args[0] }, \"Swiplet\"));\n });\n\nexport const remove = defineCommand({\n name: \"remove\",\n use: \"remove ID\",\n short: tr(\"Remove a swiplet\"),\n args: [1, 1],\n run: removeSwiplet,\n});\n"],"mappings":";;;;AAIA,MAAM,iBAAiB,YACrB,QAAQ,SAAS,OAAO,WAAW;CACjC,MAAM,OAAO,SAAS,cACpB,EAAE,WAAW,QAAQ,KAAK,GAAG,GAC7B,EAAE,QAAQ,QAAQ,OAAO,CAC3B;CACA,QAAQ,IAAI,GAAG,kBAAkB,EAAE,MAAM,QAAQ,KAAK,GAAG,GAAG,SAAS,CAAC;AACxE,CAAC;AAEH,MAAa,SAAS,cAAc;CAClC,MAAM;CACN,KAAK;CACL,OAAO,GAAG,kBAAkB;CAC5B,MAAM,CAAC,GAAG,CAAC;CACX,KAAK;AACP,CAAC"}
|
package/dist/client.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { resolveHost } from "./mdns.js";
|
|
1
2
|
import { LogService } from "./proto/logs_pb.js";
|
|
2
3
|
import { REPLService } from "./proto/repl_pb.js";
|
|
3
4
|
import { SwipletService } from "./proto/swiplets_pb.js";
|
|
@@ -7,6 +8,7 @@ import dns from "node:dns";
|
|
|
7
8
|
import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
|
|
8
9
|
// src/client.ts
|
|
9
10
|
const largestMessage = 128 << 20;
|
|
11
|
+
const resolveLimit = 5e3;
|
|
10
12
|
const contentType = "application/grpc-web+proto";
|
|
11
13
|
const webSocketSubprotocol = "grpc-websockets";
|
|
12
14
|
const { apiLevel } = createRequire(import.meta.url)("@swipt/api/package.json");
|
|
@@ -52,6 +54,24 @@ const transportError = (error) => {
|
|
|
52
54
|
if (error?.name === "AbortError") return new RpcError(Code.Canceled, "the call was canceled");
|
|
53
55
|
return new RpcError(Code.Unavailable, causeText(error?.cause) || error?.message || String(error));
|
|
54
56
|
};
|
|
57
|
+
async function locate(connection, signal) {
|
|
58
|
+
const url = new URL(connection.url);
|
|
59
|
+
if (!url.hostname.endsWith(".local")) return connection.url;
|
|
60
|
+
let address;
|
|
61
|
+
try {
|
|
62
|
+
address = await resolveHost(url.hostname, AbortSignal.any([...signal ? [signal] : [], AbortSignal.timeout(resolveLimit)]));
|
|
63
|
+
} catch (error) {
|
|
64
|
+
throw transportError(error);
|
|
65
|
+
}
|
|
66
|
+
if (signal?.aborted) throw new RpcError(Code.Canceled, "the call was canceled");
|
|
67
|
+
if (address === void 0) throw new RpcError(Code.Unavailable, `${url.hostname} isn't found on the local network`);
|
|
68
|
+
url.hostname = address.includes(":") ? `[${address}]` : address;
|
|
69
|
+
return url.href.replace(/\/+$/, "");
|
|
70
|
+
}
|
|
71
|
+
async function base(connection, signal) {
|
|
72
|
+
connection.resolved ??= await locate(connection, signal);
|
|
73
|
+
return connection.resolved;
|
|
74
|
+
}
|
|
55
75
|
function frame(schema, init) {
|
|
56
76
|
const body = toBinary(schema, create(schema, init));
|
|
57
77
|
const out = Buffer.allocUnsafe(5 + body.length);
|
|
@@ -106,7 +126,7 @@ function requestHeaders(connection) {
|
|
|
106
126
|
async function* invokeHTTP(connection, method, input, { signal }) {
|
|
107
127
|
let response;
|
|
108
128
|
try {
|
|
109
|
-
response = await fetch(`${connection
|
|
129
|
+
response = await fetch(`${await base(connection, signal)}/${method.parent.typeName}/${method.name}`, {
|
|
110
130
|
method: "POST",
|
|
111
131
|
headers: requestHeaders(connection),
|
|
112
132
|
body: frame(method.input, input),
|
|
@@ -138,7 +158,8 @@ async function* invokeHTTP(connection, method, input, { signal }) {
|
|
|
138
158
|
}
|
|
139
159
|
async function* invokeWebSocket(connection, method, input, { signal }) {
|
|
140
160
|
if (signal?.aborted) throw new RpcError(Code.Canceled, "the call was canceled");
|
|
141
|
-
const
|
|
161
|
+
const webSocketBase = (await base(connection, signal)).replace(/^http/, "ws");
|
|
162
|
+
const socket = new WebSocket(`${webSocketBase}/${method.parent.typeName}/${method.name}`, [webSocketSubprotocol]);
|
|
142
163
|
socket.binaryType = "arraybuffer";
|
|
143
164
|
const reader = new FrameReader(method.output);
|
|
144
165
|
const messages = [];
|
|
@@ -159,7 +180,7 @@ async function* invokeWebSocket(connection, method, input, { signal }) {
|
|
|
159
180
|
const abort = () => fail(new RpcError(Code.Canceled, "the call was canceled"));
|
|
160
181
|
const opened = new Promise((resolve, reject) => {
|
|
161
182
|
socket.addEventListener("open", resolve, { once: true });
|
|
162
|
-
socket.addEventListener("close", () => reject(failure ?? new RpcError(Code.Unavailable, `cannot connect to ${
|
|
183
|
+
socket.addEventListener("close", () => reject(failure ?? new RpcError(Code.Unavailable, `cannot connect to ${webSocketBase}`)), { once: true });
|
|
163
184
|
});
|
|
164
185
|
socket.addEventListener("message", (event) => {
|
|
165
186
|
try {
|
|
@@ -180,7 +201,7 @@ async function* invokeWebSocket(connection, method, input, { signal }) {
|
|
|
180
201
|
notify();
|
|
181
202
|
});
|
|
182
203
|
socket.addEventListener("error", () => {
|
|
183
|
-
failure ??= new RpcError(Code.Unavailable, `cannot connect to ${
|
|
204
|
+
failure ??= new RpcError(Code.Unavailable, `cannot connect to ${webSocketBase}`);
|
|
184
205
|
});
|
|
185
206
|
signal?.addEventListener("abort", abort, { once: true });
|
|
186
207
|
try {
|
|
@@ -234,9 +255,9 @@ function bind(service, connection) {
|
|
|
234
255
|
}
|
|
235
256
|
function open({ url, token }) {
|
|
236
257
|
const connection = {
|
|
258
|
+
url,
|
|
237
259
|
token,
|
|
238
|
-
|
|
239
|
-
webSocketBase: url.replace(/^http/, "ws")
|
|
260
|
+
resolved: void 0
|
|
240
261
|
};
|
|
241
262
|
return {
|
|
242
263
|
system: bind(SystemService, connection),
|