1use super::*;
6use crate::emitter::emit::test_scaffold_ns as test_ns;
8use crate::testgen::TEST_SESSION_KEY;
9use bynk_check::test_suites::{self, ResolvedStub};
10use bynk_ts::{TsBindingName, TsDecl, TsExpr, TsLit, TsObjectEntry, TsParam, TsStmt, TsType};
11
12fn double_args(derived: Option<&bynk_check::symbols::DerivedInstance>) -> Vec<TsExpr> {
18 if let Some((limit, period)) = derived.and_then(|d| d.rate_limit()) {
19 return vec![num_lit(limit.to_string()), num_lit(period.to_string())];
20 }
21 match derived.filter(|d| d.is_vectorize()) {
22 Some(d) => vec![
23 num_lit(d.vectorize_dimensions().unwrap_or_default().to_string()),
24 str_lit(d.vectorize_metric().unwrap_or_default()),
25 TsExpr::Array {
26 items: d.vectorize_indexed().iter().map(str_lit).collect(),
27 multiline: false,
28 },
29 ],
30 None => Vec::new(),
31 }
32}
33
34fn events_emit_loop() -> TsStmt {
36 use crate::ts_build::{await_expr, expr_stmt, for_of, ident, member, method_call};
37 for_of(
38 "ev",
39 ident("events"),
40 expr_stmt(await_expr(method_call(
41 member(ident("this"), "Events"),
42 "emit",
43 vec![member(ident("ev"), "payload")],
44 ))),
45 )
46}
47
48#[allow(clippy::too_many_arguments)]
64pub(super) fn emit_test_deps(
65 target_name: &str,
66 target_kind: UnitKind,
67 stubs: &HashMap<String, ResolvedStub>,
68 unit_tables: &HashMap<String, UnitTable>,
69 unit_consumes: &HashMap<String, Vec<String>>,
70 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
71 unit_flattened: &HashMap<String, HashMap<String, String>>,
72 bindings: Option<&HashMap<String, String>>,
76 name: &str,
78 uses_emit: bool,
81) -> TestDeps {
82 let mut units: BTreeSet<String> = BTreeSet::new();
83 let mut doubles: Vec<(String, String, String)> = Vec::new();
84 let given_doubles: std::cell::RefCell<Vec<(String, String, String)>> =
87 std::cell::RefCell::new(Vec::new());
88 let given_double = |owner: &str, cap: &str| -> Option<TsExpr> {
89 bindings?;
90 platform_double(owner, cap, &test_ns(owner), cap, false, None)?;
91 given_doubles
92 .borrow_mut()
93 .push((owner.to_string(), cap.to_string(), cap.to_string()));
94 Some(call(ident(test_cap_factory(cap)), Vec::new()))
95 };
96 let mut tops: Vec<(String, (String, String), TopDep)> = Vec::new();
99 let mut surface_entries: Vec<(String, TsExpr)> = Vec::new();
100 let mut service_doubles: Vec<(String, String, TsExpr)> = Vec::new();
102 if matches!(target_kind, UnitKind::Context | UnitKind::Adapter)
105 && let Some(table) = unit_tables.get(target_name)
106 {
107 let mut caps: Vec<&String> = table.capabilities.keys().collect();
110 caps.sort();
111 for cap in caps {
112 let how = if table.providers.contains_key(cap) {
116 TopDep::Provider
117 } else if let Some(inst) = table.derived.get(cap) {
118 platform_or_placeholder(&inst.base_unit, &inst.base_cap)
121 } else {
122 TopDep::Placeholder
123 };
124 tops.push((cap.clone(), (target_name.to_string(), cap.clone()), how));
125 }
126 let flattened = unit_flattened.get(target_name).cloned().unwrap_or_default();
135 let mut flat: Vec<(&String, &String)> = flattened.iter().collect();
136 flat.sort_by_key(|(cap, _)| cap.as_str());
137 for (cap, owner) in flat {
138 let how = if bindings.is_some_and(|b| b.contains_key(owner)) {
141 TopDep::Provider
142 } else {
143 platform_or_placeholder(owner, cap)
144 };
145 tops.push((cap.clone(), (owner.clone(), cap.clone()), how));
146 }
147 let consumed_all: Vec<String> = unit_consumes.get(target_name).cloned().unwrap_or_default();
153 let aliases = unit_consumes_aliases
154 .get(target_name)
155 .cloned()
156 .unwrap_or_default();
157 for (cap, owner) in
158 handler_cross_caps(table, target_name, &consumed_all, &aliases, &flattened)
159 {
160 if tops.iter().any(|(k, _, _)| *k == cap) {
161 continue;
162 }
163 let how = match platform_or_placeholder(&owner, &cap) {
164 TopDep::Placeholder | TopDep::Provider => TopDep::Provider,
165 TopDep::Double => TopDep::Double,
166 };
167 tops.push((cap.clone(), (owner, cap), how));
168 }
169 let mut alias_for_target: HashMap<String, String> = HashMap::new();
177 for (alias, q) in &aliases {
178 alias_for_target.insert(q.clone(), alias.clone());
179 }
180 for q in consumed_all.iter().filter(|q| {
181 unit_tables
182 .get(*q)
183 .is_some_and(|t| t.kind != Some(UnitKind::Adapter) && !t.services.is_empty())
184 }) {
185 let key = alias_for_target
186 .get(q)
187 .cloned()
188 .unwrap_or_else(|| q.rsplit('.').next().unwrap_or(q.as_str()).to_string());
189 let other_ns = test_ns(q);
190 let surface_ty = format!("globalThis.ReturnType<typeof {other_ns}.__makeSurface>");
191 if let Some(local) =
196 stub_service_double(stubs, q, &key, &surface_ty, &mut service_doubles)
197 {
198 surface_entries.push((key, ident(local)));
199 continue;
200 }
201 surface_entries.push((key, undefined_as_unknown_as(surface_ty)));
202 }
203 }
204
205 let prebuilt: HashMap<(String, String), String> = tops
211 .iter()
212 .map(|(key, id, _)| (id.clone(), format!("__dep_{key}")))
213 .collect();
214 let mut built: Vec<BuiltDep> = Vec::new();
215 for (key, (unit, cap), how) in &tops {
216 let used = std::cell::RefCell::new(BTreeSet::new());
217 let ty = format!("{}.{cap}", test_ns(unit));
218 let base = match how {
219 TopDep::Provider => Some(instantiate_provider_ts_expr(
220 unit,
221 cap,
222 unit_tables,
223 unit_consumes,
224 unit_consumes_aliases,
225 unit_flattened,
226 ProviderNamespaces::Test {
227 prebuilt: &prebuilt,
228 used: &used,
229 bindings,
230 double: &given_double,
231 },
232 None,
233 None,
234 &mut units,
235 )),
236 TopDep::Double => {
237 let derived = unit_tables.get(unit).and_then(|t| t.derived.get(cap));
239 let (owner, base) = derived.map_or((unit, cap), |d| (&d.base_unit, &d.base_cap));
240 doubles.push((owner.clone(), base.clone(), cap.clone()));
241 let args = double_args(derived);
242 Some(call(ident(test_cap_factory(cap)), args))
243 }
244 TopDep::Placeholder => None,
245 };
246 let value = match stubs.get(key) {
247 Some(rp) => stub_overlay(rp, &ty, base),
248 None => base.unwrap_or_else(|| undefined_as_unknown_as(ty)),
249 };
250 let id = (unit.clone(), cap.clone());
251 built.push(BuiltDep {
252 key: key.clone(),
253 local: prebuilt[&id].clone(),
254 id,
255 value,
256 used: used.into_inner(),
257 });
258 }
259 let shared: BTreeSet<(String, String)> =
260 built.iter().flat_map(|b| b.used.iter().cloned()).collect();
261 let mut body: Vec<TsStmt> = Vec::new();
262 let mut declared: BTreeSet<(String, String)> = BTreeSet::new();
263 fn declare(
266 id: &(String, String),
267 built: &[BuiltDep],
268 declared: &mut BTreeSet<(String, String)>,
269 body: &mut Vec<TsStmt>,
270 ) {
271 if declared.contains(id) {
272 return;
273 }
274 let Some(dep) = built.iter().find(|b| b.id == *id) else {
275 return;
276 };
277 for used in &dep.used {
278 declare(used, built, declared, body);
279 }
280 declared.insert(id.clone());
281 body.push(TsStmt::const_stmt(
282 TsBindingName::Ident(dep.local.clone()),
283 None,
284 dep.value.clone(),
285 None,
286 ));
287 }
288 for dep in &built {
289 if shared.contains(&dep.id) {
290 declare(&dep.id, &built, &mut declared, &mut body);
291 }
292 }
293 body.extend(service_double_consts(&service_doubles));
294 let mut entries: Vec<(String, TsExpr)> = built
295 .into_iter()
296 .map(|dep| {
297 let value = if shared.contains(&dep.id) {
298 ident(dep.local)
299 } else {
300 dep.value
301 };
302 (dep.key, value)
303 })
304 .collect();
305 entries.extend(service_double_entries(&service_doubles));
306 if !surface_entries.is_empty() {
307 entries.push(("surface".to_string(), TsExpr::object(surface_entries)));
308 }
309 let virtual_time = module_is_virtual_time(target_name, target_kind, stubs, unit_tables);
312 if target_hands_off_to_exec(target_name, target_kind, unit_tables) {
313 let exec = call(ident("__bynkExec"), Vec::new());
314 entries.push((
315 "__exec".to_string(),
316 if virtual_time {
317 call(
318 ident("globalThis.Object.assign"),
319 vec![
320 exec,
321 TsExpr::object(vec![("timers".to_string(), ident("__bynkTimers"))]),
322 ],
323 )
324 } else {
325 exec
326 },
327 ));
328 }
329 entries.extend(session_keys_entry(target_name, target_kind, unit_tables));
330 let mut entries: Vec<TsObjectEntry> = entries
331 .into_iter()
332 .map(|(k, v)| TsObjectEntry::prop(k, v))
333 .collect();
334 if uses_emit {
342 entries.push(
343 TsObjectEntry::method(
344 "__eventsDispatch",
345 true,
346 vec![TsParam::new(
347 "events".to_string(),
348 Some(TsType::named_with_args(
349 "globalThis.Array",
350 vec![TsType::named(crate::emitter::EVENTS_WIRE_EVENT_TS_TYPE)],
351 )),
352 )],
353 None,
354 vec![events_emit_loop()],
355 )
356 .inlined(),
357 );
358 }
359 let case_scoped = stubs.values().any(stub_is_scoped);
360 let suite_scoped = stubs.values().any(stub_is_suite_scoped);
361 let return_value = TsExpr::object_entries(entries);
364 if virtual_time {
365 body.push(TsStmt::const_stmt(
369 TsBindingName::Ident("__deps".to_string()),
370 None,
371 return_value,
372 None,
373 ));
374 body.push(TsStmt::expr_stmt(
375 call(ident("__bynkTrackDeps"), vec![ident("__deps")]),
376 None,
377 ));
378 body.push(TsStmt::return_stmt(Some(ident("__deps")), None));
379 } else {
380 body.push(TsStmt::return_stmt(Some(return_value), None));
381 }
382 doubles.extend(given_doubles.into_inner());
383 let stmt = TsStmt::decl(
384 TsDecl::Function {
385 name: name.to_string(),
386 generics: Vec::new(),
387 params: [
390 ("__case", "string", case_scoped),
391 ("__suite", "number", suite_scoped),
392 ]
393 .into_iter()
394 .filter(|(_, _, on)| *on)
395 .map(|(name, ty, _)| TsParam::optional(name.to_string(), Some(TsType::named(ty))))
396 .collect(),
397 return_type: None,
398 body,
399 is_async: false,
400 inline: false,
401 },
402 None,
403 );
404 TestDeps {
405 stmt,
406 units,
407 doubles,
408 }
409}
410
411fn stub_service_double(
416 stubs: &HashMap<String, ResolvedStub>,
417 ctx: &str,
418 key: &str,
419 surface_ty: &str,
420 doubles: &mut Vec<(String, String, TsExpr)>,
421) -> Option<String> {
422 let rp = stubs
423 .values()
424 .find(|rp| rp.service_context.as_deref() == Some(ctx))?;
425 let local = format!("__svc_{key}");
426 let value = stub_overlay(rp, surface_ty, Some(undefined_as_unknown_as(surface_ty)));
427 doubles.push((key.to_string(), local.clone(), value));
428 Some(local)
429}
430
431fn service_double_consts(doubles: &[(String, String, TsExpr)]) -> Vec<TsStmt> {
433 doubles
434 .iter()
435 .map(|(_, local, value)| {
436 TsStmt::const_stmt(
437 TsBindingName::Ident(local.clone()),
438 None,
439 value.clone(),
440 None,
441 )
442 })
443 .collect()
444}
445
446fn service_double_entries(doubles: &[(String, String, TsExpr)]) -> Vec<(String, TsExpr)> {
449 doubles
450 .iter()
451 .map(|(key, local, _)| (key.clone(), ident(local.clone())))
452 .collect()
453}
454
455pub(super) struct TestDeps {
457 pub(super) stmt: TsStmt,
459 pub(super) units: BTreeSet<String>,
461 pub(super) doubles: Vec<(String, String, String)>,
465}
466
467pub(super) struct BuiltDep {
469 pub(super) key: String,
471 pub(super) id: (String, String),
473 pub(super) local: String,
475 pub(super) value: TsExpr,
477 pub(super) used: BTreeSet<(String, String)>,
479}
480
481pub(super) enum TopDep {
483 Provider,
485 Double,
487 Placeholder,
489}
490
491pub(super) fn platform_or_placeholder(owner: &str, cap: &str) -> TopDep {
494 if platform_double(owner, cap, &test_ns(owner), cap, false, None).is_some() {
495 TopDep::Double
496 } else {
497 TopDep::Placeholder
498 }
499}
500
501pub(super) fn emit_ns_destructure(
523 ns: &str,
524 value_names: &[String],
525 type_names: &[(String, Vec<String>)],
526) -> Vec<TsStmt> {
527 emit_ns_destructure_renamed(
528 ns,
529 value_names,
530 type_names,
531 &HashMap::new(),
532 &HashSet::new(),
533 )
534}
535
536pub(super) fn emit_ns_destructure_renamed(
542 ns: &str,
543 value_names: &[String],
544 type_names: &[(String, Vec<String>)],
545 renames: &HashMap<String, String>,
546 declared: &HashSet<String>,
547) -> Vec<TsStmt> {
548 let mut stmts = Vec::new();
549 if !value_names.is_empty() {
550 let pattern = value_names
551 .iter()
552 .flat_map(|n| match renames.get(n) {
553 Some(alias) => {
554 let entry = format!("{n}: {alias}");
555 if declared.contains(n) {
556 vec![entry, n.clone()]
557 } else {
558 vec![entry]
559 }
560 }
561 None => vec![n.clone()],
562 })
563 .collect();
564 stmts.push(TsStmt::const_stmt(
565 TsBindingName::ObjectPattern(pattern),
566 None,
567 ident(ns),
568 None,
569 ));
570 }
571 for (t, params) in type_names {
572 let target = format!("{ns}.{t}");
573 let ty = if params.is_empty() {
574 TsType::named(target)
575 } else {
576 TsType::named_with_args(target, params.iter().map(TsType::named).collect())
577 };
578 let mut names = vec![renames.get(t).unwrap_or(t).clone()];
579 if declared.contains(t) {
580 names.push(t.clone());
581 }
582 for name in names {
583 stmts.push(TsStmt::decl(
584 TsDecl::TypeAlias {
585 name,
586 type_params: params.clone(),
587 ty: ty.clone(),
588 },
589 None,
590 ));
591 }
592 }
593 stmts
594}
595
596pub(super) fn public_types(table: &UnitTable) -> impl Iterator<Item = &String> {
598 table
599 .types
600 .iter()
601 .filter(|(_, d)| d.private.is_none())
602 .map(|(n, _)| n)
603}
604
605pub(super) fn public_fns(table: &UnitTable) -> impl Iterator<Item = &String> {
607 table
608 .fns
609 .iter()
610 .filter(|(_, d)| d.private.is_none())
611 .map(|(n, _)| n)
612}
613
614pub(super) fn is_public_type(table: &UnitTable, name: &str) -> bool {
616 table.types.get(name).is_some_and(|d| d.private.is_none())
617}
618
619pub(super) fn aliased_types(
622 table: &UnitTable,
623 keep: impl Fn(&String) -> bool,
624) -> Vec<(String, Vec<String>)> {
625 let mut types: Vec<(String, Vec<String>)> = table
626 .types
627 .iter()
628 .filter(|(name, _)| keep(name))
629 .map(|(name, decl)| {
630 let params = decl
631 .type_params
632 .iter()
633 .map(|p| p.name.name.clone())
634 .collect();
635 (name.clone(), params)
636 })
637 .collect();
638 types.sort();
639 types
640}
641
642pub(super) fn target_names<'a>(
645 target_name: &str,
646 unit_tables: &'a HashMap<String, UnitTable>,
647) -> (HashSet<&'a String>, HashSet<&'a String>) {
648 let target_local: HashSet<&String> = unit_tables
659 .get(target_name)
660 .map(|t| {
661 t.types
662 .keys()
663 .chain(t.fns.keys())
664 .chain(t.assets.keys())
665 .chain(t.embeds.keys())
666 .chain(t.consts.keys())
667 .collect()
668 })
669 .unwrap_or_default();
670 let target_values: HashSet<&String> = unit_tables
679 .get(target_name)
680 .map(|t| {
681 target_local
682 .iter()
683 .copied()
684 .chain(t.services.keys())
685 .chain(t.agents.keys())
686 .chain(
687 t.providers
688 .values()
689 .filter(|p| !p.external)
690 .map(|p| &p.provider_name.name),
691 )
692 .collect()
693 })
694 .unwrap_or_default();
695 (target_local, target_values)
696}
697
698pub(super) type NsDestructure = (String, Vec<String>, Vec<(String, Vec<String>)>);
701
702pub(super) fn used_commons_destructures<'a>(
712 target_name: &str,
713 unit_tables: &'a HashMap<String, UnitTable>,
714 unit_uses: &HashMap<String, Vec<String>>,
715 seen_assets: &mut HashSet<&'a String>,
716) -> Vec<NsDestructure> {
717 let (target_local, target_values) = target_names(target_name, unit_tables);
718 let mut out = Vec::new();
719 if let Some(used) = unit_uses.get(target_name) {
720 for u in used {
721 let ns = test_ns(u);
722 if let Some(table) = unit_tables.get(u) {
723 let assets = table
727 .assets
728 .iter()
729 .filter(|(_, d)| d.private.is_none())
730 .map(|(n, _)| n)
731 .filter(|n| seen_assets.insert(*n));
732 let embeds = table
733 .embeds
734 .iter()
735 .filter(|(_, d)| d.private.is_none())
736 .map(|(n, _)| n);
737 let consts = table
738 .consts
739 .iter()
740 .filter(|(_, d)| d.private.is_none())
741 .map(|(n, _)| n);
742 let mut names: Vec<String> = public_types(table)
743 .chain(public_fns(table))
744 .chain(assets)
745 .chain(embeds)
746 .chain(consts)
747 .filter(|n| !target_values.contains(n))
748 .cloned()
749 .collect();
750 names.sort();
751 names.dedup();
752 let type_names = aliased_types(table, |n| {
753 !target_local.contains(n) && is_public_type(table, n)
754 });
755 out.push((ns, names, type_names));
756 }
757 }
758 }
759 out
760}
761
762pub(super) fn hidden_by_owner(hidden: &BTreeMap<String, String>) -> BTreeMap<String, Vec<String>> {
765 let mut by_owner: BTreeMap<String, Vec<String>> = BTreeMap::new();
766 for (name, owner) in hidden {
767 by_owner
768 .entry(owner.clone())
769 .or_default()
770 .push(name.clone());
771 }
772 by_owner
773}
774
775pub(super) fn hidden_destructures(
781 hidden: &BTreeMap<String, Vec<String>>,
782 unit_tables: &HashMap<String, UnitTable>,
783) -> Vec<TsStmt> {
784 let mut stmts = Vec::new();
785 for (owner, names) in hidden {
786 let Some(table) = unit_tables.get(owner) else {
787 continue;
788 };
789 let type_names = aliased_types(table, |n| names.contains(n));
790 stmts.extend(emit_ns_destructure(&test_ns(owner), names, &type_names));
791 }
792 stmts
793}
794
795pub(super) fn sanitise_case_name(name: &str, index: &mut usize) -> String {
796 let mut s = String::from("test_");
797 for ch in name.chars() {
798 if ch.is_ascii_alphanumeric() {
799 s.push(ch);
800 } else {
801 s.push('_');
802 }
803 }
804 if s == "test_" {
805 s.push_str(&index.to_string());
806 }
807 *index += 1;
808 s
809}
810
811pub struct TestAssetFiles<'a> {
815 pub served: &'a BTreeMap<String, String>,
816 pub bytes: &'a BTreeMap<String, Vec<u8>>,
817 pub fixtures: &'a BTreeMap<String, String>,
819}
820
821pub(super) fn env_entries(
825 env: &BTreeMap<String, bynk_check::test_env::EnvValue>,
826) -> Vec<(String, TsExpr)> {
827 env.iter()
828 .map(|(k, v)| {
829 let value = match v {
830 bynk_check::test_env::EnvValue::Literal(s) => str_lit(s.clone()),
831 bynk_check::test_env::EnvValue::Fixture(path) => ident(fixture_ident(path)),
832 };
833 (k.clone(), value)
834 })
835 .collect()
836}
837
838pub(super) fn fixture_ident(path: &str) -> String {
842 let key = bynk_project::assets::normalise_asset_path(path);
843 let mut out = String::from("__fixture_");
844 for b in key.bytes() {
845 if b.is_ascii_alphanumeric() {
846 out.push(b as char);
847 } else {
848 out.push_str(&format!("_{b:02x}"));
849 }
850 }
851 out
852}
853
854pub(super) fn fixture_consts(
860 indices: &[usize],
861 parsed: &[ParsedFile],
862 files: &TestAssetFiles,
863) -> Option<Vec<TsStmt>> {
864 let mut paths: BTreeSet<String> = BTreeSet::new();
865 for &i in indices {
866 if let bynk_syntax::ast::SourceUnit::Suite(s) = parsed[i].unit() {
867 for f in &s.fixtures {
868 paths.insert(bynk_project::assets::normalise_asset_path(&f.path));
869 }
870 }
871 }
872 let mut stmts: Vec<TsStmt> = paths
873 .iter()
874 .filter_map(|p| {
875 let text = files.fixtures.get(p)?;
876 Some(TsStmt::const_stmt(
877 TsBindingName::Ident(fixture_ident(p)),
878 Some(TsType::named("string")),
879 TsExpr::Lit(TsLit::Str(text.clone())),
880 None,
881 ))
882 })
883 .collect();
884 if stmts.is_empty() {
885 return None;
886 }
887 for stmt in stmts.iter_mut().skip(1) {
889 stmt.no_blank_before = true;
890 }
891 Some(stmts)
892}
893
894pub(super) const ASSET_FILES_NAME: &str = "__bynkAssetFiles";
897pub(super) const ASSET_FILES_TYPE: &str =
898 "Record<string, { readonly body: string; readonly contentType: string }>";
899
900pub(super) fn asset_harness(
910 target: &str,
911 unit_uses: &HashMap<String, Vec<String>>,
912 unit_consumes: &HashMap<String, Vec<String>>,
913 unit_tables: &HashMap<String, UnitTable>,
914 files: &TestAssetFiles,
915) -> Option<Vec<TsStmt>> {
916 let deployed = bynk_check::assets::deployed_assets(
917 target,
918 unit_uses,
919 unit_consumes,
920 unit_tables,
921 files.served,
922 );
923 if deployed.is_empty() {
924 return None;
925 }
926 let entries: Vec<TsObjectEntry> = deployed
927 .iter()
928 .map(|(served, source)| {
929 let bytes = files.bytes.get(source).unwrap_or_else(|| {
933 panic!(
934 "bynk internal error: deployed asset `{source}` has no bytes for the test harness"
935 )
936 });
937 TsObjectEntry::prop(
938 bynk_project::json_string(served),
939 TsExpr::object(vec![
940 ("body".to_string(), crate::ts_build::str_lit(base64(bytes))),
941 (
942 "contentType".to_string(),
943 crate::ts_build::raw_lit(bynk_project::json_string(
944 bynk_check::assets::content_type_for(served),
945 )),
946 ),
947 ]),
948 )
949 })
950 .collect();
951 let table = TsStmt::const_stmt(
952 TsBindingName::Ident(ASSET_FILES_NAME.to_string()),
953 Some(TsType::named(ASSET_FILES_TYPE)),
954 TsExpr::multiline_object_entries(entries),
955 None,
956 );
957 let mut getter = TestRuntimeModule::AssetGet.splice();
959 getter.no_blank_before = true;
960 Some(vec![table, getter])
961}
962
963pub(super) fn system_asset_owners(
968 view: &test_suites::SuiteView,
969 participants: &[String],
970 unit_tables: &HashMap<String, UnitTable>,
971) -> BTreeMap<String, Vec<String>> {
972 let mut owners: BTreeMap<String, Vec<String>> = BTreeMap::new();
973 for (name, decl) in &view.assets {
974 let owner = unit_tables
975 .iter()
976 .filter(|(_, t)| {
977 t.assets
978 .get(name)
979 .is_some_and(|d| d.path == decl.path && d.at == decl.at)
980 })
981 .map(|(u, _)| u)
982 .min_by_key(|u| (!participants.contains(u), (*u).clone()));
983 if let Some(owner) = owner {
984 owners.entry(owner.clone()).or_default().push(name.clone());
985 }
986 }
987 for names in owners.values_mut() {
988 names.sort();
989 }
990 owners
991}
992
993pub(super) fn base64(bytes: &[u8]) -> String {
996 const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
997 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
998 for chunk in bytes.chunks(3) {
999 let b = [
1000 chunk[0],
1001 *chunk.get(1).unwrap_or(&0),
1002 *chunk.get(2).unwrap_or(&0),
1003 ];
1004 let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
1005 for (i, shift) in [18u32, 12, 6, 0].into_iter().enumerate() {
1006 if i <= chunk.len() {
1007 out.push(ALPHABET[((n >> shift) & 63) as usize] as char);
1008 } else {
1009 out.push('=');
1010 }
1011 }
1012 }
1013 out
1014}
1015
1016fn session_keys_entry(
1020 target_name: &str,
1021 target_kind: UnitKind,
1022 unit_tables: &HashMap<String, UnitTable>,
1023) -> Option<(String, TsExpr)> {
1024 if target_kind != UnitKind::Context {
1025 return None;
1026 }
1027 let mut actors: Vec<String> = unit_tables
1028 .get(target_name)?
1029 .actors
1030 .values()
1031 .filter_map(|a| bynk_check::actors::signed_cookie_seam_of(a, None))
1032 .map(|s| s.actor)
1033 .collect();
1034 if actors.is_empty() {
1035 return None;
1036 }
1037 actors.sort();
1038 let keys = actors
1039 .into_iter()
1040 .map(|a| {
1041 (
1042 a,
1043 TsExpr::object(vec![("secret".to_string(), str_lit(TEST_SESSION_KEY))]),
1044 )
1045 })
1046 .collect();
1047 Some(("__session".to_string(), TsExpr::object(keys)))
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052 use super::*;
1053
1054 #[test]
1055 fn sanitise_case_name_prefixes_and_advances_index() {
1056 let mut idx = 0;
1057 assert_eq!(
1058 sanitise_case_name("hello world", &mut idx),
1059 "test_hello_world"
1060 );
1061 assert_eq!(idx, 1); assert_eq!(sanitise_case_name("a-b.c", &mut idx), "test_a_b_c");
1063 assert_eq!(idx, 2);
1064 }
1065
1066 #[test]
1067 fn sanitise_case_name_appends_index_only_for_empty_name() {
1068 let mut idx = 5;
1069 assert_eq!(sanitise_case_name("", &mut idx), "test_5"); assert_eq!(idx, 6);
1071 let mut idx2 = 9;
1073 assert_eq!(sanitise_case_name(" ", &mut idx2), "test__");
1074 assert_eq!(idx2, 10);
1075 }
1076
1077 }