@swipt/cli 0.1.0-nightly.78 → 0.1.0-nightly.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/availability.d.ts +5 -0
  2. package/dist/availability.js +349 -0
  3. package/dist/availability.js.map +1 -0
  4. package/dist/client.d.ts +25 -0
  5. package/dist/client.js +248 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/connection.d.ts +24 -0
  8. package/dist/connection.js +293 -0
  9. package/dist/connection.js.map +1 -0
  10. package/dist/coredevice.d.ts +22 -0
  11. package/dist/coredevice.js +329 -0
  12. package/dist/coredevice.js.map +1 -0
  13. package/dist/device.d.ts +130 -0
  14. package/dist/device.js +539 -0
  15. package/dist/device.js.map +1 -0
  16. package/dist/i18n.d.ts +2 -0
  17. package/dist/i18n.js +57 -0
  18. package/dist/i18n.js.map +1 -0
  19. package/dist/ignore.d.ts +8 -0
  20. package/dist/ignore.js +112 -0
  21. package/dist/ignore.js.map +1 -0
  22. package/dist/metro.d.ts +10 -0
  23. package/dist/metro.js +349 -0
  24. package/dist/metro.js.map +1 -0
  25. package/dist/output.d.ts +20 -0
  26. package/dist/output.js +116 -0
  27. package/dist/output.js.map +1 -0
  28. package/dist/project.d.ts +18 -0
  29. package/dist/project.js +696 -0
  30. package/dist/project.js.map +1 -0
  31. package/dist/proto/common_pb.js +34 -0
  32. package/dist/proto/common_pb.js.map +1 -0
  33. package/dist/proto/logs_pb.js +15 -0
  34. package/dist/proto/logs_pb.js.map +1 -0
  35. package/dist/proto/repl_pb.js +15 -0
  36. package/dist/proto/repl_pb.js.map +1 -0
  37. package/dist/proto/swiplets_pb.js +28 -0
  38. package/dist/proto/swiplets_pb.js.map +1 -0
  39. package/dist/proto/system_pb.js +15 -0
  40. package/dist/proto/system_pb.js.map +1 -0
  41. package/dist/sideload.d.ts +17 -0
  42. package/dist/sideload.js +1098 -0
  43. package/dist/sideload.js.map +1 -0
  44. package/dist/swipt.d.ts +1 -0
  45. package/dist/swipt.js +631 -0
  46. package/dist/swipt.js.map +1 -0
  47. package/dist/version.d.ts +2 -0
  48. package/dist/version.js +15 -0
  49. package/dist/version.js.map +1 -0
  50. package/package.json +21 -7
  51. package/availability.mjs +0 -642
  52. package/client.mjs +0 -375
  53. package/connection.mjs +0 -450
  54. package/coredevice.mjs +0 -464
  55. package/device.mjs +0 -837
  56. package/i18n.mjs +0 -71
  57. package/ignore.mjs +0 -149
  58. package/metro.mjs +0 -432
  59. package/output.mjs +0 -177
  60. package/project.mjs +0 -1013
  61. package/proto/common_pb.js +0 -98
  62. package/proto/logs_pb.js +0 -34
  63. package/proto/repl_pb.js +0 -55
  64. package/proto/swiplets_pb.js +0 -179
  65. package/proto/system_pb.js +0 -27
  66. package/sideload.mjs +0 -1696
  67. package/swipt.mjs +0 -726
  68. package/version.mjs +0 -16
@@ -0,0 +1,696 @@
1
+ #!/usr/bin/env node
2
+ import { AvailabilityChecker } from "./availability.js";
3
+ import { tr } from "./i18n.js";
4
+ import { loadEnvironment, metro } from "./metro.js";
5
+ import { parseVersion, versionAtLeast } from "./version.js";
6
+ import { createRequire } from "node:module";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { execFileSync } from "node:child_process";
10
+ import { createHash } from "node:crypto";
11
+ import vm from "node:vm";
12
+ import { transformAsync } from "@babel/core";
13
+ import { build } from "esbuild";
14
+ // src/project.ts
15
+ const { version } = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
16
+ const require = createRequire(import.meta.url);
17
+ const { peerDependencies } = require("@swipt/api/package.json");
18
+ const appModules = [
19
+ "react",
20
+ "react/jsx-runtime",
21
+ "react-native",
22
+ "react-native-worklets",
23
+ "expo",
24
+ "expo-localization",
25
+ "expo-maps",
26
+ "@expo/ui",
27
+ "@expo/ui/*",
28
+ "@swipt/api",
29
+ "@swipt/api/swiplet",
30
+ "@swipt/api/file-system",
31
+ "@swipt/api/localization",
32
+ "@swipt/api/maps",
33
+ "@swipt/api/http",
34
+ "@swipt/api/app-intents",
35
+ "expo-sqlite",
36
+ "expo-sqlite/kv-store",
37
+ "expo-sqlite/localStorage/install"
38
+ ];
39
+ const extensionModules = [
40
+ "@swipt/api",
41
+ "@swipt/api/swiplet",
42
+ "@swipt/api/file-system",
43
+ "@swipt/api/accessibility",
44
+ "@swipt/api/input",
45
+ "@swipt/api/device",
46
+ "@swipt/api/screen",
47
+ "@swipt/api/image",
48
+ "@swipt/api/app-intents",
49
+ "@swipt/api/localization",
50
+ "@swipt/api/http",
51
+ "expo-sqlite",
52
+ "expo-sqlite/kv-store",
53
+ "expo-sqlite/localStorage/install"
54
+ ];
55
+ const idPattern = /^[a-z0-9][a-z0-9._-]{0,127}$/;
56
+ const storedSuffixes = [
57
+ ".webp",
58
+ ".jxl",
59
+ ".avif",
60
+ ".heic",
61
+ ".heif",
62
+ ".jpg",
63
+ ".jpeg",
64
+ ".png",
65
+ ".gif",
66
+ ".mp4",
67
+ ".mov",
68
+ ".m4a",
69
+ ".mp3",
70
+ ".aac",
71
+ ".zip",
72
+ ".gz",
73
+ ".br",
74
+ ".zst",
75
+ ".xz"
76
+ ].join(":");
77
+ function loadProject(root) {
78
+ const manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
79
+ const config = manifest.swiplet ?? {};
80
+ if (typeof config.id !== "string" || !idPattern.test(config.id)) throw new Error(tr("\"swiplet.id\" in package.json must be 1 to 128 lowercase letters, digits, dots, underscores and hyphens starting with a letter or a digit"));
81
+ if (typeof config.name !== "string" || config.name === "") throw new Error(tr("\"swiplet.name\" in package.json must be a non-empty string"));
82
+ const localizedNames = config.localizedNames ?? {};
83
+ if (localizedNames === null || typeof localizedNames !== "object" || !Object.values(localizedNames).every((name) => typeof name === "string")) throw new Error(tr("\"swiplet.localizedNames\" in package.json must map languages to names"));
84
+ for (const field of ["description", "updateURL"]) if (config[field] !== void 0 && typeof config[field] !== "string") throw new Error(tr("\"{field}\" in package.json must be a string", { field: `swiplet.${field}` }));
85
+ if (config.versionCode !== void 0 && (!Number.isInteger(config.versionCode) || config.versionCode < 1)) throw new Error(tr("\"swiplet.versionCode\" in package.json must be a positive integer"));
86
+ const apiManifest = require.resolve("@swipt/api/package.json", { paths: [root, import.meta.dirname] });
87
+ const { apiLevel, oldestAPILevel = 1, minimumIOSVersion = 27 } = JSON.parse(fs.readFileSync(apiManifest, "utf8"));
88
+ if (config.minimumAPILevel !== void 0 && !(Number.isInteger(config.minimumAPILevel) && config.minimumAPILevel >= oldestAPILevel && config.minimumAPILevel <= apiLevel)) throw new Error(tr("\"swiplet.minimumAPILevel\" in package.json must be an integer from {oldest} to {level}, the API level of @swipt/api", {
89
+ oldest: oldestAPILevel,
90
+ level: apiLevel
91
+ }));
92
+ const version = parseVersion(config.minimumIOSVersion);
93
+ if (config.minimumIOSVersion !== void 0 && !(typeof config.minimumIOSVersion === "number" && version && versionAtLeast(version, parseVersion(minimumIOSVersion)))) throw new Error(tr("\"swiplet.minimumIOSVersion\" in package.json must be a version number from {version}, the minimum iOS version of @swipt/api", { version: minimumIOSVersion }));
94
+ const entry = (name) => config[name] === void 0 ? void 0 : path.resolve(root, config[name]);
95
+ return {
96
+ root,
97
+ manifest,
98
+ config,
99
+ localizedNames,
100
+ apiLevel,
101
+ minimumIOSVersion,
102
+ apiDirectory: path.dirname(apiManifest),
103
+ app: entry("app"),
104
+ extension: entry("extension")
105
+ };
106
+ }
107
+ const typeImport = (extension) => ({
108
+ name: "swiplet-type-import",
109
+ setup(build) {
110
+ build.onLoad({ filter: /.*/ }, (args) => {
111
+ if (args.path !== extension) return;
112
+ return { errors: [{ text: tr("the interface imports {file} at run time; import its type with `import type`", { file: path.basename(extension) }) }] };
113
+ });
114
+ }
115
+ });
116
+ async function bundle(project) {
117
+ const out = {
118
+ app: "",
119
+ extension: "",
120
+ extensionMap: "",
121
+ assets: /* @__PURE__ */ new Map(),
122
+ metafiles: []
123
+ };
124
+ loadEnvironment(project.root);
125
+ if (project.extension) {
126
+ const outfile = path.join(project.root, "dist", project.config.id, "src", "extension.js");
127
+ const result = await build({
128
+ entryPoints: [project.extension],
129
+ outfile,
130
+ bundle: true,
131
+ format: "cjs",
132
+ platform: "neutral",
133
+ mainFields: ["module", "main"],
134
+ target: "es2022",
135
+ external: extensionModules,
136
+ sourcemap: "external",
137
+ sourcesContent: false,
138
+ write: false,
139
+ metafile: true,
140
+ logLevel: "silent",
141
+ plugins: [metro(project.root, { sourcemap: true })]
142
+ });
143
+ out.metafiles.push(result.metafile);
144
+ out.extension = result.outputFiles.find((file) => file.path.endsWith(".js")).text;
145
+ const map = JSON.parse(result.outputFiles.find((file) => file.path.endsWith(".map")).text);
146
+ const sources = map.sources.map((source) => path.relative(project.root, path.resolve(path.dirname(outfile), map.sourceRoot ?? "", source)).split(path.sep).join("/"));
147
+ out.extensionMap = JSON.stringify({
148
+ ...map,
149
+ sourceRoot: void 0,
150
+ sources
151
+ });
152
+ }
153
+ if (project.app) {
154
+ const result = await build({
155
+ entryPoints: [project.app],
156
+ bundle: true,
157
+ format: "cjs",
158
+ platform: "neutral",
159
+ mainFields: [
160
+ "react-native",
161
+ "browser",
162
+ "module",
163
+ "main"
164
+ ],
165
+ conditions: ["react-native"],
166
+ resolveExtensions: [
167
+ ".ios.tsx",
168
+ ".ios.ts",
169
+ ".native.tsx",
170
+ ".native.ts",
171
+ ".tsx",
172
+ ".ts",
173
+ ".ios.jsx",
174
+ ".ios.js",
175
+ ".native.js",
176
+ ".jsx",
177
+ ".js",
178
+ ".json"
179
+ ],
180
+ jsx: "automatic",
181
+ target: "es2020",
182
+ define: {
183
+ "process.env.NODE_ENV": "\"production\"",
184
+ __DEV__: "false"
185
+ },
186
+ external: appModules,
187
+ write: false,
188
+ metafile: true,
189
+ logLevel: "silent",
190
+ plugins: [...project.extension ? [typeImport(project.extension)] : [], metro(project.root, { assets: out.assets })]
191
+ });
192
+ out.metafiles.push(result.metafile);
193
+ out.app = (await transformAsync(result.outputFiles[0].text, {
194
+ babelrc: false,
195
+ configFile: false,
196
+ sourceType: "script",
197
+ compact: false,
198
+ plugins: [require.resolve("@babel/plugin-transform-block-scoping")]
199
+ })).code;
200
+ }
201
+ if (out.app === "" && out.extension === "") throw new Error(tr("package.json names neither \"swiplet.app\" nor \"swiplet.extension\""));
202
+ return out;
203
+ }
204
+ const definitionKey = Symbol("definition");
205
+ function describeExtension(source) {
206
+ if (source === "") return {
207
+ service: false,
208
+ actions: []
209
+ };
210
+ const [newer, older] = [true, false].map((result) => evaluateExtension(source, result));
211
+ if (JSON.stringify(newer) !== JSON.stringify(older)) throw new Error(tr("the extension defines different actions depending on available(); define the same actions on every system and check available() inside run or an action"));
212
+ return newer;
213
+ }
214
+ function evaluateExtension(source, availableResult) {
215
+ const loading = (name) => {
216
+ const fail = () => {
217
+ throw new Error(tr("{name} is used while extension.js loads; use it inside run or an action", { name }));
218
+ };
219
+ const get = (_, key) => key === "__esModule" ? true : typeof key === "symbol" || key === "then" ? void 0 : fail();
220
+ return new Proxy(fail, {
221
+ get,
222
+ apply: fail,
223
+ construct: fail
224
+ });
225
+ };
226
+ const modules = {
227
+ "@swipt/api": { available: () => availableResult },
228
+ "@swipt/api/swiplet": {
229
+ defineExtension: (definition) => ({ [definitionKey]: definition }),
230
+ defineAction: (definition) => definition,
231
+ actions: loading("actions"),
232
+ useService: loading("useService")
233
+ },
234
+ "@swipt/api/file-system": {
235
+ get dataDirectory() {
236
+ throw new Error(tr("{name} is used while extension.js loads; use it inside run or an action", { name: "dataDirectory" }));
237
+ },
238
+ get cacheDirectory() {
239
+ throw new Error(tr("{name} is used while extension.js loads; use it inside run or an action", { name: "cacheDirectory" }));
240
+ },
241
+ get assets() {
242
+ throw new Error(tr("{name} is used while extension.js loads; use it inside run or an action", { name: "assets" }));
243
+ }
244
+ },
245
+ "@swipt/api/accessibility": loading("accessibility"),
246
+ "@swipt/api/input": loading("input"),
247
+ "@swipt/api/device": loading("device"),
248
+ "@swipt/api/screen": loading("screen"),
249
+ "@swipt/api/image": loading("image"),
250
+ "@swipt/api/app-intents": loading("appIntents"),
251
+ "@swipt/api/http": {
252
+ Client: function Client() {
253
+ return loading("Client");
254
+ },
255
+ CookieJar: function CookieJar() {
256
+ return loading("CookieJar");
257
+ }
258
+ },
259
+ "@swipt/api/localization": { preferredLocalizations: (localizations) => localizations.includes("en") ? ["en"] : localizations.slice(0, 1) },
260
+ "expo-sqlite": {
261
+ SQLiteDatabase: loading("SQLiteDatabase"),
262
+ SQLiteStatement: loading("SQLiteStatement"),
263
+ SQLiteTaggedQuery: loading("SQLiteTaggedQuery"),
264
+ SQLiteSession: loading("SQLiteSession"),
265
+ openDatabaseSync: () => loading(tr("the database")),
266
+ openDatabaseAsync: () => Promise.resolve(loading(tr("the database"))),
267
+ deserializeDatabaseSync: () => loading(tr("the database")),
268
+ deserializeDatabaseAsync: () => Promise.resolve(loading(tr("the database"))),
269
+ deleteDatabaseSync: () => {},
270
+ deleteDatabaseAsync: () => Promise.resolve(),
271
+ backupDatabaseSync: () => {},
272
+ backupDatabaseAsync: () => Promise.resolve(),
273
+ importDatabaseFromAssetAsync: () => Promise.resolve(),
274
+ addDatabaseChangeListener: () => ({ remove: () => {} }),
275
+ defaultDatabaseDirectory: "",
276
+ bundledExtensions: {},
277
+ configureWeb: () => {},
278
+ deepEqual: function deepEqual(a, b) {
279
+ if (a === b) return true;
280
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
281
+ const keys = Object.keys(a);
282
+ return keys.length === Object.keys(b).length && keys.every((key) => deepEqual(a[key], b[key]));
283
+ },
284
+ SQLiteProvider: () => {
285
+ throw new Error(tr("SQLiteProvider renders React, so it works only in the swiplet interface"));
286
+ },
287
+ useSQLiteContext: () => {
288
+ throw new Error(tr("useSQLiteContext renders React, so it works only in the swiplet interface"));
289
+ }
290
+ },
291
+ "expo-sqlite/kv-store": {
292
+ SQLiteStorage: loading("SQLiteStorage"),
293
+ AsyncStorage: loading(tr("the storage")),
294
+ Storage: loading(tr("the storage")),
295
+ default: loading(tr("the storage"))
296
+ },
297
+ get "expo-sqlite/localStorage/install"() {
298
+ context.localStorage = loading("localStorage");
299
+ return {};
300
+ }
301
+ };
302
+ const ignored = () => 0;
303
+ const context = vm.createContext({
304
+ console,
305
+ URL,
306
+ URLSearchParams,
307
+ TextEncoder,
308
+ TextDecoder,
309
+ atob,
310
+ btoa,
311
+ structuredClone,
312
+ queueMicrotask,
313
+ crypto,
314
+ AbortController,
315
+ AbortSignal,
316
+ Event,
317
+ EventTarget,
318
+ CustomEvent,
319
+ DOMException,
320
+ Blob,
321
+ ...Object.fromEntries([
322
+ "MessageEvent",
323
+ "CloseEvent",
324
+ "ErrorEvent",
325
+ "File",
326
+ "FormData",
327
+ "Headers",
328
+ "Request",
329
+ "Response",
330
+ "WebSocket",
331
+ "EventSource",
332
+ "ReadableStream",
333
+ "ReadableStreamDefaultReader",
334
+ "ReadableStreamBYOBReader",
335
+ "ReadableStreamBYOBRequest",
336
+ "ReadableStreamDefaultController",
337
+ "ReadableByteStreamController",
338
+ "WritableStream",
339
+ "WritableStreamDefaultWriter",
340
+ "WritableStreamDefaultController",
341
+ "TransformStream",
342
+ "TransformStreamDefaultController",
343
+ "ByteLengthQueuingStrategy",
344
+ "CountQueuingStrategy",
345
+ "TextEncoderStream",
346
+ "TextDecoderStream",
347
+ "CompressionStream",
348
+ "DecompressionStream",
349
+ "performance",
350
+ "Performance",
351
+ "PerformanceEntry",
352
+ "PerformanceMark",
353
+ "PerformanceMeasure",
354
+ "PerformanceObserver",
355
+ "PerformanceObserverEntryList"
356
+ ].map((name) => [name, globalThis[name]])),
357
+ fetch: loading("fetch"),
358
+ setTimeout: ignored,
359
+ setInterval: ignored,
360
+ clearTimeout: ignored,
361
+ clearInterval: ignored,
362
+ navigator: {
363
+ userAgent: "Swipt",
364
+ language: "en",
365
+ languages: ["en"]
366
+ }
367
+ });
368
+ const factory = vm.runInContext(`(function (require, module, exports) {${source}\n})`, context, { filename: "extension.js" });
369
+ const module = { exports: {} };
370
+ factory((specifier) => {
371
+ if (!Object.hasOwn(modules, specifier)) throw new Error(tr("Swipt doesn't provide \"{module}\" to extensions; bundle it into extension.js", { module: specifier }));
372
+ return modules[specifier];
373
+ }, module, module.exports);
374
+ const definition = (module.exports.default ?? module.exports)?.[definitionKey];
375
+ if (definition === void 0) throw new Error(tr("the extension's default export is not the result of defineExtension"));
376
+ const schema = (name, value, side) => {
377
+ if (value === void 0) return;
378
+ const converter = value?.["~standard"]?.jsonSchema;
379
+ if (typeof converter?.[side] !== "function") throw new Error(tr("the {side} schema of the action {action} doesn't implement Standard JSON Schema; use a library that does, such as Zod 4", {
380
+ side,
381
+ action: JSON.stringify(name)
382
+ }));
383
+ return converter[side]({ target: "draft-2020-12" });
384
+ };
385
+ const actions = Object.entries(definition.actions ?? {}).map(([name, action]) => {
386
+ if (typeof action?.title !== "string" || action.title === "") throw new Error(tr("the action {action} needs a title", { action: JSON.stringify(name) }));
387
+ const expose = action.expose ?? [];
388
+ if (!Array.isArray(expose) || !expose.every((caller) => caller === "shortcuts")) throw new Error(tr("the action {action} can only expose itself to \"shortcuts\"", { action: JSON.stringify(name) }));
389
+ return {
390
+ name,
391
+ title: action.title,
392
+ ...action.description ? { description: action.description } : {},
393
+ ...expose.length > 0 ? { expose } : {},
394
+ ...action.input ? { input: schema(name, action.input, "input") } : {},
395
+ ...action.output ? { output: schema(name, action.output, "output") } : {}
396
+ };
397
+ });
398
+ return {
399
+ service: typeof definition.run === "function",
400
+ actions
401
+ };
402
+ }
403
+ function swipletManifest(project, output) {
404
+ const { service, actions } = describeExtension(output.extension);
405
+ const { config, localizedNames } = project;
406
+ return {
407
+ id: config.id,
408
+ name: config.name,
409
+ ...Object.keys(localizedNames).length > 0 ? { localizedNames } : {},
410
+ ...config.description ? { description: config.description } : {},
411
+ ...project.manifest.version ? { version: project.manifest.version } : {},
412
+ ...config.versionCode ? { versionCode: config.versionCode } : {},
413
+ ...config.icon ? { icon: config.icon } : {},
414
+ ...config.updateURL ? { updateURL: config.updateURL } : {},
415
+ minimumAPILevel: config.minimumAPILevel ?? project.apiLevel,
416
+ minimumIOSVersion: config.minimumIOSVersion ?? project.minimumIOSVersion,
417
+ ...output.app ? { interface: true } : {},
418
+ ...service ? { service } : {},
419
+ ...actions.length > 0 ? { actions } : {}
420
+ };
421
+ }
422
+ const sourceFiles = (output) => ({
423
+ ...output.app ? { "app.js": output.app } : {},
424
+ ...output.extension ? { "extension.js": output.extension } : {}
425
+ });
426
+ async function buildProject(root, checker) {
427
+ const project = loadProject(root);
428
+ const output = await bundle(project);
429
+ if (checker === void 0) {
430
+ const owned = new AvailabilityChecker();
431
+ try {
432
+ owned.check(project, output.metafiles);
433
+ } finally {
434
+ owned.close();
435
+ }
436
+ } else checker.check(project, output.metafiles);
437
+ const manifest = swipletManifest(project, output);
438
+ const dist = path.join(root, "dist");
439
+ const folder = path.join(dist, manifest.id);
440
+ fs.rmSync(folder, {
441
+ recursive: true,
442
+ force: true
443
+ });
444
+ fs.mkdirSync(path.join(folder, "src"), { recursive: true });
445
+ fs.writeFileSync(path.join(folder, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
446
+ for (const [file, contents] of Object.entries(sourceFiles(output))) fs.writeFileSync(path.join(folder, "src", file), contents);
447
+ if (output.extensionMap) fs.writeFileSync(path.join(folder, "src", "extension.js.map"), output.extensionMap);
448
+ if (fs.existsSync(path.join(root, "icon.png"))) fs.copyFileSync(path.join(root, "icon.png"), path.join(folder, "icon.png"));
449
+ if (fs.existsSync(path.join(root, "assets"))) fs.cpSync(path.join(root, "assets"), path.join(folder, "assets"), {
450
+ recursive: true,
451
+ filter: (source) => !path.basename(source).startsWith(".")
452
+ });
453
+ for (const [name, source] of output.assets) {
454
+ const target = path.join(folder, "assets", name);
455
+ if (fs.existsSync(target)) throw new Error(tr("{source} and {asset} would both be assets/{name} in the swiplet", {
456
+ source: path.relative(root, source),
457
+ asset: path.join("assets", name),
458
+ name
459
+ }));
460
+ fs.mkdirSync(path.dirname(target), { recursive: true });
461
+ fs.copyFileSync(source, target);
462
+ }
463
+ const archive = path.join(dist, `${manifest.id}.swiplet`);
464
+ fs.rmSync(archive, { force: true });
465
+ fs.rmSync(path.join(dist, `${manifest.id}.zip`), { force: true });
466
+ execFileSync("zip", [
467
+ "-qr",
468
+ "-n",
469
+ storedSuffixes,
470
+ archive,
471
+ ...fs.readdirSync(folder)
472
+ ], { cwd: folder });
473
+ return {
474
+ id: manifest.id,
475
+ archive,
476
+ digest: folderDigest(folder)
477
+ };
478
+ }
479
+ function folderDigest(folder) {
480
+ const hash = createHash("sha256");
481
+ const walk = (directory) => {
482
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) {
483
+ const name = path.join(directory, entry.name);
484
+ if (entry.isDirectory()) walk(name);
485
+ else {
486
+ hash.update(`${path.relative(folder, name)}\0`);
487
+ hash.update(fs.readFileSync(name));
488
+ hash.update("\0");
489
+ }
490
+ }
491
+ };
492
+ walk(folder);
493
+ return hash.digest("hex");
494
+ }
495
+ const manifestEntry = /^(?:[^/]+\/)?manifest\.json$/;
496
+ function loadSource(root) {
497
+ const manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
498
+ const config = manifest.source ?? {};
499
+ for (const field of [
500
+ "name",
501
+ "image",
502
+ "url"
503
+ ]) if (config[field] !== void 0 && typeof config[field] !== "string") throw new Error(tr("\"{field}\" in package.json must be a string", { field: `source.${field}` }));
504
+ const localizedNames = config.localizedNames ?? {};
505
+ if (localizedNames === null || typeof localizedNames !== "object" || !Object.values(localizedNames).every((name) => typeof name === "string")) throw new Error(tr("\"source.localizedNames\" in package.json must map languages to names"));
506
+ if (config.icon !== void 0 && (typeof config.icon?.symbol !== "string" || config.icon.color !== void 0 && typeof config.icon.color !== "string")) throw new Error(tr("\"source.icon\" in package.json must have a symbol and may have a color"));
507
+ let prefix;
508
+ if (config.url !== void 0) try {
509
+ prefix = new URL(config.url.endsWith("/") ? config.url : `${config.url}/`);
510
+ } catch {
511
+ throw new Error(tr("\"source.url\" in package.json is not an absolute URL"));
512
+ }
513
+ const workspaces = Array.isArray(manifest.workspaces) ? manifest.workspaces : manifest.workspaces?.packages ?? [];
514
+ return {
515
+ root,
516
+ config,
517
+ localizedNames,
518
+ prefix,
519
+ workspaces
520
+ };
521
+ }
522
+ function workspaceSwiplets(source) {
523
+ const files = [];
524
+ for (const pattern of source.workspaces) for (const directory of fs.globSync(pattern, { cwd: source.root }).sort()) {
525
+ const project = path.join(source.root, directory, "package.json");
526
+ if (!fs.existsSync(project)) continue;
527
+ const id = JSON.parse(fs.readFileSync(project, "utf8")).swiplet?.id;
528
+ if (typeof id !== "string") continue;
529
+ const built = path.join(source.root, directory, "dist", `${id}.swiplet`);
530
+ if (!fs.existsSync(built)) throw new Error(tr("{file} is missing; build {directory} first", {
531
+ file: path.relative(source.root, built),
532
+ directory
533
+ }));
534
+ files.push(built);
535
+ }
536
+ return files;
537
+ }
538
+ function readSwiplet(file) {
539
+ const entry = execFileSync("unzip", ["-Z1", file], { encoding: "utf8" }).split("\n").filter((name) => manifestEntry.test(name)).sort((a, b) => a.length - b.length)[0];
540
+ if (entry === void 0) throw new Error(`${file} has no manifest.json`);
541
+ const manifest = JSON.parse(execFileSync("unzip", [
542
+ "-p",
543
+ file,
544
+ entry
545
+ ], { encoding: "utf8" }));
546
+ if (typeof manifest.id !== "string" || !idPattern.test(manifest.id)) throw new Error(`${file} has no valid swiplet id in its manifest`);
547
+ return {
548
+ file,
549
+ manifest,
550
+ data: fs.readFileSync(file)
551
+ };
552
+ }
553
+ function sourceCommand(root, given) {
554
+ const source = loadSource(root);
555
+ const files = given.length > 0 ? given.map((file) => path.resolve(file)) : workspaceSwiplets(source);
556
+ if (files.length === 0) throw new Error(tr("package.json lists no workspaces with swiplets; name the swiplets to list"));
557
+ const swiplets = /* @__PURE__ */ new Map();
558
+ for (const read of files.map(readSwiplet)) {
559
+ const { id } = read.manifest;
560
+ if (swiplets.has(id)) throw new Error(tr("{id} is both {first} and {second}", {
561
+ id,
562
+ first: swiplets.get(id).file,
563
+ second: read.file
564
+ }));
565
+ swiplets.set(id, read);
566
+ }
567
+ const image = source.config.image === void 0 ? void 0 : {
568
+ name: path.basename(source.config.image),
569
+ data: fs.readFileSync(path.resolve(root, source.config.image))
570
+ };
571
+ const located = (name) => source.prefix ? new URL(name, source.prefix).href : name;
572
+ const dist = path.join(root, "dist");
573
+ fs.rmSync(dist, {
574
+ recursive: true,
575
+ force: true
576
+ });
577
+ fs.mkdirSync(dist, { recursive: true });
578
+ const entries = [...swiplets.keys()].map((id) => {
579
+ const { manifest, data } = swiplets.get(id);
580
+ const name = `${id}.swiplet`;
581
+ fs.writeFileSync(path.join(dist, name), data);
582
+ return {
583
+ ...manifest,
584
+ url: located(name),
585
+ size: data.length,
586
+ sha256: createHash("sha256").update(data).digest("hex")
587
+ };
588
+ });
589
+ if (image) fs.writeFileSync(path.join(dist, image.name), image.data);
590
+ const index = {
591
+ ...source.config.name ? { name: source.config.name } : {},
592
+ ...Object.keys(source.localizedNames).length > 0 ? { localizedNames: source.localizedNames } : {},
593
+ ...source.config.icon ? { icon: {
594
+ symbol: source.config.icon.symbol,
595
+ ...source.config.icon.color ? { color: source.config.icon.color } : {}
596
+ } } : {},
597
+ ...image ? { image: located(image.name) } : {},
598
+ swiplets: entries
599
+ };
600
+ fs.writeFileSync(path.join(dist, "swiplets.json"), `${JSON.stringify(index, null, 2)}\n`);
601
+ console.log(path.relative(process.cwd(), path.join(dist, "swiplets.json")));
602
+ }
603
+ const swiptRange = version.includes("-") ? version : `>=${version}-0 <=${version}`;
604
+ const idOf = (name) => name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[._-]+/, "").slice(0, 128).replace(/[._-]+$/, "") || "swiplet";
605
+ const templates = {
606
+ "package.json": (name) => `${JSON.stringify({
607
+ name: idOf(name),
608
+ version: "0.1.0",
609
+ private: true,
610
+ swiplet: {
611
+ id: idOf(name),
612
+ name,
613
+ versionCode: 1,
614
+ icon: {
615
+ color: "blue",
616
+ symbol: "sparkles"
617
+ },
618
+ app: "./src/App.tsx",
619
+ extension: "./src/extension.ts"
620
+ },
621
+ scripts: {
622
+ build: "swipt project build",
623
+ check: "tsc"
624
+ },
625
+ dependencies: { zod: "^4.6.7" },
626
+ devDependencies: {
627
+ "@swipt/api": swiptRange,
628
+ "@swipt/cli": swiptRange,
629
+ typescript: "^7.0.2",
630
+ ...Object.fromEntries([
631
+ "@expo/ui",
632
+ "@types/react",
633
+ "react"
634
+ ].map((name) => [name, peerDependencies[name]]))
635
+ }
636
+ }, null, 2)}\n`,
637
+ "tsconfig.json": () => `${JSON.stringify({ compilerOptions: {
638
+ target: "ES2022",
639
+ module: "ESNext",
640
+ moduleResolution: "Bundler",
641
+ jsx: "react-jsx",
642
+ lib: ["ES2023", "DOM"],
643
+ strict: true,
644
+ noEmit: true,
645
+ skipLibCheck: true
646
+ } }, null, 2)}\n`,
647
+ ".gitignore": () => "node_modules/\ndist/\n",
648
+ "src/extension.ts": () => `import * as device from "@swipt/api/device";
649
+ import { defineAction, defineExtension } from "@swipt/api/swiplet";
650
+
651
+ export default defineExtension({
652
+ actions: {
653
+ frontApp: defineAction({
654
+ title: "Find the App in Front",
655
+ run: (_, { signal }) => device.foregroundApplication.get({ signal }),
656
+ }),
657
+ },
658
+ });
659
+ `,
660
+ "src/App.tsx": () => `import { Button, Form, Host, Section, Text } from "@expo/ui/swift-ui";
661
+ import { useState } from "react";
662
+ import { actions } from "@swipt/api/swiplet";
663
+
664
+ import type extension from "./extension";
665
+
666
+ const { frontApp } = actions<typeof extension>();
667
+
668
+ export default function App() {
669
+ const [app, setApp] = useState("");
670
+ return (
671
+ <Host style={{ flex: 1 }}>
672
+ <Form>
673
+ <Section>
674
+ <Button label="Find the App in Front" onPress={async () => setApp(await frontApp())} />
675
+ {app === "" ? null : <Text>{app}</Text>}
676
+ </Section>
677
+ </Form>
678
+ </Host>
679
+ );
680
+ }
681
+ `
682
+ };
683
+ const quote = (value) => /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
684
+ function createCommand(directory) {
685
+ const root = path.resolve(directory);
686
+ if (fs.existsSync(root) && fs.readdirSync(root).length > 0) throw new Error(tr("{directory} is not empty", { directory }));
687
+ for (const [file, template] of Object.entries(templates)) {
688
+ fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
689
+ fs.writeFileSync(path.join(root, file), template(path.basename(root)));
690
+ }
691
+ const manager = process.env.npm_config_user_agent?.split("/")[0] ?? "npm";
692
+ console.log(`cd ${quote(directory)} && ${manager} install && ${manager} run build`);
693
+ }
694
+ export { buildProject, createCommand, loadProject, sourceCommand };
695
+
696
+ //# sourceMappingURL=project.js.map