@foxglove/schemas 1.7.0 → 1.7.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 (40) hide show
  1. package/dist/internal/generatePyclass.d.ts +3 -3
  2. package/dist/internal/generatePyclass.d.ts.map +1 -1
  3. package/dist/internal/generatePyclass.js +119 -32
  4. package/dist/internal/generatePyclass.js.map +1 -1
  5. package/dist/internal/generatePyclass.test.js +147 -140
  6. package/dist/internal/generatePyclass.test.js.map +1 -1
  7. package/dist/internal/generateSdkCpp.d.ts +4 -0
  8. package/dist/internal/generateSdkCpp.d.ts.map +1 -0
  9. package/dist/internal/generateSdkCpp.js +359 -0
  10. package/dist/internal/generateSdkCpp.js.map +1 -0
  11. package/dist/internal/generateSdkRustCTypes.d.ts +3 -0
  12. package/dist/internal/generateSdkRustCTypes.d.ts.map +1 -0
  13. package/dist/internal/generateSdkRustCTypes.js +253 -0
  14. package/dist/internal/generateSdkRustCTypes.js.map +1 -0
  15. package/dist/internal/schemas.d.ts.map +1 -1
  16. package/dist/internal/schemas.js +28 -24
  17. package/dist/internal/schemas.js.map +1 -1
  18. package/dist/jsonschema/index.d.ts +9 -12
  19. package/dist/jsonschema/index.d.ts.map +1 -1
  20. package/dist/jsonschema/index.js +80 -41
  21. package/dist/jsonschema/index.js.map +1 -1
  22. package/dist/types/CameraCalibration.d.ts +1 -1
  23. package/dist/types/CompressedImage.d.ts +1 -1
  24. package/dist/types/LogLevel.d.ts +6 -0
  25. package/dist/types/LogLevel.d.ts.map +1 -1
  26. package/dist/types/LogLevel.js +6 -0
  27. package/dist/types/LogLevel.js.map +1 -1
  28. package/dist/types/NumericType.d.ts +9 -0
  29. package/dist/types/NumericType.d.ts.map +1 -1
  30. package/dist/types/NumericType.js +9 -0
  31. package/dist/types/NumericType.js.map +1 -1
  32. package/dist/types/PointsAnnotationType.d.ts +1 -0
  33. package/dist/types/PointsAnnotationType.d.ts.map +1 -1
  34. package/dist/types/PointsAnnotationType.js +1 -0
  35. package/dist/types/PointsAnnotationType.js.map +1 -1
  36. package/dist/types/PositionCovarianceType.d.ts +4 -0
  37. package/dist/types/PositionCovarianceType.d.ts.map +1 -1
  38. package/dist/types/PositionCovarianceType.js +4 -0
  39. package/dist/types/PositionCovarianceType.js.map +1 -1
  40. package/package.json +2 -2
@@ -0,0 +1,359 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateHppSchemas = generateHppSchemas;
4
+ exports.generateCppSchemas = generateCppSchemas;
5
+ const tslib_1 = require("tslib");
6
+ const assert_1 = tslib_1.__importDefault(require("assert"));
7
+ function primitiveToCpp(type) {
8
+ switch (type) {
9
+ case "uint32":
10
+ return "uint32_t";
11
+ case "bytes":
12
+ return "std::vector<std::byte>";
13
+ case "string":
14
+ return "std::string";
15
+ case "boolean":
16
+ return "bool";
17
+ case "float64":
18
+ return "double";
19
+ case "time":
20
+ return "std::optional<foxglove::Timestamp>";
21
+ case "duration":
22
+ return "std::optional<foxglove::Duration>";
23
+ }
24
+ }
25
+ function primitiveDefaultValue(type) {
26
+ switch (type) {
27
+ case "uint32":
28
+ return 0;
29
+ case "boolean":
30
+ return false;
31
+ case "float64":
32
+ return 0;
33
+ case "string":
34
+ case "bytes":
35
+ case "time":
36
+ case "duration":
37
+ return undefined;
38
+ }
39
+ }
40
+ function formatComment(comment, indent) {
41
+ const spaces = " ".repeat(indent);
42
+ return comment
43
+ .split("\n")
44
+ .map((line) => `${spaces}/// @brief ${line}`)
45
+ .join("\n");
46
+ }
47
+ function toCamelCase(name) {
48
+ return name.substring(0, 1).toLowerCase() + name.substring(1);
49
+ }
50
+ function toSnakeCase(name) {
51
+ const snakeName = name
52
+ .replace("JSON", "Json")
53
+ .replace(/([A-Z])/g, "_$1")
54
+ .toLowerCase();
55
+ return snakeName.startsWith("_") ? snakeName.substring(1) : snakeName;
56
+ }
57
+ function isSameAsCType(schema) {
58
+ return schema.fields.every((field) => field.type.type === "primitive" &&
59
+ field.type.name !== "bytes" &&
60
+ field.type.name !== "string");
61
+ }
62
+ /**
63
+ * Yield `schemas` in an order such that dependencies come before dependents, so structs don't end
64
+ * up referencing [incomplete types](https://en.cppreference.com/w/cpp/language/incomplete_type).
65
+ */
66
+ function* topologicalOrder(schemas, seenSchemaNames = new Set()) {
67
+ for (const schema of schemas) {
68
+ if (seenSchemaNames.has(schema.name)) {
69
+ continue;
70
+ }
71
+ seenSchemaNames.add(schema.name);
72
+ for (const field of schema.fields) {
73
+ if (field.type.type === "nested") {
74
+ yield* topologicalOrder([field.type.schema], seenSchemaNames);
75
+ }
76
+ }
77
+ yield schema;
78
+ }
79
+ }
80
+ function generateHppSchemas(schemas, enums) {
81
+ const enumsByParentSchema = new Map();
82
+ for (const enumSchema of enums) {
83
+ if (enumsByParentSchema.has(enumSchema.parentSchemaName)) {
84
+ throw new Error(`Multiple enums with the same parent schema not currently supported ${enumSchema.parentSchemaName}`);
85
+ }
86
+ enumsByParentSchema.set(enumSchema.parentSchemaName, enumSchema);
87
+ }
88
+ const orderedSchemas = Array.from(topologicalOrder(schemas));
89
+ if (orderedSchemas.length !== schemas.length) {
90
+ throw new Error(`Invariant: topologicalOrder should return same number of schemas (got ${orderedSchemas.length} instead of ${schemas.length})`);
91
+ }
92
+ const structDefs = orderedSchemas.map((schema) => {
93
+ let enumDef = [];
94
+ const enumSchema = enumsByParentSchema.get(schema.name);
95
+ if (enumSchema) {
96
+ enumDef = [
97
+ formatComment(enumSchema.description, 2),
98
+ ` enum class ${enumSchema.name} : uint8_t {`,
99
+ enumSchema.values
100
+ .map((value) => {
101
+ const comment = value.description != undefined ? formatComment(value.description, 4) + "\n" : "";
102
+ return `${comment} ${value.name.toUpperCase()} = ${value.value},`;
103
+ })
104
+ .join("\n"),
105
+ ` };`,
106
+ ];
107
+ }
108
+ return [
109
+ formatComment(schema.description, 0),
110
+ `struct ${schema.name} {`,
111
+ ...enumDef,
112
+ schema.fields
113
+ .map((field) => {
114
+ let fieldType;
115
+ let defaultStr = "";
116
+ switch (field.type.type) {
117
+ case "enum":
118
+ fieldType = field.type.enum.name;
119
+ break;
120
+ case "nested":
121
+ fieldType = field.type.schema.name;
122
+ break;
123
+ case "primitive": {
124
+ const defaultValue = field.array != undefined ? undefined : primitiveDefaultValue(field.type.name);
125
+ defaultStr = defaultValue != undefined ? ` = ${defaultValue.toString()}` : "";
126
+ fieldType = primitiveToCpp(field.type.name);
127
+ break;
128
+ }
129
+ }
130
+ if (typeof field.array === "number") {
131
+ fieldType = `std::array<${fieldType}, ${field.array}>`;
132
+ }
133
+ else if (field.array) {
134
+ fieldType = `std::vector<${fieldType}>`;
135
+ }
136
+ else if (field.type.type === "nested") {
137
+ fieldType = `std::optional<${fieldType}>`;
138
+ }
139
+ return `${formatComment(field.description, 2)}\n ${fieldType} ${toSnakeCase(field.name)}${defaultStr};`;
140
+ })
141
+ .join("\n\n"),
142
+ `};`,
143
+ ].join("\n");
144
+ });
145
+ const channelClasses = schemas.map((schema) => `/// @brief A channel for logging ${schema.name} messages to a topic.
146
+ ///
147
+ /// @note While channels are fully thread-safe, the ${schema.name} struct is not thread-safe.
148
+ /// Avoid modifying it concurrently or during a log operation.
149
+ class ${schema.name}Channel {
150
+ public:
151
+ /// @brief Create a new channel.
152
+ ///
153
+ /// @param topic The topic name. You should choose a unique topic name per channel for
154
+ /// compatibility with the Foxglove app.
155
+ /// @param context The context which associates logs to a sink. If omitted, the default context is
156
+ /// used.
157
+ static FoxgloveResult<${schema.name}Channel> create(const std::string_view& topic, const Context& context = Context());
158
+
159
+ /// @brief Log a message to the channel.
160
+ ///
161
+ /// @param msg The ${schema.name} message to log.
162
+ /// @param log_time The timestamp of the message. If omitted, the current time is used.
163
+ FoxgloveError log(const ${schema.name}& msg, std::optional<uint64_t> log_time = std::nullopt) noexcept;
164
+
165
+ /// @brief Uniquely identifies a channel in the context of this program.
166
+ ///
167
+ /// @return The ID of the channel.
168
+ [[nodiscard]] uint64_t id() const noexcept;
169
+
170
+ ${schema.name}Channel(const ${schema.name}Channel& other) noexcept = delete;
171
+ ${schema.name}Channel& operator=(const ${schema.name}Channel& other) noexcept = delete;
172
+ /// @brief Default move constructor.
173
+ ${schema.name}Channel(${schema.name}Channel&& other) noexcept = default;
174
+ /// @brief Default move assignment.
175
+ ${schema.name}Channel& operator=(${schema.name}Channel&& other) noexcept = default;
176
+ /// @brief Default destructor.
177
+ ~${schema.name}Channel() = default;
178
+
179
+ private:
180
+ explicit ${schema.name}Channel(ChannelUniquePtr&& channel)
181
+ : impl_(std::move(channel)) {}
182
+
183
+ ChannelUniquePtr impl_;
184
+ };`);
185
+ const includes = [
186
+ "#include <array>",
187
+ "#include <cstdint>",
188
+ "#include <string>",
189
+ "#include <type_traits>",
190
+ "#include <vector>",
191
+ "#include <optional>",
192
+ "#include <memory>",
193
+ "",
194
+ "#include <foxglove/time.hpp>",
195
+ "#include <foxglove/error.hpp>",
196
+ "#include <foxglove/context.hpp>",
197
+ ];
198
+ const uniquePtr = [
199
+ "/// @brief A functor for freeing a channel. Used by ChannelUniquePtr. For internal use only.",
200
+ "struct ChannelDeleter {",
201
+ " /// @brief free the channel",
202
+ " void operator()(const foxglove_channel* ptr) const noexcept;",
203
+ "};",
204
+ "/// @brief A unique pointer to a C foxglove_channel pointer. For internal use only.",
205
+ "typedef std::unique_ptr<const foxglove_channel, ChannelDeleter> ChannelUniquePtr;",
206
+ ];
207
+ const outputSections = [
208
+ "// Generated by https://github.com/foxglove/foxglove-sdk",
209
+ "#pragma once",
210
+ includes.join("\n"),
211
+ "struct foxglove_channel;",
212
+ "namespace foxglove::schemas {",
213
+ uniquePtr.join("\n"),
214
+ structDefs.join("\n\n"),
215
+ channelClasses.join("\n\n"),
216
+ "} // namespace foxglove::schemas",
217
+ ].filter(Boolean);
218
+ return outputSections.join("\n\n") + "\n";
219
+ }
220
+ function cppToC(schema, copyTypes) {
221
+ return schema.fields.map((field) => {
222
+ const srcName = toSnakeCase(field.name);
223
+ const dstName = srcName;
224
+ if (field.array != undefined) {
225
+ if (typeof field.array === "number") {
226
+ return `::memcpy(dest.${dstName}, src.${srcName}.data(), src.${srcName}.size() * sizeof(*src.${srcName}.data()));`;
227
+ }
228
+ else {
229
+ if (field.type.type === "nested") {
230
+ if (copyTypes.has(field.type.schema.name)) {
231
+ return `dest.${dstName} = reinterpret_cast<const foxglove_${toSnakeCase(field.type.schema.name)}*>(src.${srcName}.data());\n dest.${dstName}_count = src.${srcName}.size();`;
232
+ }
233
+ else {
234
+ return `dest.${dstName} = arena.map<foxglove_${toSnakeCase(field.type.schema.name)}>(src.${srcName}, ${toCamelCase(field.type.schema.name)}ToC);
235
+ dest.${dstName}_count = src.${srcName}.size();`;
236
+ }
237
+ }
238
+ else if (field.type.type === "primitive") {
239
+ (0, assert_1.default)(field.type.name !== "bytes");
240
+ return `dest.${dstName} = src.${srcName}.data();\n dest.${dstName}_count = src.${srcName}.size();`;
241
+ }
242
+ else {
243
+ throw Error(`unsupported array type: ${field.type.type}`);
244
+ }
245
+ }
246
+ }
247
+ switch (field.type.type) {
248
+ case "primitive":
249
+ if (field.type.name === "string") {
250
+ return `dest.${dstName} = {src.${srcName}.data(), src.${srcName}.size()};`;
251
+ }
252
+ else if (field.type.name === "bytes") {
253
+ return `dest.${dstName} = reinterpret_cast<const unsigned char *>(src.${srcName}.data());\n dest.${dstName}_len = src.${srcName}.size();`;
254
+ }
255
+ else if (field.type.name === "time") {
256
+ return `dest.${dstName} = src.${srcName} ? reinterpret_cast<const foxglove_timestamp*>(&*src.${srcName}) : nullptr;`;
257
+ }
258
+ else if (field.type.name === "duration") {
259
+ return `dest.${dstName} = src.${srcName} ? reinterpret_cast<const foxglove_duration*>(&*src.${srcName}) : nullptr;`;
260
+ }
261
+ return `dest.${dstName} = src.${srcName};`;
262
+ case "enum":
263
+ return `dest.${dstName} = static_cast<foxglove_${toSnakeCase(field.type.enum.name)}>(src.${srcName});`;
264
+ case "nested":
265
+ if (copyTypes.has(field.type.schema.name)) {
266
+ return `dest.${dstName} = src.${srcName} ? reinterpret_cast<const foxglove_${toSnakeCase(field.type.schema.name)}*>(&*src.${srcName}) : nullptr;`;
267
+ }
268
+ else {
269
+ return `dest.${dstName} = src.${srcName} ? arena.map_one<foxglove_${toSnakeCase(field.type.schema.name)}>(src.${srcName}.value(), ${toCamelCase(field.type.schema.name)}ToC) : nullptr;`;
270
+ }
271
+ }
272
+ });
273
+ }
274
+ function generateCppSchemas(schemas) {
275
+ // Sort by name
276
+ schemas.sort((a, b) => a.name.localeCompare(b.name));
277
+ const copyTypes = new Set(schemas
278
+ .map((schema) => {
279
+ return isSameAsCType(schema) ? schema.name : "";
280
+ })
281
+ .filter((name) => name.length > 0));
282
+ const conversionFuncDecls = schemas.flatMap((schema) => {
283
+ if (isSameAsCType(schema)) {
284
+ return [];
285
+ }
286
+ return [
287
+ `void ${toCamelCase(schema.name)}ToC(foxglove_${toSnakeCase(schema.name)}& dest, const ${schema.name}& src, Arena& arena);`,
288
+ ];
289
+ });
290
+ const traitSpecializations = schemas.flatMap((schema) => {
291
+ const snakeName = toSnakeCase(schema.name);
292
+ let conversionCode;
293
+ if (isSameAsCType(schema)) {
294
+ conversionCode = [
295
+ ` return FoxgloveError(foxglove_channel_log_${snakeName}(impl_.get(), reinterpret_cast<const foxglove_${snakeName}*>(&msg), log_time ? &*log_time : nullptr));`,
296
+ ];
297
+ }
298
+ else {
299
+ conversionCode = [
300
+ " Arena arena;",
301
+ ` foxglove_${snakeName} c_msg;`,
302
+ ` ${toCamelCase(schema.name)}ToC(c_msg, msg, arena);`,
303
+ ` return FoxgloveError(foxglove_channel_log_${snakeName}(impl_.get(), &c_msg, log_time ? &*log_time : nullptr));`,
304
+ ];
305
+ }
306
+ return [
307
+ `FoxgloveResult<${schema.name}Channel> ${schema.name}Channel::create(const std::string_view& topic, const Context& context) {`,
308
+ " const foxglove_channel* channel = nullptr;",
309
+ ` foxglove_error error = foxglove_channel_create_${snakeName}({topic.data(), topic.size()}, context.getInner(), &channel);`,
310
+ " if (error != foxglove_error::FOXGLOVE_ERROR_OK || channel == nullptr) {",
311
+ " return foxglove::unexpected(FoxgloveError(error));",
312
+ " }",
313
+ ` return ${schema.name}Channel(ChannelUniquePtr(channel));`,
314
+ "}\n",
315
+ `FoxgloveError ${schema.name}Channel::log(const ${schema.name}& msg, std::optional<uint64_t> log_time) noexcept {`,
316
+ ...conversionCode,
317
+ "}\n",
318
+ `uint64_t ${schema.name}Channel::id() const noexcept {`,
319
+ " return foxglove_channel_get_id(impl_.get());",
320
+ "}\n\n",
321
+ ];
322
+ });
323
+ const conversionFuncs = schemas.flatMap((schema) => {
324
+ if (isSameAsCType(schema)) {
325
+ return [];
326
+ }
327
+ return [
328
+ `void ${toCamelCase(schema.name)}ToC(foxglove_${toSnakeCase(schema.name)}& dest, const ${schema.name}& src, Arena& arena) {`,
329
+ ` ${cppToC(schema, copyTypes).join("\n ")}`,
330
+ "}\n",
331
+ ];
332
+ });
333
+ const channelUniquePtr = [
334
+ "void ChannelDeleter::operator()(const foxglove_channel* ptr) const noexcept {",
335
+ " foxglove_channel_free(ptr);",
336
+ "};",
337
+ ];
338
+ const systemIncludes = ["#include <optional>", "#include <cstring>"];
339
+ const includes = [
340
+ "#include <foxglove/error.hpp>",
341
+ "#include <foxglove/schemas.hpp>",
342
+ "#include <foxglove/arena.hpp>",
343
+ "#include <foxglove/context.hpp>",
344
+ ];
345
+ const outputSections = [
346
+ "// Generated by https://github.com/foxglove/foxglove-sdk",
347
+ "#include <foxglove-c/foxglove-c.h>",
348
+ includes.join("\n"),
349
+ systemIncludes.join("\n"),
350
+ "namespace foxglove::schemas {",
351
+ channelUniquePtr.join("\n"),
352
+ conversionFuncDecls.join("\n"),
353
+ traitSpecializations.join("\n"),
354
+ conversionFuncs.join("\n"),
355
+ "} // namespace foxglove::schemas",
356
+ ];
357
+ return outputSections.join("\n\n") + "\n";
358
+ }
359
+ //# sourceMappingURL=generateSdkCpp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"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
@@ -0,0 +1,3 @@
1
+ import { FoxgloveEnumSchema, FoxgloveMessageSchema } from "./types";
2
+ export declare function generateRustTypes(schemas: readonly FoxgloveMessageSchema[], enums: readonly FoxgloveEnumSchema[]): string;
3
+ //# sourceMappingURL=generateSdkRustCTypes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateSdkRustCTypes.d.ts","sourceRoot":"","sources":["../../src/internal/generateSdkRustCTypes.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAqB,MAAM,SAAS,CAAC;AAyCvF,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,SAAS,qBAAqB,EAAE,EACzC,KAAK,EAAE,SAAS,kBAAkB,EAAE,GACnC,MAAM,CAmNR"}
@@ -0,0 +1,253 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateRustTypes = generateRustTypes;
4
+ const tslib_1 = require("tslib");
5
+ const assert_1 = tslib_1.__importDefault(require("assert"));
6
+ function primitiveToRust(type) {
7
+ switch (type) {
8
+ case "uint32":
9
+ return "u32";
10
+ case "boolean":
11
+ return "bool";
12
+ case "float64":
13
+ return "f64";
14
+ case "time":
15
+ return "Timestamp";
16
+ case "duration":
17
+ return "Duration";
18
+ case "string":
19
+ return "FoxgloveString";
20
+ case "bytes":
21
+ (0, assert_1.default)(false, "bytes not supported by primitiveToRust");
22
+ }
23
+ }
24
+ function formatComment(comment) {
25
+ return comment
26
+ .split("\n")
27
+ .map((line) => `/// ${line}`)
28
+ .join("\n");
29
+ }
30
+ function escapeId(id) {
31
+ return id === "type" ? `r#${id}` : id;
32
+ }
33
+ function toSnakeCase(name) {
34
+ const snakeName = name.replace(/([A-Z])/g, "_$1").toLowerCase();
35
+ return snakeName.startsWith("_") ? snakeName.substring(1) : snakeName;
36
+ }
37
+ function toTitleCase(name) {
38
+ return name.toLowerCase().replace(/(?:^|_)([a-z])/g, (_, letter) => letter.toUpperCase());
39
+ }
40
+ function generateRustTypes(schemas, enums) {
41
+ const schemaStructs = schemas.map((schema) => {
42
+ const { fields, description } = schema;
43
+ const name = schema.name.replace("JSON", "Json");
44
+ const snakeName = toSnakeCase(name);
45
+ return `\
46
+ ${formatComment(description)}
47
+ #[repr(C)]
48
+ pub struct ${name} {
49
+ ${fields
50
+ .flatMap((field) => {
51
+ const comment = formatComment(field.description);
52
+ const identName = escapeId(toSnakeCase(field.name));
53
+ let fieldType;
54
+ let fieldHasLen = false;
55
+ switch (field.type.type) {
56
+ case "primitive":
57
+ if (field.type.name === "bytes") {
58
+ fieldType = "*const c_uchar";
59
+ fieldHasLen = true;
60
+ }
61
+ else if (field.type.name === "time") {
62
+ fieldType = "*const FoxgloveTimestamp";
63
+ }
64
+ else if (field.type.name === "duration") {
65
+ fieldType = "*const FoxgloveDuration";
66
+ }
67
+ else {
68
+ fieldType = primitiveToRust(field.type.name);
69
+ }
70
+ break;
71
+ case "enum":
72
+ fieldType = `Foxglove${field.type.enum.name}`;
73
+ break;
74
+ case "nested":
75
+ fieldType = field.type.schema.name.replace("JSON", "Json");
76
+ break;
77
+ }
78
+ const lines = [comment];
79
+ if (typeof field.array === "number") {
80
+ lines.push(`pub ${identName}: [${fieldType}; ${field.array}],`);
81
+ if (fieldHasLen) {
82
+ lines.push(`pub ${identName}_len: [usize; ${field.array}],`);
83
+ }
84
+ }
85
+ else if (field.array === true) {
86
+ lines.push(`pub ${identName}: *const ${fieldType},`);
87
+ if (fieldHasLen) {
88
+ lines.push(`pub ${identName}_len: *const usize,`);
89
+ }
90
+ lines.push(`pub ${identName}_count: usize,`);
91
+ }
92
+ else {
93
+ if (field.type.type === "nested") {
94
+ fieldType = `*const ${fieldType}`;
95
+ }
96
+ lines.push(`pub ${identName}: ${fieldType},`);
97
+ if (fieldHasLen) {
98
+ lines.push(`pub ${identName}_len: usize,`);
99
+ }
100
+ }
101
+ return lines.join("\n");
102
+ })
103
+ .join("\n\n")}
104
+ }
105
+
106
+ impl ${name} {
107
+ /// Create a new typed channel, and return an owned raw channel pointer to it.
108
+ ///
109
+ /// # Safety
110
+ /// We're trusting the caller that the channel will only be used with this type T.
111
+ #[unsafe(no_mangle)]
112
+ pub unsafe extern "C" fn foxglove_channel_create_${snakeName}(
113
+ topic: FoxgloveString,
114
+ context: *const FoxgloveContext,
115
+ channel: *mut *const FoxgloveChannel,
116
+ ) -> FoxgloveError {
117
+ if channel.is_null() {
118
+ tracing::error!("channel cannot be null");
119
+ return FoxgloveError::ValueError;
120
+ }
121
+ unsafe {
122
+ let result = do_foxglove_channel_create::<foxglove::schemas::${name}>(topic, context);
123
+ result_to_c(result, channel)
124
+ }
125
+ }
126
+ }
127
+
128
+ impl BorrowToNative for ${name} {
129
+ type NativeType = foxglove::schemas::${name};
130
+
131
+ unsafe fn borrow_to_native(&self, #[allow(unused_mut, unused_variables)] mut arena: Pin<&mut Arena>) -> Result<ManuallyDrop<Self::NativeType>, foxglove::FoxgloveError> {
132
+ ${fields
133
+ .flatMap((field) => {
134
+ const fieldName = escapeId(toSnakeCase(field.name));
135
+ if (field.array != undefined &&
136
+ typeof field.array !== "number" &&
137
+ field.type.type === "nested") {
138
+ return [
139
+ `let ${fieldName} = unsafe { arena.as_mut().map(self.${fieldName}, self.${fieldName}_count)? };`,
140
+ ];
141
+ }
142
+ switch (field.type.type) {
143
+ case "primitive":
144
+ if (field.type.name === "string") {
145
+ return [
146
+ `let ${fieldName} = unsafe { string_from_raw(self.${fieldName}.as_ptr() as *const _, self.${fieldName}.len(), "${field.name}")? };`,
147
+ ];
148
+ }
149
+ return [];
150
+ case "nested":
151
+ return [
152
+ `let ${fieldName} = unsafe { self.${fieldName}.as_ref().map(|m| m.borrow_to_native(arena.as_mut())) }.transpose()?;`,
153
+ ];
154
+ case "enum":
155
+ return [];
156
+ }
157
+ })
158
+ .join("\n ")}
159
+
160
+ Ok(ManuallyDrop::new(foxglove::schemas::${name} {
161
+ ${fields
162
+ .map((field) => {
163
+ const fieldName = escapeId(toSnakeCase(field.name));
164
+ if (field.array != undefined) {
165
+ if (typeof field.array === "number") {
166
+ (0, assert_1.default)(field.type.type === "primitive", `unsupported array type: ${field.type.type}`);
167
+ return `${fieldName}: ManuallyDrop::into_inner(unsafe { vec_from_raw(self.${fieldName}.as_ptr() as *mut ${primitiveToRust(field.type.name)}, self.${fieldName}.len()) })`;
168
+ }
169
+ else {
170
+ if (field.type.type === "nested") {
171
+ return `${fieldName}: ManuallyDrop::into_inner(${fieldName})`;
172
+ }
173
+ else if (field.type.type === "primitive") {
174
+ (0, assert_1.default)(field.type.name !== "bytes");
175
+ return `${fieldName}: ManuallyDrop::into_inner(unsafe { vec_from_raw(self.${fieldName} as *mut ${primitiveToRust(field.type.name)}, self.${fieldName}_count) })`;
176
+ }
177
+ else {
178
+ throw Error(`unsupported array type: ${field.type.type}`);
179
+ }
180
+ }
181
+ }
182
+ switch (field.type.type) {
183
+ case "primitive":
184
+ if (field.type.name === "string") {
185
+ return `${fieldName}: ManuallyDrop::into_inner(${fieldName})`;
186
+ }
187
+ else if (field.type.name === "bytes") {
188
+ return `${fieldName}: ManuallyDrop::into_inner(unsafe { bytes_from_raw(self.${fieldName}, self.${fieldName}_len) })`;
189
+ }
190
+ else if (field.type.name === "time" || field.type.name === "duration") {
191
+ return `${fieldName}: unsafe { self.${fieldName}.as_ref() }.map(|&m| m.into())`;
192
+ }
193
+ return `${fieldName}: self.${fieldName}`;
194
+ case "enum":
195
+ return `${fieldName}: self.${fieldName} as i32`;
196
+ case "nested":
197
+ return `${fieldName}: ${fieldName}.map(ManuallyDrop::into_inner)`;
198
+ }
199
+ })
200
+ .join(",\n ")}
201
+ }))
202
+ }
203
+ }
204
+
205
+ /// Log a ${name} message to a channel.
206
+ ///
207
+ /// # Safety
208
+ /// The channel must have been created for this type with foxglove_channel_create_${snakeName}.
209
+ #[unsafe(no_mangle)]
210
+ pub extern "C" fn foxglove_channel_log_${snakeName}(channel: Option<&FoxgloveChannel>, msg: Option<&${name}>, log_time: Option<&u64>) -> FoxgloveError {
211
+ let mut arena = pin!(Arena::new());
212
+ let arena_pin = arena.as_mut();
213
+ // Safety: we're borrowing from the msg, but discard the borrowed message before returning
214
+ match unsafe { ${name}::borrow_option_to_native(msg, arena_pin) } {
215
+ Ok(msg) => {
216
+ // Safety: this casts channel back to a typed channel for type of msg, it must have been created for this type.
217
+ log_msg_to_channel(channel, &*msg, log_time)
218
+ },
219
+ Err(e) => {
220
+ tracing::error!("${name}: {}", e);
221
+ e.into()
222
+ }
223
+ }
224
+ }
225
+ `;
226
+ });
227
+ const imports = [
228
+ "use std::ffi::c_uchar;",
229
+ "use std::mem::ManuallyDrop;",
230
+ "use std::pin::{pin, Pin};",
231
+ "",
232
+ "use crate::{FoxgloveString, FoxgloveError, FoxgloveChannel, FoxgloveContext, FoxgloveTimestamp, FoxgloveDuration, log_msg_to_channel, result_to_c, do_foxglove_channel_create};",
233
+ "use crate::arena::{Arena, BorrowToNative};",
234
+ "use crate::util::{bytes_from_raw, string_from_raw, vec_from_raw};",
235
+ ];
236
+ const enumDefs = enums.map((enumSchema) => {
237
+ return `
238
+ #[derive(Clone, Copy, Debug)]
239
+ #[repr(i32)]
240
+ pub enum Foxglove${enumSchema.name} {
241
+ ${enumSchema.values.map((value) => `${toTitleCase(value.name)} = ${value.value},`).join("\n")}
242
+ }`;
243
+ });
244
+ const outputSections = [
245
+ "// Generated by https://github.com/foxglove/foxglove-sdk",
246
+ imports.join("\n"),
247
+ enumDefs.join("\n"),
248
+ ...schemaStructs,
249
+ "",
250
+ ];
251
+ return outputSections.join("\n\n");
252
+ }
253
+ //# sourceMappingURL=generateSdkRustCTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateSdkRustCTypes.js","sourceRoot":"","sources":["../../src/internal/generateSdkRustCTypes.ts"],"names":[],"mappings":";;AA2CA,8CAsNC;;AAjQD,4DAA4B;AAI5B,SAAS,eAAe,CAAC,IAAuB;IAC9C,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,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.ts","sourceRoot":"","sources":["../../src/internal/schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAs+CpE,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwClC,CAAC;AAEF,eAAO,MAAM,mBAAmB;;;;;;;CAO/B,CAAC"}
1
+ {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/internal/schemas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAy+CpE,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwClC,CAAC;AAEF,eAAO,MAAM,mBAAmB;;;;;;;CAO/B,CAAC"}