@polytric/openws-sdkgen 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # OpenWS SDK Generator
2
+
3
+ `@polytric/openws-sdkgen` is the OpenWS SDK generator CLI. It takes an OpenWS spec JSON file and produces SDK source code for a target language/environment.
4
+
5
+ The generator is pipeline-driven:
6
+
7
+ - Parse CLI arguments
8
+ - Load the OpenWS spec
9
+ - Build an intermediate representation
10
+ - Execute a build plan for the selected language/environment
11
+
12
+ ---
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pnpm add -g @polytric/openws-sdkgen
18
+ ```
19
+
20
+ ---
21
+
22
+ ## Usage
23
+
24
+ ```bash
25
+ openws-sdkgen \
26
+ --spec ./openws-spec.json \
27
+ --out ./generated \
28
+ --project MyCompany \
29
+ --service ChatService \
30
+ --hostRole server \
31
+ --language csharp \
32
+ --environment unity
33
+ ```
34
+
35
+ The CLI exposes the following options:
36
+
37
+ - `--spec` (string): Path to the OpenWS spec JSON file.
38
+ - `--out` (string): Output directory for generated code.
39
+ - `--project` (string): Project/namespace prefix for generated code.
40
+ - `--service` (string): Service name (default: `MyService`).
41
+ - `--hostRole` (string): Participant role name that represents the host side.
42
+ - `--language` (string): Target language (`csharp` or `javascript`).
43
+ - `--environment` (string|array): Target environment (`unity`, `node`, `browser`).
44
+
45
+ ---
46
+
47
+ ## Current targets
48
+
49
+ The generator is wired for:
50
+
51
+ - C# (Unity) with `newtonsoft` serialization templates.
52
+
53
+ Additional targets are configured through build plans in `tooling/sdkgen/dotnet` and can be expanded as needed.
54
+
55
+ ---
56
+
57
+ ## License
58
+
59
+ Apache-2.0
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@polytric/openws-sdkgen",
3
+ "version": "0.0.1",
4
+ "description": "OpenWS SDK generator CLI",
5
+ "license": "Apache-2.0",
6
+ "author": "Polytric",
7
+ "engines": {
8
+ "node": ">=18"
9
+ },
10
+ "bin": {
11
+ "openws-sdkgen": "./src/main.js"
12
+ },
13
+ "files": [
14
+ "src",
15
+ "LICENSE",
16
+ "README.md"
17
+ ],
18
+ "keywords": [
19
+ "openws",
20
+ "sdk",
21
+ "codegen",
22
+ "websocket",
23
+ "unity",
24
+ "dotnet"
25
+ ],
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/AgeOfLearning/openws.git",
29
+ "directory": "tooling/sdkgen"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@pocketgems/schema": "^0.1.3",
36
+ "ejs": "^3.1.10",
37
+ "yargs": "^18.0.0"
38
+ },
39
+ "scripts": {}
40
+ }
@@ -0,0 +1,220 @@
1
+ const S = require('@pocketgems/schema')
2
+
3
+ const validateIr = S.obj({
4
+ package: S.obj({
5
+ project: S.str,
6
+ service: S.str,
7
+ description: S.str.optional(),
8
+ version: S.str.optional(),
9
+ }),
10
+ networks: S.arr(
11
+ S.obj({
12
+ name: S.str,
13
+ description: S.str.optional(),
14
+ version: S.str.optional(),
15
+ roles: S.arr(
16
+ S.obj({
17
+ name: S.str,
18
+ description: S.str.optional(),
19
+ isHost: S.bool,
20
+ endpoints: S.arr(
21
+ S.obj({
22
+ scheme: S.str.enum('ws', 'wss'),
23
+ host: S.str,
24
+ port: S.int.min(0).max(65535),
25
+ path: S.str,
26
+ })
27
+ ),
28
+ })
29
+ ),
30
+ handlers: S.arr(
31
+ S.obj({
32
+ roleName: S.str,
33
+ handlerName: S.str,
34
+ description: S.str.optional(),
35
+ })
36
+ ),
37
+ messages: S.arr(
38
+ S.obj({
39
+ roleName: S.str,
40
+ handlerName: S.str,
41
+ description: S.str.optional(),
42
+ })
43
+ ),
44
+ models: S.arr(
45
+ S.obj({
46
+ scopeName: S.str,
47
+ modelName: S.str,
48
+ type: S.str,
49
+ description: S.str.optional(),
50
+ properties: S.arr(
51
+ S.obj({
52
+ type: S.str,
53
+ scopeName: S.str,
54
+ modelName: S.str,
55
+ description: S.str.optional(),
56
+ required: S.bool.optional(),
57
+ items: S.obj({
58
+ type: S.str,
59
+ scopeName: S.str,
60
+ modelName: S.str,
61
+ description: S.str.optional(),
62
+ }).optional(),
63
+ })
64
+ ).optional(),
65
+ })
66
+ ),
67
+ })
68
+ ).desc('An array of network definitions'),
69
+ }).compile('IrValidator')
70
+
71
+ function buildIrModels(scopeName, modelName, schema) {
72
+ const type = schema.type
73
+ const model = {
74
+ type,
75
+ scopeName,
76
+ modelName,
77
+ description: schema.description,
78
+ }
79
+ switch (type) {
80
+ case 'string':
81
+ case 'number':
82
+ case 'integer':
83
+ case 'boolean':
84
+ case 'null':
85
+ return []
86
+ case 'array': {
87
+ return buildIrModels(scopeName, modelName, schema.items)
88
+ }
89
+ case 'object': {
90
+ const properties = []
91
+ model.properties = properties
92
+ const models = []
93
+ for (const [subName, subSchema] of Object.entries(schema.properties)) {
94
+ const subModels = buildIrModels(scopeName, subName, subSchema)
95
+ const mainModel = subModels.find(m => m.modelName === subName) ?? subSchema
96
+ const property = {
97
+ type: mainModel.type,
98
+ description: mainModel.description,
99
+ scopeName: mainModel.scopeName ?? scopeName,
100
+ modelName: mainModel.modelName ?? subName,
101
+ required: schema.required?.includes(subName),
102
+ }
103
+
104
+ if (mainModel.items) {
105
+ property.items = {
106
+ type: mainModel.items.type,
107
+ description: mainModel.items.description,
108
+ scopeName: mainModel.items.scopeName ?? scopeName,
109
+ modelName: mainModel.items.modelName ?? subName,
110
+ }
111
+ }
112
+ properties.push(property)
113
+ models.push(...subModels)
114
+ }
115
+ return [model, ...models]
116
+ }
117
+ }
118
+ }
119
+
120
+ module.exports = function buildIr(ctx) {
121
+ const { request, spec } = ctx
122
+ const { hostRoles } = request
123
+
124
+ const irPackage = {
125
+ project: request.project,
126
+ service: spec.name,
127
+ description: spec.description,
128
+ version: spec.version,
129
+ }
130
+ const irNetworks = []
131
+ const ir = {
132
+ package: irPackage,
133
+ networks: irNetworks,
134
+ }
135
+
136
+ for (const [networkName, networkSpec] of Object.entries(spec.networks)) {
137
+ const hostRoleSpecs = hostRoles.map(hostRole => networkSpec.roles[hostRole])
138
+ const otherRoleSpecs = {}
139
+ for (const [roleName, roleSpec] of Object.entries(networkSpec.roles)) {
140
+ if (!hostRoles.includes(roleName)) {
141
+ otherRoleSpecs[roleName] = roleSpec
142
+ }
143
+ }
144
+
145
+ const requiredRoles = new Set()
146
+ for (const hostRoleSpec of hostRoleSpecs) {
147
+ for (const handlerSpec of Object.values(hostRoleSpec.messages)) {
148
+ if (handlerSpec.from) {
149
+ for (const fromRoleName of handlerSpec.from) {
150
+ requiredRoles.add(fromRoleName)
151
+ }
152
+ } else {
153
+ requiredRoles.add(...Object.keys(otherRoleSpecs))
154
+ break
155
+ }
156
+ }
157
+ }
158
+
159
+ const irRoles = []
160
+ const irHandlers = []
161
+ const irMessages = []
162
+ const irModels = []
163
+
164
+ // Add host roles
165
+ for (const hostRoleSpec of hostRoleSpecs) {
166
+ irRoles.push({
167
+ name: hostRoleSpec.name,
168
+ description: hostRoleSpec.description,
169
+ isHost: true,
170
+ endpoints: hostRoleSpec.endpoints || [],
171
+ })
172
+ for (const [handlerName, handlerSpec] of Object.entries(hostRoleSpec.messages)) {
173
+ irHandlers.push({
174
+ roleName: hostRoleSpec.name,
175
+ handlerName,
176
+ description: handlerSpec.description,
177
+ })
178
+ irModels.push(...buildIrModels(hostRoleSpec.name, handlerName, handlerSpec.payload))
179
+ }
180
+ }
181
+
182
+ // Add remote roles
183
+ for (const [roleName, roleSpec] of Object.entries(otherRoleSpecs)) {
184
+ if (!requiredRoles.has(roleName)) {
185
+ continue
186
+ }
187
+ irRoles.push({
188
+ name: roleName,
189
+ description: roleSpec.description,
190
+ isHost: false,
191
+ endpoints: roleSpec.endpoints || [],
192
+ })
193
+ for (const [handlerName, handlerSpec] of Object.entries(roleSpec.messages)) {
194
+ irMessages.push({
195
+ roleName,
196
+ handlerName,
197
+ description: handlerSpec.description,
198
+ })
199
+ irModels.push(...buildIrModels(roleName, handlerName, handlerSpec.payload))
200
+ }
201
+ }
202
+
203
+ const irNetwork = {
204
+ name: networkName,
205
+ description: networkSpec.description,
206
+ version: networkSpec.version,
207
+ roles: irRoles,
208
+ handlers: irHandlers,
209
+ messages: irMessages,
210
+ models: irModels,
211
+ }
212
+ irNetworks.push(irNetwork)
213
+ }
214
+
215
+ validateIr(ir)
216
+ return {
217
+ ...ctx,
218
+ ir,
219
+ }
220
+ }
@@ -0,0 +1,16 @@
1
+ const path = require('node:path')
2
+
3
+ const planIndex = {
4
+ csharp: {
5
+ unity: './dotnet/build-plan.js',
6
+ },
7
+ }
8
+
9
+ module.exports = function dispatchBuildPlan(ctx) {
10
+ const { request } = ctx
11
+ const language = Object.keys(request.target)[0]
12
+ const environment = request.target[language].environment
13
+ const templatePath = planIndex[language][environment]
14
+ const plan = require(path.join(__dirname, templatePath))
15
+ return plan(ctx)
16
+ }
@@ -0,0 +1,46 @@
1
+ const path = require('node:path')
2
+ const { cwd } = require('node:process')
3
+
4
+ const S = require('@pocketgems/schema')
5
+
6
+ const validateBuildRequest = S.obj({
7
+ specPath: S.str,
8
+ outputPath: S.str,
9
+ project: S.str,
10
+ hostRoles: S.arr(S.str),
11
+ target: S.obj({
12
+ csharp: S.obj({
13
+ environment: S.str.enum('unity'), // aspnet
14
+ frameworks: S.arr(S.str.enum('newtonsoft')).optional(),
15
+ }).optional(),
16
+ javascript: S.obj({
17
+ environment: S.str.enum('node'), // browser
18
+ frameworks: S.arr(S.str.enum('fastify')).optional(),
19
+ }).optional(),
20
+ })
21
+ .min(1)
22
+ .max(1)
23
+ .desc('The target platform to generate code for'),
24
+ }).compile('BuildRequestValidator')
25
+
26
+ module.exports = function buildRequest(ctx) {
27
+ const { rawInput } = ctx
28
+ console.log(rawInput.hostRole)
29
+ const request = {
30
+ specPath: path.join(process.cwd(), rawInput.spec),
31
+ outputPath: path.join(process.cwd(), rawInput.out),
32
+ project: rawInput.project,
33
+ hostRoles: rawInput.hostRole, // naming oddity from cli --hostRole serverA --hostRole serverB is readable as singular hostRole
34
+ target: {
35
+ [rawInput.language]: {
36
+ environment: rawInput.environment,
37
+ frameworks: rawInput.frameworks,
38
+ },
39
+ },
40
+ }
41
+ validateBuildRequest(request)
42
+ return {
43
+ ...ctx,
44
+ request,
45
+ }
46
+ }
@@ -0,0 +1,215 @@
1
+ const path = require('node:path')
2
+
3
+ function pascalCase(str) {
4
+ return str.charAt(0).toUpperCase() + str.slice(1)
5
+ }
6
+
7
+ function camelCase(str) {
8
+ return str.charAt(0).toLowerCase() + str.slice(1)
9
+ }
10
+
11
+ function createPlan(ctx) {
12
+ const { ir, request } = ctx
13
+ const assemblyName = `${pascalCase(ir.package.project)}.${pascalCase(ir.package.service)}.Sdk`
14
+ ir.assemblyName = assemblyName
15
+
16
+ const plan = [
17
+ {
18
+ name: 'assembly definition',
19
+ command: 'render',
20
+ getData: () => ctx.ir,
21
+ template: path.join(__dirname, 'template', 'Service.asmdef.ejs'),
22
+ output: path.join(ctx.request.outputPath, assemblyName, `${assemblyName}.asmdef`),
23
+ },
24
+ {
25
+ name: 'user assembly reference',
26
+ command: 'render',
27
+ getData: () => ctx.ir,
28
+ template: path.join(__dirname, 'template', 'UserService.asmref.ejs'),
29
+ output: path.join(
30
+ ctx.request.outputPath,
31
+ `${assemblyName}.User`,
32
+ `${assemblyName}.User.asmref`
33
+ ),
34
+ },
35
+ ]
36
+
37
+ for (const networkIr of ir.networks) {
38
+ const networkNamespace = `${pascalCase(ir.package.project)}.${pascalCase(ir.package.service)}.${pascalCase(networkIr.name)}`
39
+ const networkClassName = `${pascalCase(networkIr.name)}Network`
40
+ const networkOutputPath = path.join(
41
+ ctx.request.outputPath,
42
+ assemblyName,
43
+ pascalCase(networkIr.name)
44
+ )
45
+ const userNetworkOutputPath = path.join(
46
+ ctx.request.outputPath,
47
+ `${assemblyName}.User`,
48
+ pascalCase(networkIr.name)
49
+ )
50
+
51
+ // Build role info from IR
52
+ const hostRoles = []
53
+ const remoteRoles = []
54
+
55
+ for (const role of networkIr.roles) {
56
+ const roleInfo = {
57
+ roleName: role.name,
58
+ className: pascalCase(role.name),
59
+ varName: camelCase(role.name),
60
+ description: role.description || '',
61
+ baseClassName: role.isHost ? 'HostRole' : 'RemoteRole',
62
+ endpoints: role.endpoints || [],
63
+ }
64
+ if (role.isHost) {
65
+ hostRoles.push(roleInfo)
66
+ } else {
67
+ remoteRoles.push(roleInfo)
68
+ }
69
+ }
70
+
71
+ const allRoles = [...hostRoles, ...remoteRoles]
72
+
73
+ // Build all model imports for user templates
74
+ const allModelImports = allRoles.map(role => `${networkNamespace}.Models.${role.className}`)
75
+
76
+ // Generate Network.cs
77
+ plan.push({
78
+ name: `network ${networkIr.name}`,
79
+ command: 'render',
80
+ getData: () => ({
81
+ namespace: networkNamespace,
82
+ networkClassName,
83
+ networkName: networkIr.name,
84
+ description: networkIr.description,
85
+ version: networkIr.version,
86
+ allRoles,
87
+ }),
88
+ template: path.join(__dirname, 'template', 'Network.cs.ejs'),
89
+ output: path.join(networkOutputPath, `${networkClassName}.cs`),
90
+ })
91
+
92
+ // Process models
93
+ for (const modelIr of networkIr.models) {
94
+ modelIr.namespace = `${networkNamespace}.Models.${pascalCase(modelIr.scopeName)}`
95
+ modelIr.className = pascalCase(modelIr.modelName)
96
+ if (modelIr.properties) {
97
+ for (const propertyIr of modelIr.properties) {
98
+ propertyIr.propertyName = pascalCase(propertyIr.modelName)
99
+ propertyIr.typeName = mapType(propertyIr)
100
+ }
101
+ }
102
+ }
103
+
104
+ // Process handlers (incoming messages for host roles)
105
+ for (const handlerIr of networkIr.handlers) {
106
+ handlerIr.modelClassName = pascalCase(handlerIr.handlerName)
107
+ handlerIr.messageName = handlerIr.handlerName
108
+ handlerIr.methodName = pascalCase(handlerIr.handlerName)
109
+ }
110
+
111
+ // Process messages (outgoing messages to remote roles)
112
+ for (const messageIr of networkIr.messages) {
113
+ messageIr.modelClassName = pascalCase(messageIr.handlerName)
114
+ messageIr.messageName = messageIr.handlerName
115
+ messageIr.methodName = pascalCase(messageIr.handlerName)
116
+ }
117
+
118
+ // Generate HostRole classes
119
+ for (const hostRole of hostRoles) {
120
+ const roleHandlers = networkIr.handlers.filter(h => h.roleName === hostRole.roleName)
121
+ const modelImports = [`${networkNamespace}.Models.${hostRole.className}`]
122
+
123
+ plan.push({
124
+ name: `host role ${hostRole.className}`,
125
+ command: 'render',
126
+ getData: () => ({
127
+ namespace: `${networkNamespace}.Roles`,
128
+ handlers: roleHandlers,
129
+ remoteRoles,
130
+ modelImports,
131
+ ...hostRole,
132
+ }),
133
+ template: path.join(__dirname, 'template', 'HostRole.cs.ejs'),
134
+ output: path.join(networkOutputPath, 'Roles', `${hostRole.className}.cs`),
135
+ })
136
+
137
+ // Generate User stub for HostRole
138
+ plan.push({
139
+ name: `user host role ${hostRole.className}`,
140
+ command: 'render',
141
+ getData: () => ({
142
+ namespace: `${networkNamespace}.Roles`,
143
+ handlers: roleHandlers,
144
+ remoteRoles,
145
+ modelImports: allModelImports,
146
+ ...hostRole,
147
+ }),
148
+ template: path.join(__dirname, 'template', 'UserHostRole.cs.ejs'),
149
+ output: path.join(userNetworkOutputPath, 'Roles', `${hostRole.className}.cs`),
150
+ })
151
+ }
152
+
153
+ // Generate RemoteRole classes
154
+ for (const remoteRole of remoteRoles) {
155
+ const roleMessages = networkIr.messages.filter(m => m.roleName === remoteRole.roleName)
156
+ const modelImports = [`${networkNamespace}.Models.${remoteRole.className}`]
157
+
158
+ plan.push({
159
+ name: `remote role ${remoteRole.className}`,
160
+ command: 'render',
161
+ getData: () => ({
162
+ namespace: `${networkNamespace}.Roles`,
163
+ messages: roleMessages,
164
+ modelImports,
165
+ ...remoteRole,
166
+ }),
167
+ template: path.join(__dirname, 'template', 'RemoteRole.cs.ejs'),
168
+ output: path.join(networkOutputPath, 'Roles', `${remoteRole.className}.cs`),
169
+ })
170
+ }
171
+
172
+ // Generate Models
173
+ for (const modelIr of networkIr.models) {
174
+ if (modelIr.type !== 'object') continue
175
+ plan.push({
176
+ name: `model ${modelIr.className}`,
177
+ command: 'render',
178
+ getData: () => modelIr,
179
+ template: path.join(__dirname, 'template', 'Model.cs.ejs'),
180
+ output: path.join(
181
+ networkOutputPath,
182
+ 'Models',
183
+ pascalCase(modelIr.scopeName),
184
+ `${modelIr.className}.cs`
185
+ ),
186
+ })
187
+ }
188
+ }
189
+
190
+ return {
191
+ ...ctx,
192
+ plan,
193
+ }
194
+ }
195
+
196
+ function mapType(property) {
197
+ switch (property.type) {
198
+ case 'string':
199
+ return 'string'
200
+ case 'number':
201
+ return 'double'
202
+ case 'integer':
203
+ return 'int'
204
+ case 'boolean':
205
+ return 'bool'
206
+ case 'array':
207
+ return `List<${mapType(property.items)}>`
208
+ case 'object':
209
+ return pascalCase(property.modelName)
210
+ default:
211
+ return 'object'
212
+ }
213
+ }
214
+
215
+ module.exports = createPlan
@@ -0,0 +1,52 @@
1
+ using System.Threading.Tasks;
2
+ using Newtonsoft.Json.Linq;
3
+ using Polytric.OpenWs.Core;
4
+ <% for (const modelImport of ctx.modelImports) { -%>
5
+ using <%= modelImport %>;
6
+ <% } -%>
7
+
8
+ namespace <%= ctx.namespace %>
9
+ {
10
+ public partial class <%= ctx.className %> : <%= ctx.baseClassName %>
11
+ {
12
+ public override string Name { get; set; } = "<%= ctx.roleName %>";
13
+ public override string Description { get; set; } = "<%= ctx.description ?? '' %>";
14
+
15
+ public override async Task HandleOpenAsync(RemoteRole remoteRole)
16
+ {
17
+ <% for (const remoteRole of ctx.remoteRoles) { %>
18
+ if (remoteRole is <%= remoteRole.className %> <%= remoteRole.varName %>)
19
+ {
20
+ await HandleOpenAsync(<%= remoteRole.varName %>).ConfigureAwait(false);
21
+ }
22
+ <% } -%>
23
+ }
24
+
25
+ <% for (const remoteRole of ctx.remoteRoles) { -%>
26
+ private partial Task HandleOpenAsync(<%= remoteRole.className %> <%= remoteRole.varName %>);
27
+ <% } -%>
28
+
29
+ public override async Task HandleMessageAsync(string messageName, JToken payload, RemoteRole remoteRole)
30
+ {
31
+ switch (messageName)
32
+ {
33
+ <% for (const handler of ctx.handlers) { %>
34
+ case "<%= handler.messageName %>":
35
+ {
36
+ var message = payload.ToObject<<%= handler.modelClassName %>>();
37
+ <% for (const remoteRole of ctx.remoteRoles) { %>
38
+ await HandleMessageAsync(message, remoteRole as <%= remoteRole.className %>).ConfigureAwait(false);
39
+ <% } -%>
40
+ break;
41
+ }
42
+ <% } -%>
43
+ }
44
+ }
45
+
46
+ <% for (const handler of ctx.handlers) { -%>
47
+ <% for (const remoteRole of ctx.remoteRoles) { -%>
48
+ private partial Task HandleMessageAsync(<%= handler.modelClassName %> payload, <%= remoteRole.className %> <%= remoteRole.varName %>);
49
+ <% } -%>
50
+ <% } -%>
51
+ }
52
+ }
@@ -0,0 +1,13 @@
1
+ using Newtonsoft.Json;
2
+
3
+ namespace <%= ctx.namespace %>
4
+ {
5
+ public class <%= ctx.className %>
6
+ {
7
+ <% for (const property of ctx.properties) { -%>
8
+ [JsonProperty("<%= property.modelName %>")]
9
+ public <%= property.typeName %> <%= property.propertyName %>;
10
+
11
+ <% } -%>
12
+ }
13
+ }
@@ -0,0 +1,14 @@
1
+ using Polytric.OpenWs.Core;
2
+ using System;
3
+ using <%= ctx.namespace %>.Roles;
4
+
5
+ namespace <%= ctx.namespace %>
6
+ {
7
+ public partial class <%= ctx.networkClassName %> : Network
8
+ {
9
+ public override string Name { get; set; } = "<%= ctx.networkName %>";
10
+ public override string Description { get; set; } = "<%= ctx.description ?? '' %>";
11
+ public override string Version { get; set; } = "<%= ctx.version ?? '1.0.0' %>";
12
+ public override Type[] Roles { get; set; } = new Type[] { <% for (let i = 0; i < ctx.allRoles.length; i++) { -%>typeof(<%= ctx.allRoles[i].className %>)<%= i < ctx.allRoles.length - 1 ? ', ' : '' %><% } -%> };
13
+ }
14
+ }
@@ -0,0 +1,34 @@
1
+ using Polytric.OpenWs.Core;
2
+ using Polytric.OpenWs.Spec.Serialization;
3
+ using System;
4
+ using System.Collections.Generic;
5
+ using System.Threading.Tasks;
6
+ <% for (const modelImport of ctx.modelImports) { %>
7
+ using <%= modelImport %>;
8
+ <% } %>
9
+
10
+ namespace <%= ctx.namespace %>
11
+ {
12
+ public partial class <%= ctx.className %> : <%= ctx.baseClassName %>
13
+ {
14
+ public override string Name { get; set; } = "<%= ctx.roleName %>";
15
+ public override string Description { get; set; } = "<%= ctx.description ?? '' %>";
16
+ <% if (ctx.endpoints && ctx.endpoints.length > 0) { -%>
17
+ public override IReadOnlyList<Endpoint> Endpoints { get; set; } = new List<Endpoint>
18
+ {
19
+ <% for (const ep of ctx.endpoints) { -%>
20
+ new Endpoint { Scheme = "<%= ep.scheme %>", Host = "<%= ep.host %>", Port = <%= ep.port %>, Path = "<%= ep.path %>" },
21
+ <% } -%>
22
+ };
23
+ <% } -%>
24
+
25
+ <% for (const message of ctx.messages) { -%>
26
+ public async Task <%= message.methodName %>Async(string fromRole, <%= message.modelClassName %> message)
27
+ {
28
+ await SendMessageAsync(fromRole, "<%= message.messageName %>", message).ConfigureAwait(false);
29
+ }
30
+
31
+ <% } -%>
32
+ }
33
+ }
34
+
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "<%= ctx.assemblyName %>",
3
+ "rootNamespace": "",
4
+ "references": [
5
+ "Polytric.OpenWs.Core.Runtime",
6
+ "Polytric.OpenWs.Spec",
7
+ "Polytric.OpenWs.Unity.Runtime"
8
+ ],
9
+ "includePlatforms": [],
10
+ "excludePlatforms": [],
11
+ "allowUnsafeCode": false,
12
+ "overrideReferences": false,
13
+ "precompiledReferences": [],
14
+ "autoReferenced": true,
15
+ "defineConstraints": [],
16
+ "versionDefines": [],
17
+ "noEngineReferences": false
18
+ }
@@ -0,0 +1,29 @@
1
+ using System.Threading.Tasks;
2
+ using Polytric.OpenWs.Core;
3
+ <% for (const modelImport of ctx.modelImports) { -%>
4
+ using <%= modelImport %>;
5
+ <% } %>
6
+ namespace <%= ctx.namespace %>
7
+ {
8
+ public partial class <%= ctx.className %>
9
+ {
10
+ <% for (const remoteRole of ctx.remoteRoles) { -%>
11
+ private partial Task HandleOpenAsync(<%= remoteRole.className %> <%= remoteRole.varName %>)
12
+ {
13
+ // TODO: Implement connection handling for <%= remoteRole.className %>
14
+ return Task.CompletedTask;
15
+ }
16
+
17
+ <% } -%>
18
+ <% for (const handler of ctx.handlers) { -%>
19
+ <% for (const remoteRole of ctx.remoteRoles) { -%>
20
+ private partial Task HandleMessageAsync(<%= handler.modelClassName %> payload, <%= remoteRole.className %> <%= remoteRole.varName %>)
21
+ {
22
+ // TODO: Handle <%= handler.messageName %> from <%= remoteRole.className %>
23
+ return Task.CompletedTask;
24
+ }
25
+
26
+ <% } -%>
27
+ <% } -%>
28
+ }
29
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "reference": "<%= ctx.assemblyName %>"
3
+ }
@@ -0,0 +1,38 @@
1
+ const fs = require('node:fs')
2
+ const path = require('node:path')
3
+
4
+ const ejs = require('ejs')
5
+
6
+ const rendererCache = {}
7
+
8
+ function renderTemplate(templatePath, data) {
9
+ if (rendererCache[templatePath]) {
10
+ return rendererCache[templatePath](data)
11
+ }
12
+ const templateContent = fs.readFileSync(templatePath, 'utf8')
13
+ const renderer = ejs.compile(templateContent)
14
+ rendererCache[templatePath] = renderer
15
+ return renderer(data)
16
+ }
17
+
18
+ function executePlan(ctx) {
19
+ const { plan } = ctx
20
+ for (const step of plan) {
21
+ switch (step.command) {
22
+ case 'copy':
23
+ fs.cpSync(step.input, step.output, { recursive: true })
24
+ break
25
+ case 'render': {
26
+ const { getData, template, output } = step
27
+ const data = getData()
28
+ console.log(data)
29
+ fs.mkdirSync(path.dirname(output), { recursive: true, force: true })
30
+ fs.writeFileSync(output, renderTemplate(template, { ctx: data }))
31
+ break
32
+ }
33
+ }
34
+ }
35
+ return ctx
36
+ }
37
+
38
+ module.exports = executePlan
@@ -0,0 +1,9 @@
1
+ module.exports = function loadSpec(ctx) {
2
+ const { request } = ctx
3
+ const { specPath } = request
4
+ const spec = require(specPath)
5
+ return {
6
+ ...ctx,
7
+ spec,
8
+ }
9
+ }
package/src/main.js ADDED
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+
3
+ const buildIr = require('./build-ir')
4
+ const dispatchBuildPlan = require('./build-plan')
5
+ const buildRequest = require('./build-request')
6
+ const executePlan = require('./execute-plan')
7
+ const loadSpec = require('./load-spec')
8
+ const parseInput = require('./parse-input')
9
+ const prepareOutput = require('./prepare-output')
10
+
11
+ const Pipeline = [
12
+ parseInput,
13
+ buildRequest,
14
+ prepareOutput,
15
+ loadSpec,
16
+ buildIr,
17
+ dispatchBuildPlan,
18
+ executePlan,
19
+ ]
20
+
21
+ function main() {
22
+ return Pipeline.reduce(
23
+ (acc, step) => {
24
+ return step(acc)
25
+ },
26
+ { argv: process.argv }
27
+ )
28
+ }
29
+
30
+ console.log(JSON.stringify(main(), null, 2))
@@ -0,0 +1,49 @@
1
+ const yargs = require('yargs')
2
+ const { hideBin } = require('yargs/helpers')
3
+
4
+ module.exports = function parseInput(ctx) {
5
+ const args = yargs(hideBin(ctx.argv))
6
+ .scriptName('sdkgen')
7
+ .version(false)
8
+ .option('spec', {
9
+ type: 'string',
10
+ description: 'The path to the OpenWS spec file',
11
+ })
12
+ .option('out', {
13
+ type: 'string',
14
+ description: 'The path to the output directory',
15
+ })
16
+ .option('project', {
17
+ type: 'string',
18
+ description: 'The path to the project directory',
19
+ })
20
+ .option('hostRole', {
21
+ type: 'array',
22
+ description: 'The target participant roles that use the generated code',
23
+ })
24
+ .option('language', {
25
+ type: 'string',
26
+ description: 'The language to generate code for',
27
+ choices: ['csharp', 'javascript'],
28
+ default: 'csharp',
29
+ })
30
+ .option('environment', {
31
+ type: 'string',
32
+ description: 'The environments to generate code for',
33
+ choices: ['unity', 'node', 'browser'],
34
+ default: ['unity'],
35
+ })
36
+ .option('frameworks', {
37
+ type: 'array',
38
+ description: 'The frameworks to generate code for',
39
+ choices: ['fastify', 'newtonsoft'],
40
+ })
41
+ .strict()
42
+ .help()
43
+ .parse()
44
+
45
+ return {
46
+ ...ctx,
47
+ rawInput: args,
48
+ }
49
+ }
@@ -0,0 +1,12 @@
1
+ const fs = require('node:fs')
2
+
3
+ // 1. Create / clear output directory
4
+ // 2. Load OpenWS spec
5
+ // 3. Generate plan
6
+ module.exports = function prepareOutput(ctx) {
7
+ const { request } = ctx
8
+ const { outputPath } = request
9
+ fs.rmSync(outputPath, { recursive: true, force: true })
10
+ fs.mkdirSync(outputPath, { recursive: true })
11
+ return ctx
12
+ }