@synopackageland/cli 0.53.17 → 0.53.18

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/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.53.18 (2026-11-14)
4
+
5
+ - `ui.stable_pages` gives pages in `ui.dir` a URL that survives package updates, such as a phone-browser page behind a QR code, a bookmark or a home-screen shortcut. A module UI lives in `app/<digest>/`, whose name changes with every build, so such links stopped working after an update. `stable_pages: {m: m/index.html}` serves `/webman/3rdparty/<package>/m/index.html` on DSM 7.1+ without sign-in, ingress or CGI. The build writes a forwarding page with the same bytes in every build, plus `target.json` naming the current file. DSM serves these files with `Last-Modified` at 1970, a size-only ETag and no `Cache-Control`, so only fixed bytes are safe to cache. The forwarding page reads `target.json` uncached and keeps the query and fragment. `check` validates names and paths (`STANDALONE_UI_STABLE_PAGES_INVALID`); `build` refuses a missing target or a name already used under `ui/` (`STANDALONE_UI_STABLE_PAGE_MISSING`, `STANDALONE_UI_STABLE_PAGE_CONFLICT`); `inspect` replays the forwarding page and pointer (`UI_STABLE_PAGE_INVALID`). The secret scan covers all of these files.
6
+ - The build writes a gzip copy (`<file>.gz`) beside each UI text file of 1 KiB or more (`.js`, `.mjs`, `.cjs`, `.css`, `.html`, `.json`, `.svg`, `.wasm`, `.txt`, `.xml`) when it saves at least 10%, after minification. DSM's nginx serves `/webman/3rdparty/` with `gzip_static` and no on-the-fly compression, so until now every App bundle reached the browser uncompressed; DSM's own packages (Hyper Backup, Application Service) already ship `.gz` files there. A 9.5 MB `app.js` now travels as 2.6 MB. Applies to SDK windows (classic and module UI, whose digest covers the `.gz` files) and native layouts; port-templated files, which the install wizard rewrites, and mobile assets keep no `.gz`. The `.gz` files carry no timestamp and a fixed OS byte, so builds stay reproducible. Apps take the change when they rebuild with this CLI; App code does not change.
7
+
3
8
  ## 0.53.17 (2026-11-12)
4
9
 
5
10
  - The `ui-vue` skill reference no longer asks for one Refresh per page in the header. Apps read again when the window is shown again (`ctx.reopen`) and when a page is shown, a failed read offers Retry beside its error, and `AppShell`'s `#actions` holds only real page actions (such as Add), so a page without one has no bar above it. This matches templates 0.42.2, which the existing `~0.42.1` range already installs.
package/README.md CHANGED
@@ -412,6 +412,40 @@ ui:
412
412
  banner: hidden
413
413
  ```
414
414
 
415
+ `ui.stable_pages` gives pages in `ui.dir` a URL that survives package updates,
416
+ for links handed to people: a QR code, a bookmark, a phone home-screen shortcut.
417
+ A module UI (`app.module.js`) lives in a content-addressed folder,
418
+ `/webman/3rdparty/<package>/app/<digest>/`, whose name changes with every build.
419
+ Each entry maps a page name to a file in `ui.dir`:
420
+
421
+ ```yaml
422
+ ui:
423
+ dir: frontend/dist
424
+ stable_pages:
425
+ m: m/index.html # /webman/3rdparty/<package>/m/index.html
426
+ ```
427
+
428
+ The build writes `ui/<name>/index.html`, a small page that forwards to the
429
+ declared file in the installed build, keeping the query and fragment. DSM serves
430
+ it without sign-in on every supported DSM version (no ingress, no CGI). DSM
431
+ sends these files without `Cache-Control`, with `Last-Modified` at 1970 and an
432
+ ETag of the file size only, so a browser may keep them for years. The stub is
433
+ therefore the same bytes in every build and every package, and reads the
434
+ current target from `ui/<name>/target.json` with an uncached request. The
435
+ digest folder stays immutable. Link to the stable URL itself and name the file
436
+ (DSM answers a folder URL with 403). After forwarding, the address bar shows the
437
+ digest URL, so a web app manifest beside the page should set `start_url` to the
438
+ stable URL and `scope` to `/webman/3rdparty/<package>/`.
439
+
440
+ Names are lowercase letters, digits and `-`, at most 8, and not `app`, `cgi`,
441
+ `config`, `images`, `sso` or `texts`; `build` also refuses a name any other
442
+ generated file already uses (`STANDALONE_UI_STABLE_PAGE_CONFLICT`). A target is a
443
+ path relative to `ui.dir` without `.` or `..` segments, query or fragment, and
444
+ must exist after the UI build (`STANDALONE_UI_STABLE_PAGE_MISSING`). The stub,
445
+ pointer and target stay public UI files: the secret scan covers them, and
446
+ `inspect` replays the stub and pointer (`UI_STABLE_PAGE_INVALID`). Classic
447
+ `app.js` UIs may declare stable pages too; their pointer names `app/<file>`.
448
+
415
449
  A full page does not need Application Portal. Omit `portal` unless an alias is
416
450
  explicitly wanted; only that opt-in adds `defaultAlias`, login styling, Portal
417
451
  panels and capabilities. No Portal is a healthy default for inspect/info/doctor.
@@ -5,6 +5,7 @@ export const ERROR_REGISTRY = {
5
5
  INSTALLED_INFO_TOO_LARGE: { code: 'INSTALLED_INFO_TOO_LARGE', description: 'The installed INFO, with the base64 icon lines DSM adds at install, would exceed the 65536 bytes the SDK executor reads', suggestion: 'Recompress the icon PNG with fewer colours and less detail (posterize or quantize it); the 256 px icon typically needs to be under about 40 KB' },
6
6
  STANDALONE_MOBILE_INVALID: { code: 'STANDALONE_MOBILE_INVALID', description: 'The mobile declaration or its UI/gateway dependency is invalid', suggestion: 'Check mobile against the manifest schema and read the mobile skill' },
7
7
  MOBILE_SDK_ENTRY_MISSING: { code: 'MOBILE_SDK_ENTRY_MISSING', description: 'The installed frontend SDK has no entry export', suggestion: 'Install an SDK with /entry in the UI build directory or project root' },
8
+ UI_STABLE_PAGE_INVALID: { code: 'UI_STABLE_PAGE_INVALID', description: 'A packaged stable page differs from its build record', suggestion: 'Rebuild the SPK and inspect it again' },
8
9
  MOBILE_INVALID: { code: 'MOBILE_INVALID', description: 'Packaged mobile assets differ from their build declaration', suggestion: 'Rebuild the SPK and inspect it again' },
9
10
  SECRET_FILE_TRACKED: { code: "SECRET_FILE_TRACKED", description: "Git tracks a local secret file.", suggestion: SECRET_FILE_FIX },
10
11
  SECRET_FILE_UNIGNORED: { code: "SECRET_FILE_UNIGNORED", description: "A local secret file lacks a repository ignore rule.", suggestion: SECRET_FILE_FIX },
@@ -690,6 +691,21 @@ export const ERROR_REGISTRY = {
690
691
  description: "ui.banner is neither shown nor hidden.",
691
692
  suggestion: "Set ui.banner to hidden to drop DSM's banner from the App's standalone page, or omit it to keep the banner.",
692
693
  },
694
+ STANDALONE_UI_STABLE_PAGES_INVALID: {
695
+ code: "STANDALONE_UI_STABLE_PAGES_INVALID",
696
+ description: "ui.stable_pages does not map page names to files in ui.dir.",
697
+ suggestion: "Map 1 to 8 names (lowercase letters, digits and -, not app, cgi, config, images, sso or texts) to a file path relative to ui.dir, for example stable_pages: {m: m/index.html}.",
698
+ },
699
+ STANDALONE_UI_STABLE_PAGE_MISSING: {
700
+ code: "STANDALONE_UI_STABLE_PAGE_MISSING",
701
+ description: "A ui.stable_pages target is not a file in the built UI.",
702
+ suggestion: "Run the UI build and point the page at a file it writes under ui.dir.",
703
+ },
704
+ STANDALONE_UI_STABLE_PAGE_CONFLICT: {
705
+ code: "STANDALONE_UI_STABLE_PAGE_CONFLICT",
706
+ description: "A ui.stable_pages name collides with a file the package already puts under ui/.",
707
+ suggestion: "Choose another page name.",
708
+ },
693
709
  STANDALONE_UI_BUILD_FAILED: {
694
710
  code: "STANDALONE_UI_BUILD_FAILED",
695
711
  description: "The UI build command failed.",
@@ -2,6 +2,7 @@ import { folderPickerWizardFiles } from '../build-spk/folder-picker.js';
2
2
  import { parseDsmStrings } from "./dsm-texts.js";
3
3
  import { readTCPListeners } from "./tcp-listeners.js";
4
4
  import { inspectMobileFiles, mobileRecordProblem } from './mobile.js';
5
+ import { inspectStablePages } from './stable-pages.js';
5
6
  import { DAEMON_NOFILE_UNSUPPORTED, DAEMON_NOFILE_ACTIVATION_PROBLEM, readNoFile, daemonSystemUnitName, renderDaemonSystemUnit, daemonNoFileSdkProblem, daemonNoFileIdentityProblem, DAEMON_NOFILE_MIN_DSM } from "./daemon-nofile.js";
6
7
  import { gatewayIngressPathProblem, gatewayIngressOwnershipSupported } from './gateway-ingress.js';
7
8
  import { renderGatewayIngressCheck } from './native-gateway.js';
@@ -184,6 +185,7 @@ export async function inspectSpk(spkPath, expectedKind, options = {}) {
184
185
  findings.push("daemon.nofile requires a native daemon controller");
185
186
  const daemonRestart = recoverDaemonRestart(metadata.daemon_restart, metadata.daemon_restart === undefined && daemonNoFile !== undefined ? undefined : metadata.daemon_sdk, findings);
186
187
  await inspectModuleUi(dir, paths, metadata.ui_module, findings, metadata.mobile);
188
+ await inspectStablePageFiles(dir, paths, metadata.stable_pages, metadata.ui_module, findings);
187
189
  if (metadata.daemon_restart !== undefined && (metadata.compose !== undefined || !paths.has("daemon/control")))
188
190
  findings.push("DAEMON_RESTART_INVALID daemon restart requires a native daemon controller, without Compose supervision");
189
191
  const { identityGateway, gateway } = await inspectGatewayAdmission(dir, paths, metadata.provider_only_oidc, findings);
@@ -462,6 +464,25 @@ async function inspectModuleUi(dir, paths, version, findings, mobile) {
462
464
  findings.push(`UI_MODULE_INVALID ${error.message}`);
463
465
  }
464
466
  }
467
+ const UI_STABLE_PAGE_INVALID = "UI_STABLE_PAGE_INVALID";
468
+ /** Replay each recorded stable page: the fixed stub, its pointer and the target. */
469
+ async function inspectStablePageFiles(dir, paths, record, version, findings) {
470
+ if (record === undefined)
471
+ return;
472
+ const names = record && typeof record === "object" ? Object.keys(record) : [];
473
+ const root = join(dir, "stable-page-inspection");
474
+ mkdirSync(root);
475
+ try {
476
+ if (names.length)
477
+ await extractSpkArchive({ file: join(dir, "package.tgz"), cwd: root, filter: path => names.some(name => path.replace(/^\.\//, "").startsWith(`ui/${name}/`)) });
478
+ const problem = inspectStablePages(record, paths, version, path => readOptional(join(root, path)));
479
+ if (problem)
480
+ findings.push(`${UI_STABLE_PAGE_INVALID} ${problem}`);
481
+ }
482
+ catch (error) {
483
+ findings.push(`${UI_STABLE_PAGE_INVALID} ${error.message}`);
484
+ }
485
+ }
465
486
  const LAUNCHER_TYPE_MISMATCH = "LAUNCHER_TYPE_MISMATCH";
466
487
  const LAUNCHER_PORTAL_MISMATCH = "LAUNCHER_PORTAL_MISMATCH";
467
488
  /** Compare the actual launcher and Portal fields to the packaged declaration. */
@@ -97,6 +97,8 @@ export interface StandaloneManifest {
97
97
  window?: WindowSize;
98
98
  /** `ui.banner: hidden`: a standalone page drops DSM's banner (name, account menu), as DSM's own "Hide banner" does for every App. */
99
99
  banner?: "hidden";
100
+ /** `ui.stable_pages`: page name → file in ui.dir, served at /webman/3rdparty/<package>/<name>/index.html in every build. */
101
+ stablePages?: Record<string, string>;
100
102
  };
101
103
  i18n?: StandaloneI18n;
102
104
  capabilities: Capabilities;
@@ -1,5 +1,6 @@
1
1
  import { loadNativeTexts } from "./dsm-texts.js";
2
2
  import { readUiSecretIgnores } from "./public-ui.js";
3
+ import { stablePagesProblem } from "./stable-pages.js";
3
4
  import { readTCPListeners, tcpSDKProblem } from "./tcp-listeners.js";
4
5
  import { validateNativeManifest } from './native-http.js';
5
6
  import { readMobile, mobileIconPath } from './mobile.js';
@@ -1104,8 +1105,12 @@ function readUi(value, c) {
1104
1105
  if (value.banner !== undefined && value.banner !== "shown" && value.banner !== "hidden")
1105
1106
  return c.fail("STANDALONE_UI_BANNER_INVALID", "ui.banner must be shown or hidden.");
1106
1107
  const banner = value.banner === "hidden" ? { banner: "hidden" } : {};
1108
+ const stableProblem = value.stable_pages === undefined ? undefined : stablePagesProblem(value.stable_pages);
1109
+ if (stableProblem)
1110
+ return c.fail("STANDALONE_UI_STABLE_PAGES_INVALID", `ui.stable_pages ${stableProblem}`);
1111
+ const stable = value.stable_pages === undefined ? {} : { stablePages: { ...value.stable_pages } };
1107
1112
  if (value.build === undefined) {
1108
- return dir ? { dir, ...launch, ...window, ...banner } : undefined;
1113
+ return dir ? { dir, ...launch, ...window, ...banner, ...stable } : undefined;
1109
1114
  }
1110
1115
  const build = value.build;
1111
1116
  const command = isRecord(build) ? build.command : undefined;
@@ -1122,6 +1127,7 @@ function readUi(value, c) {
1122
1127
  ...launch,
1123
1128
  ...window,
1124
1129
  ...banner,
1130
+ ...stable,
1125
1131
  }
1126
1132
  : undefined;
1127
1133
  }
@@ -7,6 +7,7 @@ import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync,
7
7
  import { enforceRepositorySecrets, readAllowedSecretFiles } from '../secret-files.js';
8
8
  import { enforcePublicUi, minifyUiTree, readUiSecretIgnores, storedUiSecretIgnores, uiFiles } from './public-ui.js';
9
9
  import { tmpdir } from 'node:os';
10
+ import { precompressUiTree } from './ui-assets.js';
10
11
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
11
12
  import { parse } from 'yaml';
12
13
  import { createReproducibleTar } from '../build-spk/reproducible-archive.js';
@@ -357,6 +358,7 @@ export async function buildNativeLayout(options) {
357
358
  mkdirSync(target);
358
359
  copyTree(payload, target);
359
360
  minifyUiTree(join(target, 'ui'));
361
+ precompressUiTree(join(target, 'ui'));
360
362
  const uiIgnores = enforcePublicUi(join(target, 'ui'), m.uiSecretIgnores);
361
363
  const files = layoutFiles(target);
362
364
  const ignoredUi = uiFiles(join(target, 'ui')).filter(file => uiIgnores.some(ignore => ignore.file === file)).map(file => `ui/${file}`);
@@ -28,7 +28,8 @@ import { renderDelegateScopeSteps } from "../build-spk/delegate-scope.js";
28
28
  import { createReproducibleTar } from "../build-spk/reproducible-archive.js";
29
29
  import { renderStandaloneScript } from "./lifecycle.js";
30
30
  import { APP_SCRIPTS_DIR, APP_SCRIPTS_SPK_DIR } from "./app-scripts.js";
31
- import { MODULE_UI_ENTRY, uiTreeDigest } from "./ui-assets.js";
31
+ import { MODULE_UI_ENTRY, precompressUiTree, uiTreeDigest } from "./ui-assets.js";
32
+ import { writeStablePages } from "./stable-pages.js";
32
33
  import { enforcePublicUi, isUiBundle, logicalUiFile, minifyUi, minifyUiTree, storedUiSecretIgnores, uiFiles } from "./public-ui.js";
33
34
  import { codedMessage } from "../errors.js";
34
35
  import { CHECKSUM_PLACEHOLDER, DIGEST_PLACEHOLDER, largestInstalledInfo, projectInstalledInfoIssue, stagedInstalledInfoIssue } from "../spk/installed-info.js";
@@ -105,6 +106,7 @@ export async function assembleStandaloneSpk(options) {
105
106
  else
106
107
  mkdirSync(appDir, { recursive: true });
107
108
  minifyUiTree(appDir);
109
+ precompressUiTree(appDir);
108
110
  const moduleUi = hasSdkWindow(manifest) && existsSync(join(appDir, MODULE_UI_ENTRY));
109
111
  const uiDigest = uiTreeDigest(appDir, moduleUi);
110
112
  const mobile = await renderMobileAssets(manifest, uiDigest, moduleUi ? uiDigest : undefined);
@@ -272,8 +274,18 @@ export async function assembleStandaloneSpk(options) {
272
274
  ...(variant.daemon || variant.compose ? { 'daemon/config.json': daemonConfig(variant) } : {}),
273
275
  ...(variant.installSettings ? { 'install/settings.json': JSON.stringify(settingsConfig(variant), null, 2) + '\n' } : {}),
274
276
  }));
277
+ // Last ui/ writer: a stable page name must not collide with any generated entry.
278
+ if (manifest.ui?.stablePages)
279
+ writeStablePages(uiRoot, manifest.ui.stablePages, moduleVersion, (code, message) => { throw new StandaloneBuildError(code, message); });
275
280
  // App bytes were minified before their digest; mobile builds its own final inventory.
276
281
  minifyUiTree(uiRoot, ["app"]);
282
+ // The install wizard rewrites port-templated files, so they get no .gz.
283
+ const portFiles = manifest.installPorts
284
+ ? Object.keys(JSON.parse(readFileSync(join(staging, "package/install/ports.json"), "utf8")).files)
285
+ .filter(path => path.startsWith("ui/")).map(path => path.slice("ui/".length))
286
+ : [];
287
+ // Stable pages hold only their fixed stub and pointer, which inspect replays.
288
+ precompressUiTree(uiRoot, ["app", ...portFiles, ...Object.keys(manifest.ui?.stablePages ?? {})]);
277
289
  if (manifest.installPorts) {
278
290
  const file = join(staging, "package/install/ports.json");
279
291
  const ports = JSON.parse(readFileSync(file, "utf8"));
@@ -306,6 +318,7 @@ export async function assembleStandaloneSpk(options) {
306
318
  ...(mobile ? { mobile: mobile.record } : {}),
307
319
  dependencies: packageDependencies(manifest),
308
320
  ...(moduleVersion ? { ui_module: moduleVersion } : {}),
321
+ ...(manifest.ui?.stablePages ? { stable_pages: manifest.ui.stablePages } : {}),
309
322
  ...(manifest.installSettings ? { installSettings: manifest.installSettings } : {}),
310
323
  ...(manifest.installPorts ? { installPorts: portDefaults(manifest) } : {}),
311
324
  ...(manifest.minMemoryMb !== undefined ? { minMemoryMb: manifest.minMemoryMb } : {}),
@@ -0,0 +1,37 @@
1
+ /**
2
+ * `ui.stable_pages`: page URLs that stay the same across package updates.
3
+ *
4
+ * Module UI lives in a content-addressed folder (ui/app/<digest>/), so its URLs
5
+ * change with every build. A stable page is ui/<name>/index.html, served by DSM
6
+ * at /webman/3rdparty/<package>/<name>/index.html without sign-in on DSM 7.1+.
7
+ * It forwards to the declared file in the current build.
8
+ *
9
+ * DSM serves these static files with no Cache-Control, Last-Modified 1970 (the
10
+ * reproducible archive's mtime) and an ETag of the size alone: browsers may keep
11
+ * them for years, and a revalidation can keep an older copy of the same size.
12
+ * So the stub's bytes never change between builds or packages, and it reads the
13
+ * current target from target.json with a no-store, cache-busted request.
14
+ */
15
+ export declare const STABLE_PAGE_FILE = "index.html";
16
+ export declare const STABLE_PAGE_POINTER = "target.json";
17
+ /** ui/ entries the CLI generates; build also refuses any other existing entry. */
18
+ export declare const STABLE_PAGE_RESERVED: string[];
19
+ export declare const STABLE_PAGE_LIMIT = 8;
20
+ export type StablePages = Record<string, string>;
21
+ /** Undefined when valid; otherwise why. */
22
+ export declare function stablePagesProblem(value: unknown): string | undefined;
23
+ /** Fixed bytes: a cached copy from any build keeps working, since it reads target.json. */
24
+ export declare const STABLE_PAGE_STUB = "<!doctype html>\n<html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><meta name=\"referrer\" content=\"same-origin\"><meta name=\"robots\" content=\"noindex\"><title></title></head>\n<body><noscript>This page needs JavaScript.</noscript><script>\n(function () {\n function fail() { document.body.textContent = \"This page is not available. Reload to try again.\"; }\n try {\n fetch(\"target.json?t=\" + Date.now(), {cache: \"no-store\", credentials: \"same-origin\"})\n .then(function (r) { if (!r.ok) throw 0; return r.json(); })\n .then(function (p) {\n if (!p || p.v !== 1 || typeof p.href !== \"string\" || !/^\\.\\.\\/app(?:\\/[\\w~-][\\w.~-]*)+$/.test(p.href)) throw 0;\n var url = new URL(p.href, location.href);\n if (url.origin !== location.origin) throw 0;\n url.search = location.search;\n url.hash = location.hash;\n location.replace(url.href);\n })\n .catch(fail);\n } catch (e) { fail(); }\n})();\n</script></body></html>\n";
25
+ /** The relative URL of the declared file in this build, from ui/<name>/. */
26
+ export declare function stablePageHref(target: string, moduleVersion?: string): string;
27
+ export declare function stablePagePointer(target: string, moduleVersion?: string): string;
28
+ /**
29
+ * Write each page's stub and pointer once every other ui/ file exists, so a
30
+ * name that collides with a generated entry fails here.
31
+ */
32
+ export declare function writeStablePages(uiRoot: string, pages: StablePages, moduleVersion: string | undefined, fail: (code: string, message: string) => never): void;
33
+ /**
34
+ * inspect: the recorded pages against the archive. `read` returns a packaged
35
+ * ui/ file's text. Undefined when consistent.
36
+ */
37
+ export declare function inspectStablePages(record: unknown, paths: Set<string>, moduleVersion: string | undefined, read: (path: string) => string | undefined): string | undefined;
@@ -0,0 +1,110 @@
1
+ import { existsSync, lstatSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ /**
4
+ * `ui.stable_pages`: page URLs that stay the same across package updates.
5
+ *
6
+ * Module UI lives in a content-addressed folder (ui/app/<digest>/), so its URLs
7
+ * change with every build. A stable page is ui/<name>/index.html, served by DSM
8
+ * at /webman/3rdparty/<package>/<name>/index.html without sign-in on DSM 7.1+.
9
+ * It forwards to the declared file in the current build.
10
+ *
11
+ * DSM serves these static files with no Cache-Control, Last-Modified 1970 (the
12
+ * reproducible archive's mtime) and an ETag of the size alone: browsers may keep
13
+ * them for years, and a revalidation can keep an older copy of the same size.
14
+ * So the stub's bytes never change between builds or packages, and it reads the
15
+ * current target from target.json with a no-store, cache-busted request.
16
+ */
17
+ export const STABLE_PAGE_FILE = "index.html";
18
+ export const STABLE_PAGE_POINTER = "target.json";
19
+ /** ui/ entries the CLI generates; build also refuses any other existing entry. */
20
+ export const STABLE_PAGE_RESERVED = ["app", "cgi", "config", "images", "sso", "texts"];
21
+ export const STABLE_PAGE_LIMIT = 8;
22
+ const NAME = /^[a-z][a-z0-9-]{0,31}$/;
23
+ const SEGMENT = /^[A-Za-z0-9_~-][A-Za-z0-9._~-]*$/;
24
+ /** Undefined when valid; otherwise why. */
25
+ export function stablePagesProblem(value) {
26
+ if (!value || typeof value !== "object" || Array.isArray(value))
27
+ return "must map a page name to a file in ui.dir, for example {m: m/index.html}";
28
+ const entries = Object.entries(value);
29
+ if (!entries.length || entries.length > STABLE_PAGE_LIMIT)
30
+ return `must list 1 to ${STABLE_PAGE_LIMIT} pages`;
31
+ for (const [name, target] of entries) {
32
+ if (!NAME.test(name))
33
+ return `name ${JSON.stringify(name)} must be lowercase letters, digits and -, starting with a letter (at most 32)`;
34
+ if (STABLE_PAGE_RESERVED.includes(name))
35
+ return `name ${JSON.stringify(name)} is used by the package's generated UI files (${STABLE_PAGE_RESERVED.join(", ")})`;
36
+ if (typeof target !== "string" || target.length > 256 || !target.split("/").every(part => SEGMENT.test(part) && !/^\.+$/.test(part)))
37
+ return `${name} must name a file relative to ui.dir, using letters, digits, ., _, ~, - and /, with no . or .. segment, query or fragment`;
38
+ if (/\.(?:gz|map)$/i.test(target))
39
+ return `${name} must name a page, not a .gz or .map file`;
40
+ }
41
+ return undefined;
42
+ }
43
+ /** Fixed bytes: a cached copy from any build keeps working, since it reads target.json. */
44
+ export const STABLE_PAGE_STUB = `<!doctype html>
45
+ <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="same-origin"><meta name="robots" content="noindex"><title></title></head>
46
+ <body><noscript>This page needs JavaScript.</noscript><script>
47
+ (function () {
48
+ function fail() { document.body.textContent = "This page is not available. Reload to try again."; }
49
+ try {
50
+ fetch("${STABLE_PAGE_POINTER}?t=" + Date.now(), {cache: "no-store", credentials: "same-origin"})
51
+ .then(function (r) { if (!r.ok) throw 0; return r.json(); })
52
+ .then(function (p) {
53
+ if (!p || p.v !== 1 || typeof p.href !== "string" || !/^\\.\\.\\/app(?:\\/[\\w~-][\\w.~-]*)+$/.test(p.href)) throw 0;
54
+ var url = new URL(p.href, location.href);
55
+ if (url.origin !== location.origin) throw 0;
56
+ url.search = location.search;
57
+ url.hash = location.hash;
58
+ location.replace(url.href);
59
+ })
60
+ .catch(fail);
61
+ } catch (e) { fail(); }
62
+ })();
63
+ </script></body></html>
64
+ `;
65
+ /** The relative URL of the declared file in this build, from ui/<name>/. */
66
+ export function stablePageHref(target, moduleVersion) {
67
+ return `../app/${moduleVersion ? `${moduleVersion}/` : ""}${target}`;
68
+ }
69
+ export function stablePagePointer(target, moduleVersion) {
70
+ return JSON.stringify({ v: 1, href: stablePageHref(target, moduleVersion) }) + "\n";
71
+ }
72
+ /**
73
+ * Write each page's stub and pointer once every other ui/ file exists, so a
74
+ * name that collides with a generated entry fails here.
75
+ */
76
+ export function writeStablePages(uiRoot, pages, moduleVersion, fail) {
77
+ for (const [name, target] of Object.entries(pages).sort(([a], [b]) => a.localeCompare(b))) {
78
+ const file = join(uiRoot, "app", moduleVersion ?? "", target);
79
+ if (!existsSync(file) || !lstatSync(file).isFile())
80
+ fail("STANDALONE_UI_STABLE_PAGE_MISSING", `ui.stable_pages.${name}: ${target} is not a file in the built UI (ui.dir).`);
81
+ const dir = join(uiRoot, name);
82
+ if (existsSync(dir))
83
+ fail("STANDALONE_UI_STABLE_PAGE_CONFLICT", `ui.stable_pages.${name}: the package already has ui/${name}; choose another name.`);
84
+ mkdirSync(dir, { mode: 0o755 });
85
+ writeFileSync(join(dir, STABLE_PAGE_FILE), STABLE_PAGE_STUB, { mode: 0o644 });
86
+ writeFileSync(join(dir, STABLE_PAGE_POINTER), stablePagePointer(target, moduleVersion), { mode: 0o644 });
87
+ }
88
+ }
89
+ /**
90
+ * inspect: the recorded pages against the archive. `read` returns a packaged
91
+ * ui/ file's text. Undefined when consistent.
92
+ */
93
+ export function inspectStablePages(record, paths, moduleVersion, read) {
94
+ const problem = stablePagesProblem(record);
95
+ if (problem)
96
+ return `invalid build record: ${problem}`;
97
+ for (const [name, target] of Object.entries(record)) {
98
+ const prefix = `ui/${name}/`;
99
+ const extra = [...paths].filter(path => path.startsWith(prefix) && ![STABLE_PAGE_FILE, STABLE_PAGE_POINTER].includes(path.slice(prefix.length)));
100
+ if (extra.length)
101
+ return `ui/${name} holds files besides its stub: ${extra.join(", ")}`;
102
+ if (read(prefix + STABLE_PAGE_FILE) !== STABLE_PAGE_STUB)
103
+ return `ui/${name}/${STABLE_PAGE_FILE} differs from the generated stub`;
104
+ if (read(prefix + STABLE_PAGE_POINTER) !== stablePagePointer(target, moduleVersion))
105
+ return `ui/${name}/${STABLE_PAGE_POINTER} does not point at ${target} in this build`;
106
+ if (!paths.has(`ui/app/${moduleVersion ? `${moduleVersion}/` : ""}${target}`))
107
+ return `${name} target ${target} is missing from the UI`;
108
+ }
109
+ return undefined;
110
+ }
@@ -1,3 +1,11 @@
1
1
  export declare const MODULE_UI_ENTRY = "app.module.js";
2
2
  /** Include paths and bytes: moving a chunk changes its import URL too. */
3
3
  export declare function uiTreeDigest(root: string, framed?: boolean): string;
4
+ /**
5
+ * Write `<file>.gz` beside each text asset. DSM's nginx serves /webman/3rdparty/
6
+ * with gzip_static and no on-the-fly gzip, so only a .gz sibling reaches the
7
+ * browser compressed. Run after the files reach their final bytes (after
8
+ * minifying, before digests and secret scans); a file rewritten later would
9
+ * leave a stale .gz. `skip` lists root-relative files or folders to leave out.
10
+ */
11
+ export declare function precompressUiTree(root: string, skip?: string[]): void;
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
- import { lstatSync, readFileSync, readdirSync } from "node:fs";
3
- import { join } from "node:path";
2
+ import { existsSync, lstatSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
3
+ import { extname, join } from "node:path";
4
+ import { constants, gzipSync } from "node:zlib";
4
5
  export const MODULE_UI_ENTRY = "app.module.js";
5
6
  /** Include paths and bytes: moving a chunk changes its import URL too. */
6
7
  export function uiTreeDigest(root, framed = false) {
@@ -25,3 +26,35 @@ export function uiTreeDigest(root, framed = false) {
25
26
  walk(root, "");
26
27
  return hash.digest("hex");
27
28
  }
29
+ // Text the browser fetches; images, fonts and archives are already compressed.
30
+ const PRECOMPRESSED = new Set([".js", ".mjs", ".cjs", ".css", ".html", ".htm", ".json", ".svg", ".wasm", ".txt", ".xml"]);
31
+ const PRECOMPRESS_MIN_BYTES = 1024;
32
+ /**
33
+ * Write `<file>.gz` beside each text asset. DSM's nginx serves /webman/3rdparty/
34
+ * with gzip_static and no on-the-fly gzip, so only a .gz sibling reaches the
35
+ * browser compressed. Run after the files reach their final bytes (after
36
+ * minifying, before digests and secret scans); a file rewritten later would
37
+ * leave a stale .gz. `skip` lists root-relative files or folders to leave out.
38
+ */
39
+ export function precompressUiTree(root, skip = []) {
40
+ const walk = (dir, prefix) => {
41
+ for (const name of readdirSync(dir).sort()) {
42
+ const path = join(dir, name);
43
+ const file = `${prefix}${name}`;
44
+ if (skip.some(entry => file === entry || file.startsWith(`${entry}/`)))
45
+ continue;
46
+ const stat = lstatSync(path);
47
+ if (stat.isDirectory())
48
+ walk(path, `${file}/`);
49
+ else if (stat.isFile() && stat.size >= PRECOMPRESS_MIN_BYTES && PRECOMPRESSED.has(extname(name).toLowerCase())) {
50
+ const gz = gzipSync(readFileSync(path), { level: constants.Z_BEST_COMPRESSION });
51
+ // zlib stamps the build host's OS; one value keeps the SPK reproducible.
52
+ gz[9] = 255;
53
+ if (gz.length < stat.size * 0.9)
54
+ writeFileSync(`${path}.gz`, gz);
55
+ }
56
+ }
57
+ };
58
+ if (existsSync(root))
59
+ walk(root, "");
60
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@synopackageland/cli",
3
- "version": "0.53.17",
3
+ "version": "0.53.18",
4
4
  "description": "Syno Package Land Developer Kit CLI",
5
5
  "type": "module",
6
6
  "bin": {
package/skills/SKILL.md CHANGED
@@ -349,6 +349,8 @@ favicon 與手機 viewport 由 wrapper 設定。不需要 `pureEnv` 或 `allowAl
349
349
 
350
350
  `ui.banner: hidden` 只替這個 App 的全頁拿掉 DSM 橫幅(預設 `shown` 保留);適合 App 外框已有名稱與帳號區時,帳號與登出改由 SDK `AppShell` 負責。細節見 reference/ui-vue.md。
351
351
 
352
+ 要給人一個跨版本不變的頁面網址(QR code、書籤、手機主畫面捷徑、PWA `start_url`)時,宣告 `ui.stable_pages: {<name>: <ui.dir 內的檔案>}`,例如 `{m: m/index.html}` → `/webman/3rdparty/<package>/m/index.html`。不要把 `app/<digest>/…` 網址交給使用者:module UI 的 digest 資料夾每次 build 都會換。build 生成固定內容的轉址頁與 `target.json`,DSM 7.1+ 免登入可開,不需 ingress 或 CGI。細節見 reference/ui-vue.md 的 Stable page URLs。
353
+
352
354
  Application Portal 是獨立 opt-in:不想要別名就省略 `portal`,不生成
353
355
  `defaultAlias`、Portal 面板/capability 或 Web Station alias;沒有 Portal
354
356
  不是 inspect/info/doctor 問題。明確啟用 `portal` 時才將其 alias 作為 `defaultAlias`。
@@ -224,6 +224,33 @@ ui:
224
224
  banner: hidden
225
225
  ```
226
226
 
227
+ ## Stable page URLs
228
+
229
+ `app.module.js` 的 UI 放在內容雜湊資料夾 `/webman/3rdparty/<package>/app/<digest>/`,
230
+ 每次 build 名稱都變。要交給使用者的網址(QR code、書籤、手機主畫面捷徑、PWA `start_url`)
231
+ 改用 `ui.stable_pages`:頁名對應到 `ui.dir` 內的檔案。
232
+
233
+ ```yaml
234
+ ui:
235
+ dir: frontend/dist
236
+ stable_pages:
237
+ m: m/index.html # /webman/3rdparty/<package>/m/index.html
238
+ ```
239
+
240
+ - build 寫入 `ui/<name>/index.html`(固定內容的轉址頁)與 `ui/<name>/target.json`(這次 build 的目標)。
241
+ 轉址頁以不快取的請求讀 `target.json`,再 `location.replace` 到目前 digest 資料夾內的檔案,保留 query 與 fragment。
242
+ - 為什麼轉址頁內容固定:DSM 對這些靜態檔不送 `Cache-Control`,`Last-Modified` 是 1970,ETag 只看檔案大小,
243
+ 瀏覽器可能快取多年,重新驗證也可能留著同大小的舊版。固定內容讓舊快取永遠可用;digest 資料夾照舊 immutable。
244
+ - DSM 7.1+ 免登入;不需要 ingress(7.2-64570+)或 CGI。DSM 不提供資料夾索引(403),連結要寫到 `index.html`。
245
+ - 轉址後網址列是 digest 網址。頁面旁的 web app manifest 要把 `start_url` 設成穩定網址、
246
+ `scope` 設成 `/webman/3rdparty/<package>/`,安裝到主畫面才會開穩定網址。App 內產生連結時直接寫穩定網址,
247
+ 不要從 `import.meta.url` 推 digest 路徑。
248
+ - 規則:頁名為小寫字母、數字與 `-`,最多 8 個,不得是 `app`、`cgi`、`config`、`images`、`sso`、`texts`;
249
+ 與其他生成檔撞名時 build 回 `STANDALONE_UI_STABLE_PAGE_CONFLICT`。目標是 `ui.dir` 內的相對路徑,
250
+ 不得有 `.`/`..` 片段、query 或 fragment,UI build 後必須存在,否則 `STANDALONE_UI_STABLE_PAGE_MISSING`;
251
+ 宣告格式錯誤時 check 回 `STANDALONE_UI_STABLE_PAGES_INVALID`。
252
+ - 轉址頁、`target.json` 與目標都是公開 UI 檔,照樣過 secret scan;`inspect` 會比對轉址頁與 pointer(`UI_STABLE_PAGE_INVALID`)。
253
+
227
254
  Application Portal 是獨立 opt-in:不想要別名就省略 `portal`,不生成
228
255
  `defaultAlias`、Portal 面板/capability 或 Web Station alias;沒有 Portal
229
256
  不是 inspect/info/doctor 問題。明確啟用 `portal` 時才將其 alias 作為 `defaultAlias`。