@gtkx/cli 1.2.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/README.md +6 -4
  2. package/dist/builder.d.ts +0 -1
  3. package/dist/builder.d.ts.map +1 -1
  4. package/dist/builder.js +6 -6
  5. package/dist/builder.js.map +1 -1
  6. package/dist/codegen/freshness.js +1 -1
  7. package/dist/codegen/freshness.js.map +1 -1
  8. package/dist/codegen/run-codegen.d.ts +2 -2
  9. package/dist/codegen/run-codegen.d.ts.map +1 -1
  10. package/dist/codegen/run-codegen.js +28 -9
  11. package/dist/codegen/run-codegen.js.map +1 -1
  12. package/dist/commands/build.d.ts +0 -4
  13. package/dist/commands/build.d.ts.map +1 -1
  14. package/dist/commands/build.js +0 -5
  15. package/dist/commands/build.js.map +1 -1
  16. package/dist/commands/codegen.d.ts.map +1 -1
  17. package/dist/commands/codegen.js +1 -3
  18. package/dist/commands/codegen.js.map +1 -1
  19. package/dist/commands/docs.d.ts.map +1 -1
  20. package/dist/commands/docs.js +3 -0
  21. package/dist/commands/docs.js.map +1 -1
  22. package/dist/deploy/depends.d.ts +2 -2
  23. package/dist/deploy/depends.d.ts.map +1 -1
  24. package/dist/deploy/depends.js +30 -15
  25. package/dist/deploy/depends.js.map +1 -1
  26. package/dist/deploy/nfpm/config.js +1 -1
  27. package/dist/deploy/nfpm/config.js.map +1 -1
  28. package/dist/deploy/node-runtime/elf.d.ts +1 -1
  29. package/dist/deploy/node-runtime/elf.d.ts.map +1 -1
  30. package/dist/deploy/node-runtime/elf.js +2 -2
  31. package/dist/deploy/node-runtime/elf.js.map +1 -1
  32. package/dist/deploy/node-runtime/index.js +2 -2
  33. package/dist/deploy/node-runtime/index.js.map +1 -1
  34. package/dist/deploy/notices/collect.d.ts +3 -1
  35. package/dist/deploy/notices/collect.d.ts.map +1 -1
  36. package/dist/deploy/notices/collect.js +2 -2
  37. package/dist/deploy/notices/collect.js.map +1 -1
  38. package/dist/deploy/notices/packages.d.ts +2 -1
  39. package/dist/deploy/notices/packages.d.ts.map +1 -1
  40. package/dist/deploy/notices/packages.js +4 -27
  41. package/dist/deploy/notices/packages.js.map +1 -1
  42. package/dist/deploy/payload/icons.d.ts +7 -3
  43. package/dist/deploy/payload/icons.d.ts.map +1 -1
  44. package/dist/deploy/payload/icons.js +46 -28
  45. package/dist/deploy/payload/icons.js.map +1 -1
  46. package/dist/deploy/payload/stage.d.ts.map +1 -1
  47. package/dist/deploy/payload/stage.js +3 -2
  48. package/dist/deploy/payload/stage.js.map +1 -1
  49. package/dist/deploy/run-deploy.d.ts.map +1 -1
  50. package/dist/deploy/run-deploy.js +63 -11
  51. package/dist/deploy/run-deploy.js.map +1 -1
  52. package/dist/deploy/settings/build-manifest.d.ts +9 -0
  53. package/dist/deploy/settings/build-manifest.d.ts.map +1 -0
  54. package/dist/deploy/settings/build-manifest.js +80 -0
  55. package/dist/deploy/settings/build-manifest.js.map +1 -0
  56. package/dist/deploy/settings/index.d.ts.map +1 -1
  57. package/dist/deploy/settings/index.js +9 -3
  58. package/dist/deploy/settings/index.js.map +1 -1
  59. package/dist/deploy/settings/libraries.d.ts +8 -0
  60. package/dist/deploy/settings/libraries.d.ts.map +1 -0
  61. package/dist/deploy/settings/libraries.js +39 -0
  62. package/dist/deploy/settings/libraries.js.map +1 -0
  63. package/dist/deploy/settings/paths.d.ts +3 -0
  64. package/dist/deploy/settings/paths.d.ts.map +1 -1
  65. package/dist/deploy/settings/paths.js +6 -32
  66. package/dist/deploy/settings/paths.js.map +1 -1
  67. package/dist/deploy/targets/appimage.d.ts.map +1 -1
  68. package/dist/deploy/targets/appimage.js +19 -13
  69. package/dist/deploy/targets/appimage.js.map +1 -1
  70. package/dist/deploy/targets/flatpak-manifest.d.ts +2 -1
  71. package/dist/deploy/targets/flatpak-manifest.d.ts.map +1 -1
  72. package/dist/deploy/targets/flatpak-manifest.js +5 -1
  73. package/dist/deploy/targets/flatpak-manifest.js.map +1 -1
  74. package/dist/deploy/targets/flatpak-pnpm.js +4 -4
  75. package/dist/deploy/targets/flatpak-pnpm.js.map +1 -1
  76. package/dist/deploy/targets/flatpak-source.d.ts.map +1 -1
  77. package/dist/deploy/targets/flatpak-source.js +9 -6
  78. package/dist/deploy/targets/flatpak-source.js.map +1 -1
  79. package/dist/deploy/types.d.ts +4 -4
  80. package/dist/deploy/types.d.ts.map +1 -1
  81. package/dist/deploy/types.js.map +1 -1
  82. package/dist/dev/icon-dir.d.ts +1 -1
  83. package/dist/dev/icon-dir.d.ts.map +1 -1
  84. package/dist/dev/icon-dir.js +20 -7
  85. package/dist/dev/icon-dir.js.map +1 -1
  86. package/dist/dev/runner-deps.d.ts.map +1 -1
  87. package/dist/dev/runner-deps.js +5 -1
  88. package/dist/dev/runner-deps.js.map +1 -1
  89. package/dist/dev/runner-main.js +4 -4
  90. package/dist/dev/runner-main.js.map +1 -1
  91. package/dist/dev/runner.d.ts +1 -1
  92. package/dist/dev/runner.d.ts.map +1 -1
  93. package/dist/dev/runner.js +1 -1
  94. package/dist/dev/runner.js.map +1 -1
  95. package/dist/dev/schema-dir.d.ts +1 -1
  96. package/dist/dev/schema-dir.d.ts.map +1 -1
  97. package/dist/dev/schema-dir.js +3 -1
  98. package/dist/dev/schema-dir.js.map +1 -1
  99. package/dist/internal/build-manifest.d.ts +20 -0
  100. package/dist/internal/build-manifest.d.ts.map +1 -0
  101. package/dist/internal/build-manifest.js +6 -0
  102. package/dist/internal/build-manifest.js.map +1 -0
  103. package/dist/internal/icon-path.d.ts +13 -0
  104. package/dist/internal/icon-path.d.ts.map +1 -0
  105. package/dist/internal/icon-path.js +86 -0
  106. package/dist/internal/icon-path.js.map +1 -0
  107. package/dist/internal/source-imports.d.ts +8 -0
  108. package/dist/internal/source-imports.d.ts.map +1 -0
  109. package/dist/internal/source-imports.js +144 -0
  110. package/dist/internal/source-imports.js.map +1 -0
  111. package/dist/mcp/widget-properties.d.ts.map +1 -1
  112. package/dist/mcp/widget-properties.js +3 -12
  113. package/dist/mcp/widget-properties.js.map +1 -1
  114. package/dist/settings/render.d.ts +7 -1
  115. package/dist/settings/render.d.ts.map +1 -1
  116. package/dist/settings/render.js +69 -20
  117. package/dist/settings/render.js.map +1 -1
  118. package/dist/settings/schema.d.ts +4 -3
  119. package/dist/settings/schema.d.ts.map +1 -1
  120. package/dist/settings/schema.js +122 -15
  121. package/dist/settings/schema.js.map +1 -1
  122. package/dist/vite-plugins/asset-emitter.d.ts +1 -1
  123. package/dist/vite-plugins/asset-emitter.d.ts.map +1 -1
  124. package/dist/vite-plugins/asset-emitter.js.map +1 -1
  125. package/dist/vite-plugins/asset-extensions.d.ts.map +1 -1
  126. package/dist/vite-plugins/asset-extensions.js +1 -0
  127. package/dist/vite-plugins/asset-extensions.js.map +1 -1
  128. package/dist/vite-plugins/asset-imports.d.ts +2 -1
  129. package/dist/vite-plugins/asset-imports.d.ts.map +1 -1
  130. package/dist/vite-plugins/asset-imports.js +37 -16
  131. package/dist/vite-plugins/asset-imports.js.map +1 -1
  132. package/dist/vite-plugins/asset-specifier.d.ts +13 -1
  133. package/dist/vite-plugins/asset-specifier.d.ts.map +1 -1
  134. package/dist/vite-plugins/asset-specifier.js +39 -1
  135. package/dist/vite-plugins/asset-specifier.js.map +1 -1
  136. package/dist/vite-plugins/build-manifest.d.ts +5 -0
  137. package/dist/vite-plugins/build-manifest.d.ts.map +1 -0
  138. package/dist/vite-plugins/{bundled-packages.js → build-manifest.js} +20 -14
  139. package/dist/vite-plugins/build-manifest.js.map +1 -0
  140. package/dist/vite-plugins/built-url.d.ts +1 -1
  141. package/dist/vite-plugins/built-url.d.ts.map +1 -1
  142. package/dist/vite-plugins/built-url.js +37 -24
  143. package/dist/vite-plugins/built-url.js.map +1 -1
  144. package/dist/vite-plugins/icons.d.ts +2 -1
  145. package/dist/vite-plugins/icons.d.ts.map +1 -1
  146. package/dist/vite-plugins/icons.js +25 -12
  147. package/dist/vite-plugins/icons.js.map +1 -1
  148. package/dist/vite-plugins/index.d.ts +2 -1
  149. package/dist/vite-plugins/index.d.ts.map +1 -1
  150. package/dist/vite-plugins/index.js +7 -5
  151. package/dist/vite-plugins/index.js.map +1 -1
  152. package/dist/vite-plugins/native.d.ts.map +1 -1
  153. package/dist/vite-plugins/native.js +23 -4
  154. package/dist/vite-plugins/native.js.map +1 -1
  155. package/dist/vite-plugins/resource-init-module.d.ts +7 -3
  156. package/dist/vite-plugins/resource-init-module.d.ts.map +1 -1
  157. package/dist/vite-plugins/resource-init-module.js +39 -14
  158. package/dist/vite-plugins/resource-init-module.js.map +1 -1
  159. package/dist/vite-plugins/resource-shared.d.ts +3 -1
  160. package/dist/vite-plugins/resource-shared.d.ts.map +1 -1
  161. package/dist/vite-plugins/resource-shared.js +3 -1
  162. package/dist/vite-plugins/resource-shared.js.map +1 -1
  163. package/dist/vite-plugins/resources.d.ts +1 -1
  164. package/dist/vite-plugins/resources.d.ts.map +1 -1
  165. package/dist/vite-plugins/resources.js +922 -86
  166. package/dist/vite-plugins/resources.js.map +1 -1
  167. package/dist/vite-plugins/settings-worker-env.d.ts.map +1 -1
  168. package/dist/vite-plugins/settings-worker-env.js +6 -3
  169. package/dist/vite-plugins/settings-worker-env.js.map +1 -1
  170. package/dist/vite-plugins/settings.d.ts +3 -1
  171. package/dist/vite-plugins/settings.d.ts.map +1 -1
  172. package/dist/vite-plugins/settings.js +63 -23
  173. package/dist/vite-plugins/settings.js.map +1 -1
  174. package/dist/vite-plugins/store-links.js +1 -1
  175. package/dist/vite-plugins/store-links.js.map +1 -1
  176. package/dist/vite-plugins/undeclared-library.d.ts.map +1 -1
  177. package/dist/vite-plugins/undeclared-library.js +25 -13
  178. package/dist/vite-plugins/undeclared-library.js.map +1 -1
  179. package/env.d.ts +11 -192
  180. package/package.json +14 -14
  181. package/src/builder.ts +6 -7
  182. package/src/codegen/freshness.ts +1 -1
  183. package/src/codegen/run-codegen.ts +33 -10
  184. package/src/commands/build.ts +0 -5
  185. package/src/commands/codegen.ts +1 -3
  186. package/src/commands/docs.ts +3 -0
  187. package/src/deploy/depends.ts +47 -18
  188. package/src/deploy/nfpm/config.ts +1 -1
  189. package/src/deploy/node-runtime/elf.ts +3 -3
  190. package/src/deploy/node-runtime/index.ts +2 -2
  191. package/src/deploy/notices/collect.ts +4 -2
  192. package/src/deploy/notices/packages.ts +5 -43
  193. package/src/deploy/payload/icons.ts +64 -34
  194. package/src/deploy/payload/stage.ts +5 -2
  195. package/src/deploy/run-deploy.ts +87 -12
  196. package/src/deploy/settings/build-manifest.ts +122 -0
  197. package/src/deploy/settings/index.ts +9 -4
  198. package/src/deploy/settings/libraries.ts +57 -0
  199. package/src/deploy/settings/paths.ts +10 -47
  200. package/src/deploy/targets/appimage.ts +32 -15
  201. package/src/deploy/targets/flatpak-manifest.ts +7 -1
  202. package/src/deploy/targets/flatpak-pnpm.ts +4 -4
  203. package/src/deploy/targets/flatpak-source.ts +9 -10
  204. package/src/deploy/types.ts +4 -4
  205. package/src/dev/icon-dir.ts +31 -7
  206. package/src/dev/runner-deps.ts +5 -1
  207. package/src/dev/runner-main.ts +4 -4
  208. package/src/dev/runner.ts +2 -2
  209. package/src/dev/schema-dir.ts +3 -1
  210. package/src/internal/build-manifest.ts +32 -0
  211. package/src/internal/icon-path.ts +127 -0
  212. package/src/internal/source-imports.ts +200 -0
  213. package/src/mcp/widget-properties.ts +3 -14
  214. package/src/settings/render.ts +99 -21
  215. package/src/settings/schema.ts +190 -17
  216. package/src/vite-plugins/asset-emitter.ts +1 -1
  217. package/src/vite-plugins/asset-extensions.ts +1 -0
  218. package/src/vite-plugins/asset-imports.ts +60 -19
  219. package/src/vite-plugins/asset-specifier.ts +73 -1
  220. package/src/vite-plugins/{bundled-packages.ts → build-manifest.ts} +30 -19
  221. package/src/vite-plugins/built-url.ts +49 -28
  222. package/src/vite-plugins/icons.ts +33 -14
  223. package/src/vite-plugins/index.ts +12 -5
  224. package/src/vite-plugins/native.ts +31 -4
  225. package/src/vite-plugins/resource-init-module.ts +44 -15
  226. package/src/vite-plugins/resource-shared.ts +4 -0
  227. package/src/vite-plugins/resources.ts +1459 -100
  228. package/src/vite-plugins/settings-worker-env.ts +7 -3
  229. package/src/vite-plugins/settings.ts +89 -21
  230. package/src/vite-plugins/store-links.ts +1 -1
  231. package/src/vite-plugins/undeclared-library.ts +31 -13
  232. package/dist/vite-plugins/bundled-packages.d.ts +0 -5
  233. package/dist/vite-plugins/bundled-packages.d.ts.map +0 -1
  234. package/dist/vite-plugins/bundled-packages.js.map +0 -1
@@ -1,20 +1,177 @@
1
- import { createConfigLoader } from "@gtkx/config/internal";
2
- import { error, info, sortStrings } from "@gtkx/utils";
3
- import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
- import { dirname, join } from "node:path";
1
+ import { createConfigLoader, resourceBasePath } from "@gtkx/config/internal";
2
+ import { error, info, isRecord, sortStrings } from "@gtkx/utils";
3
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { basename, dirname, extname, isAbsolute, join, posix, relative, sep } from "node:path";
5
+ import { parseSync } from "vite";
5
6
  import { resolveDataDir } from "../internal/data-dir.js";
6
7
  import { listFilesRecursive } from "../internal/list-files.js";
7
- import { loadModuleExclusively } from "../internal/module-loads.js";
8
8
  import { runCliTool } from "../internal/run-cli-tool.js";
9
+ import { parseRuntimeImportsIn } from "../internal/source-imports.js";
9
10
  import { createRetainedStagingDir, withStagingDir } from "../internal/staging-dir.js";
10
11
  import { ASSET_RE } from "./asset-extensions.js";
11
- import { DATA_PREFIX, isDataAsset } from "./asset-specifier.js";
12
+ import { DATA_PREFIX, isBareRelativeAsset, isDataAsset, parseIconSpecifier, parseResourceSpecifier, } from "./asset-specifier.js";
12
13
  import { renderInitModule } from "./resource-init-module.js";
13
- import { BUNDLE_FILENAME, escapeXml, fromVirtualId, isVirtual, REFRESH_EXPORT, REL_SEPARATOR, RESOURCE_PATH_EXPORT, toVirtualId, VIRTUAL_INIT, } from "./resource-shared.js";
14
+ import { BUNDLE_FILENAME, escapeXml, fromVirtualId, ICON_NAME_SEPARATOR, isVirtual, REFRESH_EXPORT, REGISTER_REFRESH_EXPORT, REL_SEPARATOR, RESOURCE_PATH_EXPORT, toVirtualId, VIRTUAL_INIT, } from "./resource-shared.js";
15
+ import { stripQuery } from "./strip-query.js";
14
16
  const RESOURCE_COMPILER = "glib-compile-resources";
15
17
  const MANIFEST_PREFIX = "/";
16
18
  const DEV_STAGING_PREFIX = "resources-dev";
17
- const deriveResourcePrefix = (applicationId) => `/${applicationId.replaceAll(".", "/")}`;
19
+ const MANIFEST_FILENAME = "package.json";
20
+ const BUNDLED_QUERY_MENTION_RE = /[?&](?:icon|resource)(?:[=&]|$)/;
21
+ const ICON_EXTENSIONS = new Set([".png", ".svg", ".xpm"]);
22
+ const ICON_CONTEXTS = new Set([
23
+ "actions",
24
+ "animations",
25
+ "apps",
26
+ "categories",
27
+ "devices",
28
+ "emblems",
29
+ "emotes",
30
+ "filesystems",
31
+ "intl",
32
+ "mimetypes",
33
+ "places",
34
+ "status",
35
+ ]);
36
+ const STOCK_ICON_CONTEXTS = new Set([
37
+ "chart",
38
+ "code",
39
+ "data",
40
+ "form",
41
+ "image",
42
+ "io",
43
+ "media",
44
+ "navigation",
45
+ "net",
46
+ "object",
47
+ "table",
48
+ "text",
49
+ ]);
50
+ const ICON_SIZE_RE = /^([1-9]\d*)x\1(?:@[1-9]\d*)?$/;
51
+ const RESERVED_ICON_NAMES = new Set(["", ".", ".."]);
52
+ const SOURCE_LANGUAGES = new Map([
53
+ [".cjs", "jsx"],
54
+ [".cts", "ts"],
55
+ [".js", "jsx"],
56
+ [".jsx", "jsx"],
57
+ [".mjs", "jsx"],
58
+ [".mts", "ts"],
59
+ [".ts", "ts"],
60
+ [".tsx", "tsx"],
61
+ ]);
62
+ const toForwardSlashes = (value) => value.replaceAll(/[/\\]/g, "/");
63
+ const isWithin = (root, path) => {
64
+ const rel = relative(root, path);
65
+ return rel.length > 0 && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
66
+ };
67
+ const isDependencyFile = (root, path) => isWithin(root, path) && relative(root, path).split(sep).includes("node_modules");
68
+ const packageIdentityIn = (dir) => {
69
+ try {
70
+ const manifest = JSON.parse(readFileSync(join(dir, MANIFEST_FILENAME), "utf8"));
71
+ return isRecord(manifest) && typeof manifest.name === "string" ? manifest.name : null;
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ };
77
+ const packageIn = (dir) => {
78
+ const name = packageIdentityIn(dir);
79
+ if (name !== null) {
80
+ return { dir, name };
81
+ }
82
+ const parent = dirname(dir);
83
+ return parent === dir ? null : packageIn(parent);
84
+ };
85
+ const packageForFile = (file) => packageIn(dirname(file));
86
+ const validateResourcePath = (resourcePath) => {
87
+ if (resourcePath === "/" ||
88
+ !resourcePath.startsWith("/") ||
89
+ resourcePath.endsWith("/") ||
90
+ resourcePath.includes("\0") ||
91
+ posix.normalize(resourcePath) !== resourcePath) {
92
+ throw new Error(`${JSON.stringify(resourcePath)} is not a valid GResource path; use an absolute normalized path`);
93
+ }
94
+ return resourcePath;
95
+ };
96
+ const derivedResourcePath = (state, sourcePath) => {
97
+ if (isWithin(state.root, sourcePath) && !isDependencyFile(state.root, sourcePath)) {
98
+ return validateResourcePath(`${state.prefix}/${toForwardSlashes(relative(state.root, sourcePath))}`);
99
+ }
100
+ const owner = packageForFile(sourcePath);
101
+ if (owner === null || !isWithin(owner.dir, sourcePath)) {
102
+ throw new Error(`${sourcePath} is outside the application and does not belong to a named package`);
103
+ }
104
+ const packagePath = toForwardSlashes(relative(owner.dir, sourcePath));
105
+ return validateResourcePath(`${state.prefix}/${owner.name}/${packagePath}`);
106
+ };
107
+ const iconExtension = (sourcePath) => {
108
+ const extension = extname(sourcePath).toLowerCase();
109
+ if (!ICON_EXTENSIONS.has(extension)) {
110
+ throw new Error(`${sourcePath} is not a supported themed icon; use an SVG, PNG, or XPM file`);
111
+ }
112
+ return extension;
113
+ };
114
+ const hasIconNamePathSeparator = (value) => value.includes("\0") || value.includes("/") || value.includes("\\");
115
+ const validateIconName = (value) => {
116
+ if (RESERVED_ICON_NAMES.has(value) ||
117
+ hasIconNamePathSeparator(value) ||
118
+ ICON_EXTENSIONS.has(extname(value).toLowerCase())) {
119
+ throw new Error(`${JSON.stringify(value)} is not a valid icon name; use an extensionless filename without slashes`);
120
+ }
121
+ return value;
122
+ };
123
+ const isIconContext = (parts) => {
124
+ const [first, second] = parts;
125
+ if (parts.length === 1) {
126
+ return first !== undefined && ICON_CONTEXTS.has(first);
127
+ }
128
+ return parts.length === 2 && first === "stock" && second !== undefined && STOCK_ICON_CONTEXTS.has(second);
129
+ };
130
+ const isIconLayout = (parts) => {
131
+ const [size, ...context] = parts;
132
+ if (size === "symbolic") {
133
+ return context.length === 1 && context[0] === "apps";
134
+ }
135
+ return size !== undefined && (size === "scalable" || ICON_SIZE_RE.test(size)) && isIconContext(context);
136
+ };
137
+ const iconLayoutInParts = (parts, beforeIndex) => {
138
+ const index = parts.lastIndexOf("icons", beforeIndex);
139
+ if (index === -1) {
140
+ return null;
141
+ }
142
+ const treePath = parts.slice(index + 1, -1);
143
+ const layout = treePath[0] === "hicolor" ? treePath.slice(1) : treePath;
144
+ return isIconLayout(layout) ? layout.join("/") : iconLayoutInParts(parts, index - 1);
145
+ };
146
+ const iconLayoutFromTree = (sourcePath) => {
147
+ const parts = toForwardSlashes(sourcePath).split("/");
148
+ return iconLayoutInParts(parts, parts.length - 2);
149
+ };
150
+ const derivedIconEntry = (state, sourcePath, requestedName) => {
151
+ const extension = iconExtension(sourcePath);
152
+ const sourceName = basename(sourcePath, extname(sourcePath));
153
+ const iconName = validateIconName(requestedName ?? sourceName);
154
+ const layout = iconLayoutFromTree(sourcePath);
155
+ const iconIdentity = layout === null
156
+ ? `${state.prefix}/icons/${iconName}`
157
+ : `${state.prefix}/icons/${layout}/${iconName}`;
158
+ const resourcePath = validateResourcePath(`${iconIdentity}${extension}`);
159
+ return { iconIdentity, iconName, resourcePath };
160
+ };
161
+ const hasSideEffectIconImport = (code, id) => {
162
+ const lang = SOURCE_LANGUAGES.get(extname(stripQuery(id)).toLowerCase());
163
+ if (lang === undefined || !code.includes("?icon")) {
164
+ return false;
165
+ }
166
+ const parsed = parseSync(id, code, { lang });
167
+ if (parsed.errors.length > 0) {
168
+ return false;
169
+ }
170
+ return parsed.module.staticImports.some((statement) => statement.entries.length === 0 && parseIconSpecifier(statement.moduleRequest.value) !== null);
171
+ };
172
+ const retainSideEffectIconImport = (state, code, id) => state.isV2 && hasSideEffectIconImport(code, id)
173
+ ? { code, moduleSideEffects: true }
174
+ : null;
18
175
  const compileBundle = (state, outputPath) => withStagingDir("resources", (dir) => {
19
176
  const manifest = stageBundle(dir, state.entries);
20
177
  return runCompiler(dir, manifest, outputPath);
@@ -56,29 +213,30 @@ const releaseStagingDir = (state) => {
56
213
  state.devBundlePath = "";
57
214
  state.compiledSignature = "";
58
215
  };
59
- const entriesSignature = (state) => sortStrings(state.entries.keys()).join("\0");
216
+ const entriesSignature = (state) => sortStrings([...state.entries].map(([resourcePath, entry]) => `${resourcePath}\0${entry.sourcePath}`)).join("\0");
60
217
  const compileDevBundle = (state) => {
61
218
  ensureStagingDir(state);
62
219
  if (state.entries.size === 0) {
220
+ rmSync(state.devBundlePath, { force: true });
221
+ state.compiledSignature = "";
63
222
  return;
64
223
  }
65
224
  compileBundle(state, state.devBundlePath);
66
225
  state.compiledSignature = entriesSignature(state);
67
226
  };
68
227
  const isRefreshHook = (value) => typeof value === "function";
69
- const reregisterDevBundle = async (state) => {
228
+ const refreshRegisteredDevBundle = (state) => {
70
229
  const server = state.server;
71
230
  if (!server) {
72
231
  return;
73
232
  }
74
- const mod = await loadModuleExclusively(server, VIRTUAL_INIT);
75
- const refresh = mod[REFRESH_EXPORT];
233
+ const refresh = server.moduleGraph.getModuleById(VIRTUAL_INIT)?.ssrModule?.[REFRESH_EXPORT];
76
234
  if (isRefreshHook(refresh)) {
77
235
  refresh();
78
236
  }
79
237
  };
80
238
  const scanDataAssets = (dataDir) => listFilesRecursive(dataDir, (name) => ASSET_RE.test(name));
81
- const primeDevBundle = (state) => {
239
+ const primeLegacyDevBundle = (state) => {
82
240
  if (state.dataDir === null) {
83
241
  return;
84
242
  }
@@ -92,102 +250,683 @@ const registerDevAsset = (state) => {
92
250
  compileDevBundle(state);
93
251
  }
94
252
  };
95
- const registerEntry = (state, absPath, rel) => {
96
- const existing = state.entries.get(absPath);
97
- if (existing) {
253
+ const importerKey = (importer) => stripQuery(importer);
254
+ const claimEntry = (state, resourcePath, importer) => {
255
+ if (importer === undefined) {
256
+ return;
257
+ }
258
+ const importers = state.entryImporters.get(resourcePath) ?? new Set();
259
+ importers.add(importerKey(importer));
260
+ state.entryImporters.set(resourcePath, importers);
261
+ };
262
+ const trackBundledSpecifier = (state, importer, source) => {
263
+ if (importer === undefined) {
264
+ return;
265
+ }
266
+ const key = importerKey(importer);
267
+ const specifiers = state.bundledSpecifiers.get(key) ?? new Set();
268
+ specifiers.add(source);
269
+ state.bundledSpecifiers.set(key, specifiers);
270
+ };
271
+ const claimIcon = (state, iconIdentity, importer) => {
272
+ if (importer === undefined) {
273
+ return;
274
+ }
275
+ const importers = state.iconImporters.get(iconIdentity) ?? new Set();
276
+ importers.add(importerKey(importer));
277
+ state.iconImporters.set(iconIdentity, importers);
278
+ };
279
+ const createResourceEntry = (sourcePath, resourcePath) => ({
280
+ sourcePath,
281
+ stagedRelPath: resourcePath.replace(/^\/+/, ""),
282
+ resourcePath,
283
+ });
284
+ const activateEntry = (state, entry, importer) => {
285
+ const existing = state.entries.get(entry.resourcePath);
286
+ if (existing !== undefined) {
287
+ if (existing.sourcePath !== entry.sourcePath) {
288
+ throw new Error(`${existing.sourcePath} and ${entry.sourcePath} both resolve to the GResource path ` +
289
+ entry.resourcePath);
290
+ }
291
+ claimEntry(state, entry.resourcePath, importer);
98
292
  return existing;
99
293
  }
100
- const resourcePath = `${state.prefix}/${rel}`;
101
- const entry = {
102
- sourcePath: absPath,
103
- stagedRelPath: resourcePath.replace(/^\/+/, ""),
104
- resourcePath,
105
- };
106
- state.entries.set(absPath, entry);
107
- state.sourcePaths.add(absPath);
294
+ state.entries.set(entry.resourcePath, entry);
295
+ state.sourcePaths.add(entry.sourcePath);
296
+ claimEntry(state, entry.resourcePath, importer);
297
+ return entry;
298
+ };
299
+ const isDeclarativeImporter = (state, importer) => !state.isBuild && state.isV2 && importer !== undefined;
300
+ const setSourceAvailability = (state, file, isAvailable) => {
301
+ if (isAvailable) {
302
+ state.missingSourcePaths.delete(file);
303
+ return;
304
+ }
305
+ state.missingSourcePaths.add(file);
306
+ };
307
+ const isDeclaredSourceAvailable = (state, sourcePath) => {
308
+ const isAvailable = existsSync(sourcePath);
309
+ setSourceAvailability(state, sourcePath, isAvailable);
310
+ return isAvailable;
311
+ };
312
+ const declareEntry = (state, importer, entry) => {
313
+ const key = importerKey(importer);
314
+ const declarations = state.declaredEntries.get(key) ?? new Map();
315
+ const existing = declarations.get(entry.resourcePath);
316
+ if (existing !== undefined && existing.sourcePath !== entry.sourcePath) {
317
+ throw new Error(`${existing.sourcePath} and ${entry.sourcePath} both resolve to the GResource path ` +
318
+ entry.resourcePath);
319
+ }
320
+ const declared = existing ?? entry;
321
+ declarations.set(entry.resourcePath, declared);
322
+ state.declaredEntries.set(key, declarations);
323
+ state.server?.watcher.add(dirname(declared.sourcePath));
324
+ return declared;
325
+ };
326
+ const declareIcon = (state, importer, iconIdentity, entry) => {
327
+ const key = importerKey(importer);
328
+ const declarations = state.declaredIcons.get(key) ?? new Map();
329
+ const existing = declarations.get(iconIdentity);
330
+ if (existing !== undefined && existing.sourcePath !== entry.sourcePath) {
331
+ throw new Error(`${existing.sourcePath} and ${entry.sourcePath} both claim the themed icon ${iconIdentity}`);
332
+ }
333
+ declarations.set(iconIdentity, existing ?? entry);
334
+ state.declaredIcons.set(key, declarations);
335
+ };
336
+ const assertIconIdentityAvailable = (state, iconIdentity, sourcePath) => {
337
+ const existing = state.iconOwners.get(iconIdentity);
338
+ if (existing !== undefined && existing.sourcePath !== sourcePath) {
339
+ throw new Error(`${existing.sourcePath} and ${sourcePath} both claim the themed icon ${iconIdentity}`);
340
+ }
341
+ };
342
+ const declareResolvedIcon = (state, importer, iconIdentity, entry) => {
343
+ if (isDeclarativeImporter(state, importer)) {
344
+ declareIcon(state, importer, iconIdentity, entry);
345
+ }
346
+ };
347
+ const activateIcon = (state, importer, iconIdentity, entry) => {
348
+ state.iconOwners.set(iconIdentity, entry);
349
+ claimIcon(state, iconIdentity, importer);
350
+ };
351
+ const registerEntry = (state, absPath, rel, importer) => {
352
+ const resourcePath = validateResourcePath(rel.startsWith("/") ? rel : `${state.prefix}/${rel}`);
353
+ let entry = createResourceEntry(absPath, resourcePath);
354
+ if (isDeclarativeImporter(state, importer)) {
355
+ entry = declareEntry(state, importer, entry);
356
+ if (!isImporterActive(state, importer) || !isDeclaredSourceAvailable(state, absPath)) {
357
+ return entry;
358
+ }
359
+ }
360
+ return activateEntry(state, entry, importer);
361
+ };
362
+ const registerIconEntry = (state, sourcePath, derived, importer) => {
363
+ const shouldActivate = !isDeclarativeImporter(state, importer) ||
364
+ (isImporterActive(state, importer) && isDeclaredSourceAvailable(state, sourcePath));
365
+ if (shouldActivate) {
366
+ assertIconIdentityAvailable(state, derived.iconIdentity, sourcePath);
367
+ }
368
+ const entry = registerEntry(state, sourcePath, derived.resourcePath, importer);
369
+ declareResolvedIcon(state, importer, derived.iconIdentity, entry);
370
+ if (shouldActivate) {
371
+ activateIcon(state, importer, derived.iconIdentity, entry);
372
+ }
108
373
  return entry;
109
374
  };
110
375
  const isTrackedSource = (state, file) => state.sourcePaths.has(file);
111
- const resolvedAssetId = (resolved, source) => {
376
+ const hasSourceEntry = (entries, file) => {
377
+ for (const entry of entries.values()) {
378
+ if (entry.sourcePath === file) {
379
+ return true;
380
+ }
381
+ }
382
+ return false;
383
+ };
384
+ const hasDeclaredSource = (declarations, file) => {
385
+ for (const entries of declarations.values()) {
386
+ if (hasSourceEntry(entries, file)) {
387
+ return true;
388
+ }
389
+ }
390
+ return false;
391
+ };
392
+ const isDeclaredSource = (state, file) => hasDeclaredSource(state.declaredEntries, file) || hasDeclaredSource(state.declaredIcons, file);
393
+ const virtualAssetId = (entry) => toVirtualId(entry.sourcePath) + REL_SEPARATOR + entry.resourcePath;
394
+ const virtualIconId = ({ entry, iconName }) => virtualAssetId(entry) + ICON_NAME_SEPARATOR + iconName;
395
+ const resolveAssetSource = async (ctx, request) => {
396
+ const resolved = await ctx.resolve(request.assetSource, request.importer, {
397
+ ...request.options,
398
+ skipSelf: true,
399
+ });
400
+ if (!resolved || resolved.external) {
401
+ return undefined;
402
+ }
403
+ const sourcePath = stripQuery(resolved.id);
404
+ if (!isAbsolute(sourcePath)) {
405
+ throw new Error(`${JSON.stringify(request.assetSource)} did not resolve to a file-backed asset`);
406
+ }
407
+ return sourcePath;
408
+ };
409
+ const resolveAssetEntry = async (ctx, state, request) => {
410
+ const sourcePath = await resolveAssetSource(ctx, request);
411
+ if (sourcePath === undefined) {
412
+ return undefined;
413
+ }
414
+ return registerEntry(state, sourcePath, request.resourcePath === null
415
+ ? derivedResourcePath(state, sourcePath)
416
+ : validateResourcePath(request.resourcePath), request.importer);
417
+ };
418
+ const resolveIconEntry = async (ctx, state, request) => {
419
+ const sourcePath = await resolveAssetSource(ctx, request);
420
+ if (sourcePath === undefined) {
421
+ return undefined;
422
+ }
423
+ const derived = derivedIconEntry(state, sourcePath, request.iconName);
424
+ return {
425
+ entry: registerIconEntry(state, sourcePath, derived, request.importer),
426
+ iconName: derived.iconName,
427
+ };
428
+ };
429
+ const resolveLegacyAssetEntry = async (ctx, state, request) => {
430
+ const resolved = await ctx.resolve(request.source, request.importer, { ...request.options, skipSelf: true });
112
431
  if (!resolved || resolved.external) {
113
432
  return undefined;
114
433
  }
115
- return toVirtualId(resolved.id) + REL_SEPARATOR + source.slice(DATA_PREFIX.length);
434
+ const sourcePath = stripQuery(resolved.id);
435
+ if (!isAbsolute(sourcePath)) {
436
+ return undefined;
437
+ }
438
+ return registerEntry(state, sourcePath, request.source.slice(DATA_PREFIX.length));
116
439
  };
117
440
  const loadInitModule = (state) => {
118
- if (!state.isBuild) {
119
- ensureStagingDir(state);
441
+ if (state.isBuild) {
442
+ if (state.bundleReferenceId === null) {
443
+ throw new Error("Cannot render the GResource loader before its bundle has been emitted");
444
+ }
445
+ return renderInitModule({ isBuild: true, bundleReferenceId: state.bundleReferenceId });
120
446
  }
121
- return renderInitModule({ isBuild: state.isBuild, devBundlePath: state.devBundlePath });
447
+ ensureStagingDir(state);
448
+ return renderInitModule({ isBuild: false, devBundlePath: state.devBundlePath });
122
449
  };
123
- const loadAssetModule = (state, virtualId) => {
450
+ const virtualAssetMetadata = (virtualId) => {
124
451
  const rest = fromVirtualId(virtualId);
125
452
  const separatorIndex = rest.indexOf(REL_SEPARATOR);
126
- const absPath = rest.slice(0, separatorIndex);
127
- const rel = rest.slice(separatorIndex + REL_SEPARATOR.length);
128
- const entry = registerEntry(state, absPath, rel);
129
- const uri = `resource://${entry.resourcePath}`;
130
- if (!state.isBuild) {
453
+ const relAndMetadata = rest.slice(separatorIndex + REL_SEPARATOR.length);
454
+ const iconSeparatorIndex = relAndMetadata.indexOf(ICON_NAME_SEPARATOR);
455
+ return {
456
+ absPath: rest.slice(0, separatorIndex),
457
+ iconName: iconSeparatorIndex === -1
458
+ ? null
459
+ : relAndMetadata.slice(iconSeparatorIndex + ICON_NAME_SEPARATOR.length),
460
+ rel: iconSeparatorIndex === -1 ? relAndMetadata : relAndMetadata.slice(0, iconSeparatorIndex),
461
+ };
462
+ };
463
+ const resourcePathExport = (entry, iconName) => iconName === null ? [`export const ${RESOURCE_PATH_EXPORT} = ${JSON.stringify(entry.resourcePath)};`] : [];
464
+ const assetModuleImports = (iconName) => {
465
+ const initBindings = iconName === null
466
+ ? "ensureRegistered"
467
+ : `ensureRegistered, ${REGISTER_REFRESH_EXPORT}`;
468
+ return [
469
+ `import { ${initBindings} } from ${JSON.stringify(VIRTUAL_INIT)};`,
470
+ ...(iconName === null
471
+ ? []
472
+ : [
473
+ "import { Display } from \"@gtkx/gi/gdk\";",
474
+ "import { IconTheme } from \"@gtkx/gi/gtk\";",
475
+ ]),
476
+ ];
477
+ };
478
+ const iconThemeRegistration = (state, iconName) => {
479
+ if (iconName === null) {
480
+ return [];
481
+ }
482
+ const resourceIconPath = `${state.prefix}/icons`;
483
+ return [
484
+ `const resourceIconPath = ${JSON.stringify(resourceIconPath)};`,
485
+ "function refreshIconTheme() {",
486
+ " const display = Display.getDefault();",
487
+ " if (!display) return;",
488
+ " const theme = IconTheme.getForDisplay(display);",
489
+ " const paths = theme.getResourcePath() ?? [];",
490
+ " theme.setResourcePath(paths.includes(resourceIconPath) ? [...paths] : [...paths, resourceIconPath]);",
491
+ "}",
492
+ `${REGISTER_REFRESH_EXPORT}(resourceIconPath, refreshIconTheme);`,
493
+ ];
494
+ };
495
+ const loadedResourceEntry = (state, sourcePath, resourcePath) => {
496
+ const registered = state.entries.get(resourcePath);
497
+ if (registered === undefined) {
498
+ return { entry: createResourceEntry(sourcePath, resourcePath), isRegistered: false };
499
+ }
500
+ if (registered.sourcePath !== sourcePath) {
501
+ throw new Error(`${registered.sourcePath} and ${sourcePath} both resolve to the GResource path ${resourcePath}`);
502
+ }
503
+ return { entry: registered, isRegistered: true };
504
+ };
505
+ const compileLoadedDevAsset = (state, isRegistered) => {
506
+ if (isRegistered && !state.isBuild) {
131
507
  registerDevAsset(state);
132
508
  }
509
+ };
510
+ const loadAssetModule = (state, virtualId) => {
511
+ const { absPath, iconName, rel } = virtualAssetMetadata(virtualId);
512
+ const resourcePath = validateResourcePath(rel);
513
+ const { entry, isRegistered } = loadedResourceEntry(state, absPath, resourcePath);
514
+ const uri = `resource://${entry.resourcePath}`;
515
+ const defaultValue = iconName ?? (state.isV2 ? entry.resourcePath : uri);
516
+ compileLoadedDevAsset(state, isRegistered);
133
517
  return [
134
- `import { ensureRegistered } from ${JSON.stringify(VIRTUAL_INIT)};`,
518
+ ...assetModuleImports(iconName),
135
519
  "ensureRegistered();",
136
- `export default ${JSON.stringify(uri)};`,
137
- `export const ${RESOURCE_PATH_EXPORT} = ${JSON.stringify(entry.resourcePath)};`,
520
+ ...iconThemeRegistration(state, iconName),
521
+ `export default ${JSON.stringify(defaultValue)};`,
522
+ ...resourcePathExport(entry, iconName),
138
523
  ].join("\n");
139
524
  };
140
- const emitBuildBundle = (ctx, state) => {
141
- if (!state.isBuild || state.entries.size === 0) {
525
+ const finalizeBuildBundle = (ctx, bundle, state) => {
526
+ if (!state.isBuild || state.bundleReferenceId === null) {
527
+ return;
528
+ }
529
+ const fileName = ctx.getFileName(state.bundleReferenceId);
530
+ const output = bundle[fileName];
531
+ if (output?.type !== "asset") {
532
+ throw new Error(`Cannot find the emitted ${BUNDLE_FILENAME} asset`);
533
+ }
534
+ if (state.entries.size === 0) {
535
+ Reflect.deleteProperty(bundle, fileName);
142
536
  return;
143
537
  }
144
538
  const compiled = withStagingDir("resources-out", (outDir) => compileBundle(state, join(outDir, BUNDLE_FILENAME)));
145
- ctx.emitFile({ type: "asset", fileName: BUNDLE_FILENAME, source: compiled });
539
+ output.source = compiled;
146
540
  info(`Compiled ${String(state.entries.size)} resource(s) into ${BUNDLE_FILENAME}`);
147
541
  };
148
- const refreshDevRegistration = async (state) => {
542
+ const refreshDevRegistration = (state) => {
149
543
  compileDevBundle(state);
150
544
  try {
151
- await reregisterDevBundle(state);
545
+ refreshRegisteredDevBundle(state);
152
546
  }
153
547
  catch (error_) {
154
548
  error("Failed to refresh GResource bundle:", error_);
155
549
  }
156
550
  };
551
+ const isSameSpecifiers = (left, right) => left === undefined
552
+ ? right.size === 0
553
+ : left.size === right.size && [...right].every((source) => left.has(source));
554
+ const bundledSpecifiersIn = (imports) => new Set(imports
555
+ .filter((entry) => parseResourceSpecifier(entry.source) !== null || parseIconSpecifier(entry.source) !== null)
556
+ .map((entry) => entry.source));
557
+ const isSourceModule = (file) => !file.endsWith(".d.ts") && !file.endsWith(".d.cts") && !file.endsWith(".d.mts") &&
558
+ SOURCE_LANGUAGES.has(extname(file).toLowerCase());
559
+ const isBundledSource = (source) => parseResourceSpecifier(source) !== null || parseIconSpecifier(source) !== null;
560
+ const validateUnbundledV2Source = (source) => {
561
+ if (isLegacyDataSpecifier(source)) {
562
+ throw new Error(`${JSON.stringify(source)} uses the legacy #data asset form`);
563
+ }
564
+ rejectInvalidV2Specifier(source);
565
+ };
566
+ const resolvedModuleDependency = async (ctx, source, importer) => {
567
+ if (isBundledSource(source)) {
568
+ return null;
569
+ }
570
+ validateUnbundledV2Source(source);
571
+ const resolved = await ctx.resolve(source, importer, { skipSelf: true });
572
+ if (resolved === null) {
573
+ throw new Error(`${JSON.stringify(source)} could not be resolved from ${importer}`);
574
+ }
575
+ return resolved.external ? null : importerKey(resolved.id);
576
+ };
577
+ const resolvedModuleDependencies = async (ctx, imports, importer) => {
578
+ const dependencies = new Set();
579
+ for (const entry of imports) {
580
+ const dependency = await resolvedModuleDependency(ctx, entry.source, importer);
581
+ if (dependency !== null) {
582
+ dependencies.add(dependency);
583
+ }
584
+ }
585
+ return dependencies;
586
+ };
587
+ const importerReconciliation = async (ctx, state, id) => {
588
+ const file = stripQuery(id);
589
+ const key = importerKey(file);
590
+ if (!state.isV2 || state.isBuild || !isSourceModule(file)) {
591
+ return null;
592
+ }
593
+ const imports = parseRuntimeImportsIn(file);
594
+ if (imports === null) {
595
+ return null;
596
+ }
597
+ return {
598
+ currentBundled: bundledSpecifiersIn(imports),
599
+ currentDependencies: await resolvedModuleDependencies(ctx, imports, file),
600
+ file,
601
+ imports,
602
+ key,
603
+ previousBundled: state.bundledSpecifiers.get(key),
604
+ previousDependencies: state.moduleDependencies.get(key),
605
+ };
606
+ };
607
+ const moduleNodeKey = (module) => importerKey(module.id ?? module.file ?? module.url);
608
+ const moduleNodeFor = (state, id) => {
609
+ const server = state.server;
610
+ if (server === null) {
611
+ return undefined;
612
+ }
613
+ return server.moduleGraph.getModuleById(id) ?? server.moduleGraph.getModuleById(importerKey(id));
614
+ };
615
+ const restoreDependencies = (pruned, current) => {
616
+ for (const dependency of current) {
617
+ pruned.delete(dependency);
618
+ }
619
+ };
620
+ const pruneRemovedDependencies = (pruned, previous, current) => {
621
+ if (previous === undefined) {
622
+ return;
623
+ }
624
+ for (const dependency of previous) {
625
+ if (!current.has(dependency)) {
626
+ pruned.add(dependency);
627
+ }
628
+ }
629
+ };
630
+ const storePrunedDependencies = (state, key, pruned) => {
631
+ if (pruned.size === 0) {
632
+ state.prunedDependencies.delete(key);
633
+ return;
634
+ }
635
+ state.prunedDependencies.set(key, pruned);
636
+ };
637
+ const updatePrunedDependencies = (state, key, previous, current) => {
638
+ const pruned = state.prunedDependencies.get(key) ?? new Set();
639
+ restoreDependencies(pruned, current);
640
+ pruneRemovedDependencies(pruned, previous, current);
641
+ storePrunedDependencies(state, key, pruned);
642
+ };
643
+ const isPrunedDependency = (state, importer, imported) => state.prunedDependencies.get(moduleNodeKey(importer))?.has(moduleNodeKey(imported)) === true;
644
+ const fallbackRootModules = (state) => {
645
+ const roots = [];
646
+ for (const key of state.moduleDependencies.keys()) {
647
+ if (moduleNodeFor(state, key)?.importers.size === 0) {
648
+ roots.push(key);
649
+ }
650
+ }
651
+ return roots;
652
+ };
653
+ const enqueueCurrentDependencies = (state, key, pending) => {
654
+ const dependencies = state.moduleDependencies.get(key) ?? [];
655
+ for (const dependency of dependencies) {
656
+ pending.push(dependency);
657
+ }
658
+ };
659
+ const enqueueGraphDependencies = (state, key, pending) => {
660
+ const module = moduleNodeFor(state, key);
661
+ if (module === undefined) {
662
+ return;
663
+ }
664
+ for (const imported of module.importedModules) {
665
+ if (!isPrunedDependency(state, module, imported)) {
666
+ pending.push(moduleNodeKey(imported));
667
+ }
668
+ }
669
+ };
670
+ const visitActiveImporter = (state, active, pending, key) => {
671
+ if (active.has(key)) {
672
+ return;
673
+ }
674
+ active.add(key);
675
+ enqueueCurrentDependencies(state, key, pending);
676
+ enqueueGraphDependencies(state, key, pending);
677
+ };
678
+ const activeImporterKeys = (state) => {
679
+ const active = new Set();
680
+ const roots = state.entryModule === null ? fallbackRootModules(state) : [state.entryModule];
681
+ const pending = [...roots];
682
+ while (pending.length > 0) {
683
+ const key = pending.pop();
684
+ if (key === undefined || active.has(key)) {
685
+ continue;
686
+ }
687
+ visitActiveImporter(state, active, pending, key);
688
+ }
689
+ return active;
690
+ };
691
+ const isImporterActive = (state, importer) => activeImporterKeys(state).has(importerKey(importer));
692
+ const activateDeclaredIcon = (state, importer, iconIdentity, entry) => {
693
+ const existing = state.iconOwners.get(iconIdentity);
694
+ if (existing !== undefined && existing.sourcePath !== entry.sourcePath) {
695
+ throw new Error(`${existing.sourcePath} and ${entry.sourcePath} both claim the themed icon ${iconIdentity}`);
696
+ }
697
+ const activeEntry = activateEntry(state, entry, importer);
698
+ state.iconOwners.set(iconIdentity, activeEntry);
699
+ claimIcon(state, iconIdentity, importer);
700
+ };
701
+ const activateDeclaredEntries = (state, importer) => {
702
+ const entries = state.declaredEntries.get(importer)?.values() ?? [];
703
+ for (const entry of entries) {
704
+ if (isDeclaredSourceAvailable(state, entry.sourcePath)) {
705
+ activateEntry(state, entry, importer);
706
+ }
707
+ }
708
+ };
709
+ const activateDeclaredIcons = (state, importer) => {
710
+ const icons = state.declaredIcons.get(importer) ?? [];
711
+ for (const [iconIdentity, entry] of icons) {
712
+ if (isDeclaredSourceAvailable(state, entry.sourcePath)) {
713
+ activateDeclaredIcon(state, importer, iconIdentity, entry);
714
+ }
715
+ }
716
+ };
717
+ const activateDeclaredClaims = (state, active) => {
718
+ for (const importer of sortStrings(active)) {
719
+ activateDeclaredEntries(state, importer);
720
+ activateDeclaredIcons(state, importer);
721
+ }
722
+ };
723
+ const rebuildActiveClaims = (state) => {
724
+ const previous = {
725
+ entries: state.entries,
726
+ entryImporters: state.entryImporters,
727
+ iconImporters: state.iconImporters,
728
+ iconOwners: state.iconOwners,
729
+ sourcePaths: state.sourcePaths,
730
+ };
731
+ state.entries = new Map();
732
+ state.entryImporters = new Map();
733
+ state.iconImporters = new Map();
734
+ state.iconOwners = new Map();
735
+ state.sourcePaths = new Set();
736
+ try {
737
+ activateDeclaredClaims(state, activeImporterKeys(state));
738
+ }
739
+ catch (error_) {
740
+ state.entries = previous.entries;
741
+ state.entryImporters = previous.entryImporters;
742
+ state.iconImporters = previous.iconImporters;
743
+ state.iconOwners = previous.iconOwners;
744
+ state.sourcePaths = previous.sourcePaths;
745
+ throw error_;
746
+ }
747
+ };
748
+ const forgetImporterDeclarations = (state, importer) => {
749
+ state.declaredEntries.delete(importer);
750
+ state.declaredIcons.delete(importer);
751
+ };
752
+ const cloneStringSetMap = (source) => {
753
+ const clone = new Map();
754
+ for (const [key, values] of source) {
755
+ clone.set(key, new Set(values));
756
+ }
757
+ return clone;
758
+ };
759
+ const cloneDeclarationMap = (source) => {
760
+ const clone = new Map();
761
+ for (const [key, declarations] of source) {
762
+ clone.set(key, new Map(declarations));
763
+ }
764
+ return clone;
765
+ };
766
+ const reconciliationCandidate = (state) => ({
767
+ ...state,
768
+ bundledSpecifiers: cloneStringSetMap(state.bundledSpecifiers),
769
+ moduleDependencies: cloneStringSetMap(state.moduleDependencies),
770
+ prunedDependencies: cloneStringSetMap(state.prunedDependencies),
771
+ declaredEntries: cloneDeclarationMap(state.declaredEntries),
772
+ declaredIcons: cloneDeclarationMap(state.declaredIcons),
773
+ missingSourcePaths: new Set(state.missingSourcePaths),
774
+ });
775
+ const storeBundledSpecifiers = (state, importer, specifiers) => {
776
+ if (specifiers.size === 0) {
777
+ state.bundledSpecifiers.delete(importer);
778
+ return;
779
+ }
780
+ state.bundledSpecifiers.set(importer, specifiers);
781
+ };
782
+ const applyImporterGraph = (state, reconciliation) => {
783
+ updatePrunedDependencies(state, reconciliation.key, reconciliation.previousDependencies, reconciliation.currentDependencies);
784
+ state.moduleDependencies.set(reconciliation.key, reconciliation.currentDependencies);
785
+ storeBundledSpecifiers(state, reconciliation.key, reconciliation.currentBundled);
786
+ };
787
+ const declareReconciledResource = async (ctx, state, importer, source) => {
788
+ const resourceSpecifier = parseResourceSpecifier(source);
789
+ if (resourceSpecifier === null) {
790
+ return;
791
+ }
792
+ const entry = await resolveAssetEntry(ctx, state, {
793
+ assetSource: resourceSpecifier.assetSource,
794
+ importer,
795
+ resourcePath: resourceSpecifier.resourcePath,
796
+ options: undefined,
797
+ });
798
+ if (entry === undefined || state.missingSourcePaths.has(entry.sourcePath)) {
799
+ throw new Error(`${JSON.stringify(source)} did not resolve to a bundled resource`);
800
+ }
801
+ };
802
+ const declareReconciledIcon = async (ctx, state, importer, source) => {
803
+ const iconSpecifier = parseIconSpecifier(source);
804
+ if (iconSpecifier === null) {
805
+ return;
806
+ }
807
+ const entry = await resolveIconEntry(ctx, state, {
808
+ assetSource: iconSpecifier.assetSource,
809
+ iconName: iconSpecifier.iconName,
810
+ importer,
811
+ options: undefined,
812
+ });
813
+ if (entry === undefined || state.missingSourcePaths.has(entry.entry.sourcePath)) {
814
+ throw new Error(`${JSON.stringify(source)} did not resolve to a bundled icon`);
815
+ }
816
+ };
817
+ const declareReconciledSource = async (ctx, state, importer, source) => {
818
+ await declareReconciledResource(ctx, state, importer, source);
819
+ await declareReconciledIcon(ctx, state, importer, source);
820
+ };
821
+ const declareReconciledImports = async (ctx, state, reconciliation) => {
822
+ for (const entry of reconciliation.imports) {
823
+ if (isBundledSource(entry.source)) {
824
+ await declareReconciledSource(ctx, state, reconciliation.file, entry.source);
825
+ }
826
+ }
827
+ };
828
+ const prepareReconciliation = async (ctx, state, reconciliation) => {
829
+ const candidate = reconciliationCandidate(state);
830
+ const isBundledChanged = !isSameSpecifiers(reconciliation.previousBundled, reconciliation.currentBundled);
831
+ if (isBundledChanged) {
832
+ forgetImporterDeclarations(candidate, reconciliation.key);
833
+ }
834
+ applyImporterGraph(candidate, reconciliation);
835
+ rebuildActiveClaims(candidate);
836
+ if (isBundledChanged) {
837
+ await declareReconciledImports(ctx, candidate, reconciliation);
838
+ }
839
+ return candidate;
840
+ };
841
+ const commitReconciliation = (state, candidate) => {
842
+ state.entries = candidate.entries;
843
+ state.entryImporters = candidate.entryImporters;
844
+ state.bundledSpecifiers = candidate.bundledSpecifiers;
845
+ state.moduleDependencies = candidate.moduleDependencies;
846
+ state.prunedDependencies = candidate.prunedDependencies;
847
+ state.declaredEntries = candidate.declaredEntries;
848
+ state.declaredIcons = candidate.declaredIcons;
849
+ state.missingSourcePaths = candidate.missingSourcePaths;
850
+ state.sourcePaths = candidate.sourcePaths;
851
+ state.iconOwners = candidate.iconOwners;
852
+ state.iconImporters = candidate.iconImporters;
853
+ };
854
+ const reconcileV2Importer = async (ctx, state, id) => {
855
+ const reconciliation = await importerReconciliation(ctx, state, id);
856
+ if (reconciliation === null) {
857
+ return;
858
+ }
859
+ const previousSignature = entriesSignature(state);
860
+ const candidate = await prepareReconciliation(ctx, state, reconciliation);
861
+ commitReconciliation(state, candidate);
862
+ if (entriesSignature(state) !== previousSignature) {
863
+ refreshDevRegistration(state);
864
+ }
865
+ };
157
866
  const resolveResourceConfig = async (state, config, loadConfig) => {
158
- const { applicationId } = await loadConfig.resolve(config.root ?? process.cwd());
159
- state.prefix = deriveResourcePrefix(applicationId);
867
+ const loaded = await loadConfig.load(config.root ?? process.cwd());
868
+ state.prefix = resourceBasePath(loaded.config.applicationId);
869
+ state.root = loaded.root;
870
+ state.isV2 = loaded.config.future?.v2ResourceImports === true;
160
871
  return {
161
872
  assetsInclude: [ASSET_RE],
162
873
  };
163
874
  };
164
- const refreshTrackedSource = async (state, file) => {
875
+ const refreshTrackedSource = (state, file) => {
165
876
  if (!isTrackedSource(state, file)) {
166
877
  return;
167
878
  }
168
879
  try {
169
- await refreshDevRegistration(state);
880
+ refreshDevRegistration(state);
170
881
  }
171
882
  catch (error_) {
172
883
  error("GResource refresh failed:", error_);
173
884
  }
174
885
  };
886
+ const rebuildForSourceAvailability = (state, previousSignature) => {
887
+ try {
888
+ rebuildActiveClaims(state);
889
+ if (entriesSignature(state) !== previousSignature) {
890
+ refreshDevRegistration(state);
891
+ }
892
+ }
893
+ catch (error_) {
894
+ error("GResource source update failed:", error_);
895
+ }
896
+ };
897
+ const updateTrackedSourceAvailability = (state, file, isAvailable) => {
898
+ if (!isTrackedSource(state, file) && !state.missingSourcePaths.has(file) && !isDeclaredSource(state, file)) {
899
+ return;
900
+ }
901
+ const previousSignature = entriesSignature(state);
902
+ setSourceAvailability(state, file, isAvailable);
903
+ rebuildForSourceAvailability(state, previousSignature);
904
+ };
175
905
  const attachResourceWatcher = (state, server) => {
176
906
  state.server = server;
177
- const onFileEvent = (file) => {
178
- void refreshTrackedSource(state, file);
907
+ const onChange = (file) => {
908
+ refreshTrackedSource(state, file);
909
+ };
910
+ const onAdd = (file) => {
911
+ updateTrackedSourceAvailability(state, file, true);
912
+ };
913
+ const onUnlink = (file) => {
914
+ updateTrackedSourceAvailability(state, file, false);
179
915
  };
180
916
  const onClose = () => {
181
917
  releaseStagingDir(state);
182
918
  };
183
919
  server.httpServer?.once("close", onClose);
184
920
  server.watcher.once("close", onClose);
185
- server.watcher.on("change", onFileEvent);
186
- server.watcher.on("add", onFileEvent);
921
+ server.watcher.on("change", onChange);
922
+ server.watcher.on("add", onAdd);
923
+ server.watcher.on("unlink", onUnlink);
187
924
  };
188
925
  const applyResolvedConfig = (state, config) => {
189
926
  state.isBuild = config.command === "build";
190
- if (state.isBuild) {
927
+ state.root = config.root;
928
+ state.dataDir = null;
929
+ if (state.isBuild || state.isV2) {
191
930
  return;
192
931
  }
193
932
  const relativeDataDir = resolveDataDir(config.root);
@@ -202,51 +941,148 @@ const loadResourceModule = (state, id) => {
202
941
  }
203
942
  return loadAssetModule(state, id);
204
943
  };
205
- function gtkxResources(loadConfig = createConfigLoader()) {
944
+ const isLegacyDataSpecifier = (source) => source.startsWith(DATA_PREFIX) && ASSET_RE.test(stripQuery(source));
945
+ const rejectInvalidV2Specifier = (source) => {
946
+ if (BUNDLED_QUERY_MENTION_RE.test(source)) {
947
+ throw new Error(`${JSON.stringify(source)} is not a valid bundled asset import; use ?resource, ` +
948
+ "?resource=/absolute/path, ?icon, or ?icon=name");
949
+ }
950
+ if (isBareRelativeAsset(source)) {
951
+ throw new Error(`${JSON.stringify(source)} must choose ?resource for a GResource, ?icon for a themed icon, ` +
952
+ "or ?url for an emitted file");
953
+ }
954
+ };
955
+ const resolveExplicitResourceId = async (ctx, state, request) => {
956
+ const specifier = parseResourceSpecifier(request.source);
957
+ if (specifier === null) {
958
+ return undefined;
959
+ }
960
+ const entry = await resolveAssetEntry(ctx, state, {
961
+ assetSource: specifier.assetSource,
962
+ importer: request.importer,
963
+ resourcePath: specifier.resourcePath,
964
+ options: request.options,
965
+ });
966
+ return entry === undefined ? undefined : virtualAssetId(entry);
967
+ };
968
+ const resolveIconResourceId = async (ctx, state, request) => {
969
+ const specifier = parseIconSpecifier(request.source);
970
+ if (specifier === null) {
971
+ return undefined;
972
+ }
973
+ const resolved = await resolveIconEntry(ctx, state, {
974
+ assetSource: specifier.assetSource,
975
+ iconName: specifier.iconName,
976
+ importer: request.importer,
977
+ options: request.options,
978
+ });
979
+ return resolved === undefined
980
+ ? undefined
981
+ : { id: virtualIconId(resolved), moduleSideEffects: true };
982
+ };
983
+ const resolveV2ResourceId = async (ctx, state, request) => {
984
+ if (isLegacyDataSpecifier(request.source)) {
985
+ throw new Error(`${JSON.stringify(request.source)} uses the legacy #data asset form; import it relatively with ` +
986
+ "?resource or ?url");
987
+ }
988
+ if (parseResourceSpecifier(request.source) !== null) {
989
+ const resolved = await resolveExplicitResourceId(ctx, state, request);
990
+ trackBundledSpecifier(state, request.importer, request.source);
991
+ return resolved;
992
+ }
993
+ if (parseIconSpecifier(request.source) !== null) {
994
+ const resolved = await resolveIconResourceId(ctx, state, request);
995
+ trackBundledSpecifier(state, request.importer, request.source);
996
+ return resolved;
997
+ }
998
+ rejectInvalidV2Specifier(request.source);
999
+ return undefined;
1000
+ };
1001
+ const resolveLegacyResourceId = async (ctx, state, request) => {
1002
+ if (BUNDLED_QUERY_MENTION_RE.test(request.source)) {
1003
+ throw new Error(`${JSON.stringify(request.source)} requires future.v2ResourceImports`);
1004
+ }
1005
+ if (!isDataAsset(request.source)) {
1006
+ return undefined;
1007
+ }
1008
+ const entry = await resolveLegacyAssetEntry(ctx, state, request);
1009
+ return entry === undefined ? undefined : virtualAssetId(entry);
1010
+ };
1011
+ const resolveResourceId = (ctx, state, request) => {
1012
+ if (request.source === VIRTUAL_INIT) {
1013
+ return Promise.resolve(VIRTUAL_INIT);
1014
+ }
1015
+ return state.isV2
1016
+ ? resolveV2ResourceId(ctx, state, request)
1017
+ : resolveLegacyResourceId(ctx, state, request);
1018
+ };
1019
+ const configureResourceServer = (state, server) => {
1020
+ attachResourceWatcher(state, server);
1021
+ primeLegacyDevBundle(state);
1022
+ };
1023
+ const createResourcesPlugin = (state, loadConfig) => ({
1024
+ name: "gtkx:resources",
1025
+ enforce: "pre",
1026
+ perEnvironmentStartEndDuringDev: true,
1027
+ config: (config) => resolveResourceConfig(state, config, loadConfig),
1028
+ configResolved: (config) => {
1029
+ applyResolvedConfig(state, config);
1030
+ },
1031
+ configureServer: (server) => {
1032
+ configureResourceServer(state, server);
1033
+ },
1034
+ buildStart() {
1035
+ if (state.isBuild && state.bundleReferenceId === null) {
1036
+ state.bundleReferenceId = this.emitFile({
1037
+ type: "asset",
1038
+ fileName: BUNDLE_FILENAME,
1039
+ source: "",
1040
+ });
1041
+ }
1042
+ },
1043
+ resolveId(source, importer, options) {
1044
+ return resolveResourceId(this, state, { source, importer, options });
1045
+ },
1046
+ load(id) {
1047
+ return loadResourceModule(state, id);
1048
+ },
1049
+ async transform(code, id) {
1050
+ await reconcileV2Importer(this, state, id);
1051
+ return retainSideEffectIconImport(state, code, id);
1052
+ },
1053
+ generateBundle(_options, bundle) {
1054
+ finalizeBuildBundle(this, bundle, state);
1055
+ },
1056
+ closeBundle() {
1057
+ releaseStagingDir(state);
1058
+ },
1059
+ });
1060
+ function gtkxResources(loadConfig = createConfigLoader(), entryPath) {
206
1061
  const state = {
207
1062
  prefix: "",
1063
+ root: "",
208
1064
  isBuild: false,
1065
+ isV2: false,
209
1066
  entries: new Map(),
1067
+ entryImporters: new Map(),
1068
+ bundledSpecifiers: new Map(),
1069
+ moduleDependencies: new Map(),
1070
+ prunedDependencies: new Map(),
1071
+ declaredEntries: new Map(),
1072
+ declaredIcons: new Map(),
1073
+ entryModule: entryPath === undefined ? null : importerKey(entryPath),
210
1074
  sourcePaths: new Set(),
1075
+ missingSourcePaths: new Set(),
211
1076
  stagingDir: createRetainedStagingDir(DEV_STAGING_PREFIX),
212
1077
  devBundlePath: "",
213
1078
  server: null,
214
1079
  compiledSignature: "",
215
1080
  dataDir: null,
1081
+ bundleReferenceId: null,
1082
+ iconOwners: new Map(),
1083
+ iconImporters: new Map(),
216
1084
  };
217
- return {
218
- name: "gtkx:resources",
219
- enforce: "pre",
220
- config(config) {
221
- return resolveResourceConfig(state, config, loadConfig);
222
- },
223
- configResolved(config) {
224
- applyResolvedConfig(state, config);
225
- },
226
- configureServer(server) {
227
- attachResourceWatcher(state, server);
228
- primeDevBundle(state);
229
- },
230
- async resolveId(source, importer, opts) {
231
- if (source === VIRTUAL_INIT) {
232
- return VIRTUAL_INIT;
233
- }
234
- if (!isDataAsset(source)) {
235
- return;
236
- }
237
- const resolved = await this.resolve(source, importer, { ...opts, skipSelf: true });
238
- return resolvedAssetId(resolved, source);
239
- },
240
- load(id) {
241
- return loadResourceModule(state, id);
242
- },
243
- buildEnd() {
244
- emitBuildBundle(this, state);
245
- },
246
- closeBundle() {
247
- releaseStagingDir(state);
248
- },
249
- };
1085
+ return createResourcesPlugin(state, loadConfig);
250
1086
  }
251
1087
  export { gtkxResources };
252
1088
  //# sourceMappingURL=resources.js.map