@lix-js/sdk 0.6.0-preview.1 → 0.6.0-preview.2

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 (191) hide show
  1. package/SKILL.md +305 -320
  2. package/dist/engine-wasm/wasm/lix_engine.d.ts +5 -0
  3. package/dist/engine-wasm/wasm/lix_engine.js +9 -13
  4. package/dist/engine-wasm/wasm/lix_engine.wasm +0 -0
  5. package/dist/engine-wasm/wasm/lix_engine.wasm.d.ts +1 -0
  6. package/dist/open-lix.d.ts +103 -14
  7. package/dist/open-lix.js +3 -0
  8. package/dist/sqlite/index.js +99 -22
  9. package/dist-engine-src/README.md +18 -0
  10. package/dist-engine-src/src/backend/kv.rs +358 -0
  11. package/dist-engine-src/src/backend/mod.rs +12 -0
  12. package/dist-engine-src/src/backend/testing.rs +658 -0
  13. package/dist-engine-src/src/backend/types.rs +96 -0
  14. package/dist-engine-src/src/binary_cas/chunking.rs +31 -0
  15. package/dist-engine-src/src/binary_cas/codec.rs +346 -0
  16. package/dist-engine-src/src/binary_cas/context.rs +139 -0
  17. package/dist-engine-src/src/binary_cas/kv.rs +1063 -0
  18. package/dist-engine-src/src/binary_cas/mod.rs +11 -0
  19. package/dist-engine-src/src/binary_cas/types.rs +127 -0
  20. package/dist-engine-src/src/cel/context.rs +86 -0
  21. package/dist-engine-src/src/cel/error.rs +19 -0
  22. package/dist-engine-src/src/cel/mod.rs +8 -0
  23. package/dist-engine-src/src/cel/provider.rs +9 -0
  24. package/dist-engine-src/src/cel/runtime.rs +167 -0
  25. package/dist-engine-src/src/cel/value.rs +50 -0
  26. package/dist-engine-src/src/changelog/codec.rs +321 -0
  27. package/dist-engine-src/src/changelog/context.rs +92 -0
  28. package/dist-engine-src/src/changelog/materialization.rs +121 -0
  29. package/dist-engine-src/src/changelog/mod.rs +13 -0
  30. package/dist-engine-src/src/changelog/reader.rs +20 -0
  31. package/dist-engine-src/src/changelog/storage.rs +220 -0
  32. package/dist-engine-src/src/changelog/types.rs +38 -0
  33. package/dist-engine-src/src/commit_graph/context.rs +1588 -0
  34. package/dist-engine-src/src/commit_graph/mod.rs +12 -0
  35. package/dist-engine-src/src/commit_graph/types.rs +145 -0
  36. package/dist-engine-src/src/commit_graph/walker.rs +780 -0
  37. package/dist-engine-src/src/common/error.rs +313 -0
  38. package/dist-engine-src/src/common/fingerprint.rs +3 -0
  39. package/dist-engine-src/src/common/fs_path.rs +1336 -0
  40. package/dist-engine-src/src/common/identity.rs +135 -0
  41. package/dist-engine-src/src/common/metadata.rs +35 -0
  42. package/dist-engine-src/src/common/mod.rs +23 -0
  43. package/dist-engine-src/src/common/types.rs +105 -0
  44. package/dist-engine-src/src/common/wire.rs +222 -0
  45. package/dist-engine-src/src/engine.rs +239 -0
  46. package/dist-engine-src/src/entity_identity.rs +285 -0
  47. package/dist-engine-src/src/functions/context.rs +327 -0
  48. package/dist-engine-src/src/functions/deterministic.rs +113 -0
  49. package/dist-engine-src/src/functions/mod.rs +18 -0
  50. package/dist-engine-src/src/functions/provider.rs +130 -0
  51. package/dist-engine-src/src/functions/state.rs +363 -0
  52. package/dist-engine-src/src/functions/types.rs +37 -0
  53. package/dist-engine-src/src/init.rs +505 -0
  54. package/dist-engine-src/src/json_store/compression.rs +77 -0
  55. package/dist-engine-src/src/json_store/context.rs +129 -0
  56. package/dist-engine-src/src/json_store/encoded.rs +15 -0
  57. package/dist-engine-src/src/json_store/mod.rs +9 -0
  58. package/dist-engine-src/src/json_store/store.rs +236 -0
  59. package/dist-engine-src/src/json_store/types.rs +52 -0
  60. package/dist-engine-src/src/lib.rs +61 -0
  61. package/dist-engine-src/src/live_state/context.rs +2241 -0
  62. package/dist-engine-src/src/live_state/mod.rs +15 -0
  63. package/dist-engine-src/src/live_state/overlay.rs +75 -0
  64. package/dist-engine-src/src/live_state/reader.rs +23 -0
  65. package/dist-engine-src/src/live_state/types.rs +239 -0
  66. package/dist-engine-src/src/live_state/visibility.rs +218 -0
  67. package/dist-engine-src/src/plugin/archive.rs +441 -0
  68. package/dist-engine-src/src/plugin/component.rs +183 -0
  69. package/dist-engine-src/src/plugin/install.rs +637 -0
  70. package/dist-engine-src/src/plugin/manifest.rs +516 -0
  71. package/dist-engine-src/src/plugin/materializer.rs +477 -0
  72. package/dist-engine-src/src/plugin/mod.rs +33 -0
  73. package/dist-engine-src/src/plugin/plugin_manifest.json +119 -0
  74. package/dist-engine-src/src/plugin/storage.rs +74 -0
  75. package/dist-engine-src/src/schema/annotations/defaults.rs +280 -0
  76. package/dist-engine-src/src/schema/annotations/mod.rs +1 -0
  77. package/dist-engine-src/src/schema/builtin/lix_account.json +22 -0
  78. package/dist-engine-src/src/schema/builtin/lix_active_account.json +30 -0
  79. package/dist-engine-src/src/schema/builtin/lix_binary_blob_ref.json +30 -0
  80. package/dist-engine-src/src/schema/builtin/lix_change.json +62 -0
  81. package/dist-engine-src/src/schema/builtin/lix_change_author.json +46 -0
  82. package/dist-engine-src/src/schema/builtin/lix_change_set.json +18 -0
  83. package/dist-engine-src/src/schema/builtin/lix_change_set_element.json +75 -0
  84. package/dist-engine-src/src/schema/builtin/lix_commit.json +62 -0
  85. package/dist-engine-src/src/schema/builtin/lix_commit_edge.json +46 -0
  86. package/dist-engine-src/src/schema/builtin/lix_directory_descriptor.json +53 -0
  87. package/dist-engine-src/src/schema/builtin/lix_entity_label.json +63 -0
  88. package/dist-engine-src/src/schema/builtin/lix_file_descriptor.json +53 -0
  89. package/dist-engine-src/src/schema/builtin/lix_key_value.json +41 -0
  90. package/dist-engine-src/src/schema/builtin/lix_label.json +22 -0
  91. package/dist-engine-src/src/schema/builtin/lix_registered_schema.json +31 -0
  92. package/dist-engine-src/src/schema/builtin/lix_version_descriptor.json +35 -0
  93. package/dist-engine-src/src/schema/builtin/lix_version_ref.json +49 -0
  94. package/dist-engine-src/src/schema/builtin/mod.rs +271 -0
  95. package/dist-engine-src/src/schema/definition.json +157 -0
  96. package/dist-engine-src/src/schema/definition.rs +636 -0
  97. package/dist-engine-src/src/schema/key.rs +206 -0
  98. package/dist-engine-src/src/schema/mod.rs +20 -0
  99. package/dist-engine-src/src/schema/seed.rs +14 -0
  100. package/dist-engine-src/src/schema/tests.rs +739 -0
  101. package/dist-engine-src/src/schema_registry.rs +294 -0
  102. package/dist-engine-src/src/session/context.rs +366 -0
  103. package/dist-engine-src/src/session/create_version.rs +80 -0
  104. package/dist-engine-src/src/session/execute.rs +447 -0
  105. package/dist-engine-src/src/session/merge/analysis.rs +102 -0
  106. package/dist-engine-src/src/session/merge/apply.rs +23 -0
  107. package/dist-engine-src/src/session/merge/conflicts.rs +62 -0
  108. package/dist-engine-src/src/session/merge/mod.rs +11 -0
  109. package/dist-engine-src/src/session/merge/stats.rs +65 -0
  110. package/dist-engine-src/src/session/merge/version.rs +437 -0
  111. package/dist-engine-src/src/session/mod.rs +25 -0
  112. package/dist-engine-src/src/session/switch_version.rs +121 -0
  113. package/dist-engine-src/src/sql2/change_provider.rs +337 -0
  114. package/dist-engine-src/src/sql2/classify.rs +147 -0
  115. package/dist-engine-src/src/sql2/commit_derived_provider.rs +591 -0
  116. package/dist-engine-src/src/sql2/context.rs +307 -0
  117. package/dist-engine-src/src/sql2/directory_history_provider.rs +623 -0
  118. package/dist-engine-src/src/sql2/directory_provider.rs +2405 -0
  119. package/dist-engine-src/src/sql2/dml.rs +148 -0
  120. package/dist-engine-src/src/sql2/entity_history_provider.rs +444 -0
  121. package/dist-engine-src/src/sql2/entity_provider.rs +2700 -0
  122. package/dist-engine-src/src/sql2/error.rs +196 -0
  123. package/dist-engine-src/src/sql2/execute.rs +3379 -0
  124. package/dist-engine-src/src/sql2/file_history_provider.rs +902 -0
  125. package/dist-engine-src/src/sql2/file_provider.rs +3254 -0
  126. package/dist-engine-src/src/sql2/filesystem_planner.rs +1526 -0
  127. package/dist-engine-src/src/sql2/filesystem_predicates.rs +159 -0
  128. package/dist-engine-src/src/sql2/filesystem_visibility.rs +369 -0
  129. package/dist-engine-src/src/sql2/history_projection.rs +80 -0
  130. package/dist-engine-src/src/sql2/history_provider.rs +418 -0
  131. package/dist-engine-src/src/sql2/history_route.rs +643 -0
  132. package/dist-engine-src/src/sql2/lix_state_provider.rs +2430 -0
  133. package/dist-engine-src/src/sql2/mod.rs +43 -0
  134. package/dist-engine-src/src/sql2/read_only.rs +65 -0
  135. package/dist-engine-src/src/sql2/record_batch.rs +17 -0
  136. package/dist-engine-src/src/sql2/result_metadata.rs +29 -0
  137. package/dist-engine-src/src/sql2/runtime.rs +60 -0
  138. package/dist-engine-src/src/sql2/session.rs +135 -0
  139. package/dist-engine-src/src/sql2/udfs/common.rs +295 -0
  140. package/dist-engine-src/src/sql2/udfs/lix_active_version_commit_id.rs +53 -0
  141. package/dist-engine-src/src/sql2/udfs/lix_empty_blob.rs +47 -0
  142. package/dist-engine-src/src/sql2/udfs/lix_json.rs +100 -0
  143. package/dist-engine-src/src/sql2/udfs/lix_json_get.rs +99 -0
  144. package/dist-engine-src/src/sql2/udfs/lix_json_get_text.rs +99 -0
  145. package/dist-engine-src/src/sql2/udfs/lix_text_decode.rs +82 -0
  146. package/dist-engine-src/src/sql2/udfs/lix_text_encode.rs +85 -0
  147. package/dist-engine-src/src/sql2/udfs/lix_uuid_v7.rs +76 -0
  148. package/dist-engine-src/src/sql2/udfs/mod.rs +82 -0
  149. package/dist-engine-src/src/sql2/version_provider.rs +1187 -0
  150. package/dist-engine-src/src/sql2/version_scope.rs +394 -0
  151. package/dist-engine-src/src/sql2/write_normalization.rs +345 -0
  152. package/dist-engine-src/src/storage/context.rs +356 -0
  153. package/dist-engine-src/src/storage/mod.rs +14 -0
  154. package/dist-engine-src/src/storage/read_scope.rs +88 -0
  155. package/dist-engine-src/src/storage/types.rs +501 -0
  156. package/dist-engine-src/src/storage_bench.rs +3406 -0
  157. package/dist-engine-src/src/test_support.rs +81 -0
  158. package/dist-engine-src/src/tracked_state/by_file_index.rs +102 -0
  159. package/dist-engine-src/src/tracked_state/codec.rs +747 -0
  160. package/dist-engine-src/src/tracked_state/context.rs +983 -0
  161. package/dist-engine-src/src/tracked_state/diff.rs +494 -0
  162. package/dist-engine-src/src/tracked_state/materialization.rs +141 -0
  163. package/dist-engine-src/src/tracked_state/merge.rs +474 -0
  164. package/dist-engine-src/src/tracked_state/mod.rs +31 -0
  165. package/dist-engine-src/src/tracked_state/rebuild.rs +771 -0
  166. package/dist-engine-src/src/tracked_state/storage.rs +243 -0
  167. package/dist-engine-src/src/tracked_state/tree.rs +2744 -0
  168. package/dist-engine-src/src/tracked_state/tree_types.rs +176 -0
  169. package/dist-engine-src/src/tracked_state/types.rs +61 -0
  170. package/dist-engine-src/src/transaction/commit.rs +1224 -0
  171. package/dist-engine-src/src/transaction/context.rs +1307 -0
  172. package/dist-engine-src/src/transaction/live_state_overlay.rs +34 -0
  173. package/dist-engine-src/src/transaction/mod.rs +11 -0
  174. package/dist-engine-src/src/transaction/normalization.rs +1026 -0
  175. package/dist-engine-src/src/transaction/schema_resolver.rs +127 -0
  176. package/dist-engine-src/src/transaction/staging.rs +1436 -0
  177. package/dist-engine-src/src/transaction/types.rs +351 -0
  178. package/dist-engine-src/src/transaction/validation.rs +4811 -0
  179. package/dist-engine-src/src/untracked_state/codec.rs +363 -0
  180. package/dist-engine-src/src/untracked_state/context.rs +82 -0
  181. package/dist-engine-src/src/untracked_state/materialization.rs +157 -0
  182. package/dist-engine-src/src/untracked_state/mod.rs +17 -0
  183. package/dist-engine-src/src/untracked_state/storage.rs +348 -0
  184. package/dist-engine-src/src/untracked_state/types.rs +96 -0
  185. package/dist-engine-src/src/version/context.rs +52 -0
  186. package/dist-engine-src/src/version/mod.rs +12 -0
  187. package/dist-engine-src/src/version/refs.rs +421 -0
  188. package/dist-engine-src/src/version/stage_rows.rs +71 -0
  189. package/dist-engine-src/src/version/types.rs +21 -0
  190. package/dist-engine-src/src/wasm/mod.rs +60 -0
  191. package/package.json +68 -64
@@ -0,0 +1,441 @@
1
+ use std::collections::{BTreeMap, BTreeSet};
2
+ use std::io::{Cursor, Read};
3
+ use std::path::{Component, Path};
4
+
5
+ use serde_json::Value as JsonValue;
6
+ use zip::read::ZipArchive;
7
+
8
+ use crate::schema::{schema_key_from_definition, validate_lix_schema_definition};
9
+ use crate::LixError;
10
+
11
+ use super::{parse_plugin_manifest_json, InstalledPlugin, PluginManifest};
12
+
13
+ #[derive(Debug, Clone)]
14
+ pub(crate) struct ParsedPluginArchive {
15
+ pub manifest: PluginManifest,
16
+ pub schemas: Vec<JsonValue>,
17
+ }
18
+
19
+ pub(crate) fn parse_plugin_archive_for_install(
20
+ archive_bytes: &[u8],
21
+ ) -> Result<ParsedPluginArchive, LixError> {
22
+ let files = read_archive_files_for_install(archive_bytes)?;
23
+
24
+ let manifest_bytes = files.get("manifest.json").ok_or_else(|| LixError {
25
+ code: "LIX_ERROR_UNKNOWN".to_string(),
26
+ message: "Plugin archive must contain manifest.json".to_string(),
27
+ hint: None,
28
+ details: None,
29
+ })?;
30
+ let manifest_raw = std::str::from_utf8(manifest_bytes).map_err(|error| LixError {
31
+ code: "LIX_ERROR_UNKNOWN".to_string(),
32
+ message: format!("Plugin archive manifest.json must be UTF-8: {error}"),
33
+ hint: None,
34
+ details: None,
35
+ })?;
36
+ let validated_manifest = parse_plugin_manifest_json(manifest_raw)?;
37
+
38
+ let entry_path = normalize_archive_path_for_install(&validated_manifest.manifest.entry)?;
39
+ let wasm_bytes = files
40
+ .get(&entry_path)
41
+ .ok_or_else(|| LixError {
42
+ code: "LIX_ERROR_UNKNOWN".to_string(),
43
+ message: format!(
44
+ "Plugin archive is missing manifest entry file '{}'",
45
+ validated_manifest.manifest.entry
46
+ ),
47
+ hint: None,
48
+ details: None,
49
+ })?
50
+ .clone();
51
+ ensure_valid_plugin_wasm_for_install(&wasm_bytes)?;
52
+
53
+ let mut schemas = Vec::with_capacity(validated_manifest.manifest.schemas.len());
54
+ let mut seen_schema_keys = BTreeSet::<(String, String)>::new();
55
+ for schema_path in &validated_manifest.manifest.schemas {
56
+ let normalized_schema_path = normalize_archive_path_for_install(schema_path)?;
57
+ let schema_bytes = files.get(&normalized_schema_path).ok_or_else(|| LixError {
58
+ code: "LIX_ERROR_UNKNOWN".to_string(),
59
+ message: format!("Plugin archive is missing schema file '{schema_path}'"),
60
+ hint: None,
61
+ details: None,
62
+ })?;
63
+ let schema_json: JsonValue =
64
+ serde_json::from_slice(schema_bytes).map_err(|error| LixError {
65
+ code: "LIX_ERROR_UNKNOWN".to_string(),
66
+ message: format!(
67
+ "Plugin archive schema '{schema_path}' is invalid JSON: {error}"
68
+ ),
69
+ hint: None,
70
+ details: None,
71
+ })?;
72
+ validate_lix_schema_definition(&schema_json)?;
73
+ let schema_key = schema_key_from_definition(&schema_json)?;
74
+ if !seen_schema_keys.insert((
75
+ schema_key.schema_key.clone(),
76
+ schema_key.schema_version.clone(),
77
+ )) {
78
+ return Err(LixError {
79
+ code: "LIX_ERROR_UNKNOWN".to_string(),
80
+ message: format!(
81
+ "Plugin archive declares duplicate schema '{}~{}'",
82
+ schema_key.schema_key, schema_key.schema_version
83
+ ),
84
+ hint: None,
85
+ details: None,
86
+ });
87
+ }
88
+ schemas.push(schema_json);
89
+ }
90
+
91
+ Ok(ParsedPluginArchive {
92
+ manifest: validated_manifest.manifest,
93
+ schemas,
94
+ })
95
+ }
96
+
97
+ pub(crate) fn load_installed_plugin_from_archive_bytes(
98
+ plugin_key: &str,
99
+ archive_path: &str,
100
+ archive_bytes: &[u8],
101
+ ) -> Result<InstalledPlugin, LixError> {
102
+ let files = read_plugin_archive_files(archive_path, archive_bytes)?;
103
+ let manifest_bytes = files.get("manifest.json").ok_or_else(|| LixError {
104
+ code: "LIX_ERROR_UNKNOWN".to_string(),
105
+ message: format!(
106
+ "plugin materialization: archive '{}' is missing manifest.json",
107
+ archive_path
108
+ ),
109
+ hint: None,
110
+ details: None,
111
+ })?;
112
+ let manifest_raw = std::str::from_utf8(manifest_bytes).map_err(|error| LixError {
113
+ code: "LIX_ERROR_UNKNOWN".to_string(),
114
+ message: format!(
115
+ "plugin materialization: archive '{}' manifest.json must be UTF-8: {error}",
116
+ archive_path
117
+ ),
118
+ hint: None,
119
+ details: None,
120
+ })?;
121
+ let validated_manifest = parse_plugin_manifest_json(manifest_raw)?;
122
+ if validated_manifest.manifest.key != plugin_key {
123
+ return Err(LixError {
124
+ code: "LIX_ERROR_UNKNOWN".to_string(),
125
+ message: format!(
126
+ "plugin materialization: archive '{}' key mismatch: path key '{}' vs manifest key '{}'",
127
+ archive_path, plugin_key, validated_manifest.manifest.key
128
+ ),
129
+ hint: None,
130
+ details: None,
131
+ });
132
+ }
133
+
134
+ let entry_path =
135
+ normalize_plugin_archive_path_for_materialization(&validated_manifest.manifest.entry)?;
136
+ let wasm = files.get(&entry_path).ok_or_else(|| LixError {
137
+ code: "LIX_ERROR_UNKNOWN".to_string(),
138
+ message: format!(
139
+ "plugin materialization: archive '{}' is missing entry file '{}'",
140
+ archive_path, validated_manifest.manifest.entry
141
+ ),
142
+ hint: None,
143
+ details: None,
144
+ })?;
145
+ ensure_valid_plugin_wasm_for_materialization(wasm)?;
146
+
147
+ let manifest = validated_manifest.manifest;
148
+ let content_type = manifest.file_match.content_type;
149
+
150
+ Ok(InstalledPlugin {
151
+ key: manifest.key,
152
+ runtime: manifest.runtime,
153
+ api_version: manifest.api_version,
154
+ path_glob: manifest.file_match.path_glob,
155
+ content_type,
156
+ entry: manifest.entry,
157
+ manifest_json: validated_manifest.normalized_json,
158
+ wasm: wasm.clone(),
159
+ })
160
+ }
161
+
162
+ fn read_archive_files_for_install(
163
+ archive_bytes: &[u8],
164
+ ) -> Result<BTreeMap<String, Vec<u8>>, LixError> {
165
+ if archive_bytes.is_empty() {
166
+ return Err(LixError {
167
+ code: "LIX_ERROR_UNKNOWN".to_string(),
168
+ message: "Plugin archive bytes must not be empty".to_string(),
169
+ hint: None,
170
+ details: None,
171
+ });
172
+ }
173
+
174
+ let mut archive = ZipArchive::new(Cursor::new(archive_bytes)).map_err(|error| LixError {
175
+ code: "LIX_ERROR_UNKNOWN".to_string(),
176
+ message: format!("Plugin archive is not a valid zip file: {error}"),
177
+ hint: None,
178
+ details: None,
179
+ })?;
180
+ let mut files = BTreeMap::<String, Vec<u8>>::new();
181
+
182
+ for index in 0..archive.len() {
183
+ let mut entry = archive.by_index(index).map_err(|error| LixError {
184
+ code: "LIX_ERROR_UNKNOWN".to_string(),
185
+ message: format!("Failed to read plugin archive entry at index {index}: {error}"),
186
+ hint: None,
187
+ details: None,
188
+ })?;
189
+ let raw_name = entry.name().to_string();
190
+
191
+ if entry.is_dir() {
192
+ continue;
193
+ }
194
+ if is_symlink_mode(entry.unix_mode()) {
195
+ return Err(LixError {
196
+ code: "LIX_ERROR_UNKNOWN".to_string(),
197
+ message: format!("Plugin archive entry '{raw_name}' must not be a symlink"),
198
+ hint: None,
199
+ details: None,
200
+ });
201
+ }
202
+
203
+ let normalized_path = normalize_archive_path_for_install(&raw_name)?;
204
+ let mut bytes = Vec::new();
205
+ entry.read_to_end(&mut bytes).map_err(|error| LixError {
206
+ code: "LIX_ERROR_UNKNOWN".to_string(),
207
+ message: format!("Failed to read plugin archive entry '{raw_name}': {error}"),
208
+ hint: None,
209
+ details: None,
210
+ })?;
211
+ if files.insert(normalized_path.clone(), bytes).is_some() {
212
+ return Err(LixError {
213
+ code: "LIX_ERROR_UNKNOWN".to_string(),
214
+ message: format!("Plugin archive contains duplicate entry '{normalized_path}'"),
215
+ hint: None,
216
+ details: None,
217
+ });
218
+ }
219
+ }
220
+
221
+ Ok(files)
222
+ }
223
+
224
+ fn read_plugin_archive_files(
225
+ archive_path: &str,
226
+ archive_bytes: &[u8],
227
+ ) -> Result<BTreeMap<String, Vec<u8>>, LixError> {
228
+ if archive_bytes.is_empty() {
229
+ return Err(LixError {
230
+ code: "LIX_ERROR_UNKNOWN".to_string(),
231
+ message: format!(
232
+ "plugin materialization: archive '{}' is empty",
233
+ archive_path
234
+ ),
235
+ hint: None,
236
+ details: None,
237
+ });
238
+ }
239
+
240
+ let mut archive = ZipArchive::new(Cursor::new(archive_bytes)).map_err(|error| LixError {
241
+ code: "LIX_ERROR_UNKNOWN".to_string(),
242
+ message: format!(
243
+ "plugin materialization: archive '{}' is not a valid zip file: {error}",
244
+ archive_path
245
+ ),
246
+ hint: None,
247
+ details: None,
248
+ })?;
249
+ let mut files = BTreeMap::<String, Vec<u8>>::new();
250
+
251
+ for index in 0..archive.len() {
252
+ let mut entry = archive.by_index(index).map_err(|error| LixError {
253
+ code: "LIX_ERROR_UNKNOWN".to_string(),
254
+ message: format!(
255
+ "plugin materialization: failed to read archive '{}' entry index {}: {error}",
256
+ archive_path, index
257
+ ),
258
+ hint: None,
259
+ details: None,
260
+ })?;
261
+
262
+ let entry_name = entry.name().to_string();
263
+ let normalized_path = normalize_plugin_archive_path_for_materialization(&entry_name)?;
264
+ if normalized_path.ends_with('/') {
265
+ continue;
266
+ }
267
+
268
+ let mut bytes = Vec::new();
269
+ entry.read_to_end(&mut bytes).map_err(|error| LixError {
270
+ code: "LIX_ERROR_UNKNOWN".to_string(),
271
+ message: format!(
272
+ "plugin materialization: failed to read archive '{}' entry '{}': {error}",
273
+ archive_path, entry_name
274
+ ),
275
+ hint: None,
276
+ details: None,
277
+ })?;
278
+ files.insert(normalized_path, bytes);
279
+ }
280
+
281
+ Ok(files)
282
+ }
283
+
284
+ fn normalize_archive_path_for_install(path: &str) -> Result<String, LixError> {
285
+ if path.is_empty() {
286
+ return Err(LixError {
287
+ code: "LIX_ERROR_UNKNOWN".to_string(),
288
+ message: "Plugin archive path must not be empty".to_string(),
289
+ hint: None,
290
+ details: None,
291
+ });
292
+ }
293
+ if path.starts_with('/') || path.starts_with('\\') {
294
+ return Err(LixError {
295
+ code: "LIX_ERROR_UNKNOWN".to_string(),
296
+ message: format!("Plugin archive path '{path}' must be relative"),
297
+ hint: None,
298
+ details: None,
299
+ });
300
+ }
301
+ if path.contains('\\') {
302
+ return Err(LixError {
303
+ code: "LIX_ERROR_UNKNOWN".to_string(),
304
+ message: format!("Plugin archive path '{path}' must use forward slash separators"),
305
+ hint: None,
306
+ details: None,
307
+ });
308
+ }
309
+
310
+ let mut segments = Vec::<String>::new();
311
+ for component in Path::new(path).components() {
312
+ match component {
313
+ Component::Normal(value) => {
314
+ let segment = value.to_str().ok_or_else(|| LixError {
315
+ code: "LIX_ERROR_UNKNOWN".to_string(),
316
+ message: format!(
317
+ "Plugin archive path '{path}' contains non-UTF-8 components"
318
+ ),
319
+ hint: None,
320
+ details: None,
321
+ })?;
322
+ if segment.is_empty() {
323
+ return Err(LixError {
324
+ code: "LIX_ERROR_UNKNOWN".to_string(),
325
+ message: format!("Plugin archive path '{path}' is invalid"),
326
+ hint: None,
327
+ details: None,
328
+ });
329
+ }
330
+ segments.push(segment.to_string());
331
+ }
332
+ Component::CurDir | Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
333
+ return Err(LixError {
334
+ code: "LIX_ERROR_UNKNOWN".to_string(),
335
+ message: format!(
336
+ "Plugin archive path '{path}' must not contain traversal or absolute components"
337
+ ),
338
+ hint: None,
339
+ details: None,
340
+ })
341
+ }
342
+ }
343
+ }
344
+
345
+ if segments.is_empty() {
346
+ return Err(LixError {
347
+ code: "LIX_ERROR_UNKNOWN".to_string(),
348
+ message: format!("Plugin archive path '{path}' is invalid"),
349
+ hint: None,
350
+ details: None,
351
+ });
352
+ }
353
+
354
+ Ok(segments.join("/"))
355
+ }
356
+
357
+ fn normalize_plugin_archive_path_for_materialization(path: &str) -> Result<String, LixError> {
358
+ let raw_path = Path::new(path);
359
+ if raw_path.is_absolute() {
360
+ return Err(LixError {
361
+ code: "LIX_ERROR_UNKNOWN".to_string(),
362
+ message: format!(
363
+ "plugin materialization: archive path '{}' must be relative",
364
+ path
365
+ ),
366
+ hint: None,
367
+ details: None,
368
+ });
369
+ }
370
+
371
+ let mut normalized = Vec::new();
372
+ for component in raw_path.components() {
373
+ match component {
374
+ Component::Normal(part) => normalized.push(part.to_string_lossy().to_string()),
375
+ Component::CurDir => {}
376
+ Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
377
+ return Err(LixError {
378
+ code: "LIX_ERROR_UNKNOWN".to_string(),
379
+ message: format!(
380
+ "plugin materialization: archive path '{}' must not escape the archive root",
381
+ path
382
+ ),
383
+ hint: None,
384
+ details: None,
385
+ });
386
+ }
387
+ }
388
+ }
389
+
390
+ if normalized.is_empty() {
391
+ return Err(LixError {
392
+ code: "LIX_ERROR_UNKNOWN".to_string(),
393
+ message: "plugin materialization: archive path must not be empty".to_string(),
394
+ hint: None,
395
+ details: None,
396
+ });
397
+ }
398
+
399
+ Ok(normalized.join("/"))
400
+ }
401
+
402
+ fn ensure_valid_plugin_wasm_for_install(wasm_bytes: &[u8]) -> Result<(), LixError> {
403
+ if wasm_bytes.is_empty() {
404
+ return Err(LixError {
405
+ code: "LIX_ERROR_UNKNOWN".to_string(),
406
+ message: "Plugin wasm bytes must not be empty".to_string(),
407
+ hint: None,
408
+ details: None,
409
+ });
410
+ }
411
+ if wasm_bytes.len() < 8 || !wasm_bytes.starts_with(&[0x00, 0x61, 0x73, 0x6d]) {
412
+ return Err(LixError {
413
+ code: "LIX_ERROR_UNKNOWN".to_string(),
414
+ message: "Plugin wasm bytes must start with a valid wasm header".to_string(),
415
+ hint: None,
416
+ details: None,
417
+ });
418
+ }
419
+ Ok(())
420
+ }
421
+
422
+ fn ensure_valid_plugin_wasm_for_materialization(bytes: &[u8]) -> Result<(), LixError> {
423
+ const WASM_MAGIC: &[u8; 4] = b"\0asm";
424
+ if bytes.len() < WASM_MAGIC.len() || &bytes[..WASM_MAGIC.len()] != WASM_MAGIC {
425
+ return Err(LixError {
426
+ code: "LIX_ERROR_UNKNOWN".to_string(),
427
+ message: "plugin materialization: entry file must be a valid WebAssembly module"
428
+ .to_string(),
429
+ hint: None,
430
+ details: None,
431
+ });
432
+ }
433
+
434
+ Ok(())
435
+ }
436
+
437
+ fn is_symlink_mode(mode: Option<u32>) -> bool {
438
+ const MODE_FILE_TYPE_MASK: u32 = 0o170000;
439
+ const MODE_SYMLINK: u32 = 0o120000;
440
+ mode.is_some_and(|value| (value & MODE_FILE_TYPE_MASK) == MODE_SYMLINK)
441
+ }
@@ -0,0 +1,183 @@
1
+ use std::sync::Arc;
2
+
3
+ use crate::common::LixError;
4
+ use crate::wasm::{WasmComponentInstance, WasmLimits, WasmRuntime};
5
+
6
+ use super::InstalledPlugin;
7
+
8
+ #[derive(Clone)]
9
+ pub(crate) struct CachedPluginComponent {
10
+ pub(crate) wasm: Vec<u8>,
11
+ pub(crate) instance: Arc<dyn WasmComponentInstance>,
12
+ }
13
+
14
+ const APPLY_CHANGES_EXPORTS: &[&str] = &["apply-changes", "api#apply-changes"];
15
+
16
+ pub(crate) trait PluginComponentHost {
17
+ fn plugin_component_cache(
18
+ &self,
19
+ ) -> &std::sync::Mutex<std::collections::BTreeMap<String, CachedPluginComponent>>;
20
+
21
+ fn wasm_runtime(&self) -> &Arc<dyn WasmRuntime>;
22
+ }
23
+
24
+ pub(crate) async fn load_or_init_plugin_component(
25
+ host: &impl PluginComponentHost,
26
+ plugin: &InstalledPlugin,
27
+ ) -> Result<Arc<dyn WasmComponentInstance>, LixError> {
28
+ {
29
+ let guard = host.plugin_component_cache().lock().map_err(|_| LixError {
30
+ code: "LIX_ERROR_UNKNOWN".to_string(),
31
+ message: "plugin component cache lock poisoned".to_string(),
32
+ hint: None,
33
+ details: None,
34
+ })?;
35
+ if let Some(cached) = guard.get(&plugin.key) {
36
+ if cached.wasm == plugin.wasm {
37
+ return Ok(cached.instance.clone());
38
+ }
39
+ }
40
+ }
41
+
42
+ let initialized = host
43
+ .wasm_runtime()
44
+ .init_component(plugin.wasm.clone(), WasmLimits::default())
45
+ .await?;
46
+ let mut guard = host.plugin_component_cache().lock().map_err(|_| LixError {
47
+ code: "LIX_ERROR_UNKNOWN".to_string(),
48
+ message: "plugin component cache lock poisoned".to_string(),
49
+ hint: None,
50
+ details: None,
51
+ })?;
52
+ if let Some(cached) = guard.get(&plugin.key) {
53
+ if cached.wasm == plugin.wasm {
54
+ return Ok(cached.instance.clone());
55
+ }
56
+ }
57
+ guard.insert(
58
+ plugin.key.clone(),
59
+ CachedPluginComponent {
60
+ wasm: plugin.wasm.clone(),
61
+ instance: initialized.clone(),
62
+ },
63
+ );
64
+ Ok(initialized)
65
+ }
66
+
67
+ pub(crate) async fn apply_changes_with_plugin(
68
+ host: &impl PluginComponentHost,
69
+ plugin: &InstalledPlugin,
70
+ payload: &[u8],
71
+ ) -> Result<Vec<u8>, LixError> {
72
+ let instance = load_or_init_plugin_component(host, plugin).await?;
73
+ invoke_apply_changes_export(instance.as_ref(), payload).await
74
+ }
75
+
76
+ async fn invoke_apply_changes_export(
77
+ instance: &dyn WasmComponentInstance,
78
+ payload: &[u8],
79
+ ) -> Result<Vec<u8>, LixError> {
80
+ let mut errors = Vec::new();
81
+ for export in APPLY_CHANGES_EXPORTS {
82
+ match instance.call(export, payload).await {
83
+ Ok(output) => return Ok(output),
84
+ Err(error) => errors.push(format!("{export}: {}", error.message)),
85
+ }
86
+ }
87
+
88
+ Err(LixError {
89
+ code: "LIX_ERROR_UNKNOWN".to_string(),
90
+ message: format!(
91
+ "plugin materialization: failed to call apply-changes export ({})",
92
+ errors.join("; ")
93
+ ),
94
+ hint: None,
95
+ details: None,
96
+ })
97
+ }
98
+
99
+ #[cfg(test)]
100
+ mod tests {
101
+ use super::*;
102
+ use crate::plugin::{InstalledPlugin, PluginRuntime};
103
+ use crate::wasm::WasmRuntime;
104
+ use async_trait::async_trait;
105
+ use std::sync::atomic::{AtomicUsize, Ordering};
106
+
107
+ struct TestHost {
108
+ wasm_runtime: Arc<dyn WasmRuntime>,
109
+ plugin_component_cache:
110
+ std::sync::Mutex<std::collections::BTreeMap<String, CachedPluginComponent>>,
111
+ }
112
+
113
+ impl PluginComponentHost for TestHost {
114
+ fn plugin_component_cache(
115
+ &self,
116
+ ) -> &std::sync::Mutex<std::collections::BTreeMap<String, CachedPluginComponent>> {
117
+ &self.plugin_component_cache
118
+ }
119
+
120
+ fn wasm_runtime(&self) -> &Arc<dyn WasmRuntime> {
121
+ &self.wasm_runtime
122
+ }
123
+ }
124
+
125
+ #[derive(Default)]
126
+ struct CountingRuntime {
127
+ init_calls: Arc<AtomicUsize>,
128
+ }
129
+
130
+ struct NoopComponent;
131
+
132
+ #[async_trait(?Send)]
133
+ impl WasmRuntime for CountingRuntime {
134
+ async fn init_component(
135
+ &self,
136
+ _bytes: Vec<u8>,
137
+ _limits: WasmLimits,
138
+ ) -> Result<Arc<dyn WasmComponentInstance>, LixError> {
139
+ self.init_calls.fetch_add(1, Ordering::SeqCst);
140
+ Ok(Arc::new(NoopComponent))
141
+ }
142
+ }
143
+
144
+ #[async_trait(?Send)]
145
+ impl WasmComponentInstance for NoopComponent {
146
+ async fn call(&self, _export: &str, _input: &[u8]) -> Result<Vec<u8>, LixError> {
147
+ Ok(Vec::new())
148
+ }
149
+ }
150
+
151
+ #[tokio::test]
152
+ async fn component_cache_reinitializes_when_same_key_wasm_changes() {
153
+ let runtime = Arc::new(CountingRuntime::default());
154
+ let host = TestHost {
155
+ wasm_runtime: runtime.clone(),
156
+ plugin_component_cache: std::sync::Mutex::new(Default::default()),
157
+ };
158
+ let mut plugin = InstalledPlugin {
159
+ key: "k".to_string(),
160
+ runtime: PluginRuntime::WasmComponentV1,
161
+ api_version: "0.1.0".to_string(),
162
+ path_glob: "*.json".to_string(),
163
+ content_type: None,
164
+ entry: "plugin.wasm".to_string(),
165
+ manifest_json: "{}".to_string(),
166
+ wasm: vec![1],
167
+ };
168
+
169
+ load_or_init_plugin_component(&host, &plugin)
170
+ .await
171
+ .expect("first init should succeed");
172
+ load_or_init_plugin_component(&host, &plugin)
173
+ .await
174
+ .expect("second lookup should reuse cache");
175
+ assert_eq!(runtime.init_calls.load(Ordering::SeqCst), 1);
176
+
177
+ plugin.wasm = vec![2];
178
+ load_or_init_plugin_component(&host, &plugin)
179
+ .await
180
+ .expect("changed wasm should reinitialize instance");
181
+ assert_eq!(runtime.init_calls.load(Ordering::SeqCst), 2);
182
+ }
183
+ }