@orthograph/generators 0.0.0-stage → 0.1.0-next.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 (53) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2 -2
  3. package/dist/main.d.ts +5 -0
  4. package/dist/main.js +15 -0
  5. package/dist/modules/adapter/internal/embed.d.ts +3 -0
  6. package/dist/modules/adapter/internal/embed.js +14 -0
  7. package/dist/modules/adapter/internal/emit.d.ts +16 -0
  8. package/dist/modules/adapter/internal/emit.js +81 -0
  9. package/dist/modules/adapter/internal/extract.d.ts +54 -0
  10. package/dist/modules/adapter/internal/extract.js +175 -0
  11. package/dist/modules/adapter/internal/names.d.ts +8 -0
  12. package/dist/modules/adapter/internal/names.js +12 -0
  13. package/dist/modules/adapter/internal/runtime/client.d.ts +61 -0
  14. package/dist/modules/adapter/internal/runtime/client.js +110 -0
  15. package/dist/modules/adapter/internal/runtime/json-schema.d.ts +6 -0
  16. package/dist/modules/adapter/internal/runtime/json-schema.js +111 -0
  17. package/dist/modules/adapter/internal/runtime/types.d.ts +34 -0
  18. package/dist/modules/adapter/internal/runtime/types.js +1 -0
  19. package/dist/modules/adapter/internal/runtime-sources.d.ts +1 -0
  20. package/dist/modules/adapter/internal/runtime-sources.js +7 -0
  21. package/dist/modules/adapter/internal/templates.d.ts +23 -0
  22. package/dist/modules/adapter/internal/templates.js +79 -0
  23. package/dist/modules/adapter/service.d.ts +2 -0
  24. package/dist/modules/adapter/service.js +41 -0
  25. package/dist/modules/adapter/types.d.ts +33 -0
  26. package/dist/modules/adapter/types.js +6 -0
  27. package/dist/modules/portal/internal/main.d.ts +3 -0
  28. package/dist/modules/portal/internal/main.js +21 -0
  29. package/dist/modules/portal/service.d.ts +2 -0
  30. package/dist/modules/portal/service.js +17 -0
  31. package/dist/modules/portal/types.d.ts +14 -0
  32. package/dist/modules/portal/types.js +1 -0
  33. package/dist/modules/render/internal/docs.d.ts +3 -0
  34. package/dist/modules/render/internal/docs.js +78 -0
  35. package/dist/modules/render/internal/examples.d.ts +3 -0
  36. package/dist/modules/render/internal/examples.js +56 -0
  37. package/dist/modules/render/internal/mounted.d.ts +13 -0
  38. package/dist/modules/render/internal/mounted.js +53 -0
  39. package/dist/modules/render/service.d.ts +2 -0
  40. package/dist/modules/render/service.js +21 -0
  41. package/dist/modules/render/types.d.ts +28 -0
  42. package/dist/modules/render/types.js +4 -0
  43. package/dist/modules/sync/internal/files.d.ts +3 -0
  44. package/dist/modules/sync/internal/files.js +9 -0
  45. package/dist/modules/sync/internal/handlers.d.ts +2 -0
  46. package/dist/modules/sync/internal/handlers.js +23 -0
  47. package/dist/modules/sync/internal/model.d.ts +8 -0
  48. package/dist/modules/sync/internal/model.js +10 -0
  49. package/dist/modules/sync/service.d.ts +3 -0
  50. package/dist/modules/sync/service.js +33 -0
  51. package/dist/modules/sync/types.d.ts +16 -0
  52. package/dist/modules/sync/types.js +5 -0
  53. package/package.json +49 -3
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 CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # @orthograph/generators
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Nx plugin: scaffolds and sync generators. Built; what each part does and how far it goes is in the package map in `docs/canon/status.md`.
package/dist/main.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { type Tree } from "@nx/devkit";
2
+ export default function sync(tree: Tree): Promise<{
3
+ outOfSyncMessage: string;
4
+ outOfSyncDetails: string[];
5
+ } | undefined>;
package/dist/main.js ADDED
@@ -0,0 +1,15 @@
1
+ // The Nx sync generator: `nx sync` writes, `nx sync:check` fails on drift. Registered in nx.json `sync.globalGenerators`.
2
+ import { getProjects } from "@nx/devkit";
3
+ import { Effect } from "effect";
4
+ import { Sync } from "#modules/sync/service.js";
5
+ export default async function sync(tree) {
6
+ // An app's blueprint is generated here; a plugin's (its package.json declares `orthograph.kind`) is not an app's, and is
7
+ // judged where an app mounts it.
8
+ const plugin = (root) => tree.exists(`${root}/package.json`) && JSON.parse(tree.read(`${root}/package.json`, "utf-8") ?? "{}").orthograph?.kind !== undefined;
9
+ const roots = [...getProjects(tree).values()].map((p) => p.root).filter((root) => tree.exists(`${root}/blueprint`) && !plugin(root));
10
+ await Effect.runPromise(Effect.forEach(roots, (root) => Sync.project(tree, root), { discard: true }));
11
+ const changed = tree.listChanges().map((c) => `${c.type} ${c.path}`);
12
+ return changed.length === 0
13
+ ? undefined
14
+ : { outOfSyncMessage: "generated/ doesn't match the blueprint. Run nx sync.", outOfSyncDetails: changed };
15
+ }
@@ -0,0 +1,3 @@
1
+ export declare const RUNTIME_NAMES: readonly ["types", "json-schema", "client"];
2
+ /** The text of `runtime-sources.ts` for these sources, one string per runtime file. */
3
+ export declare const embeddedText: (sources: Readonly<Record<(typeof RUNTIME_NAMES)[number], string>>) => string;
@@ -0,0 +1,14 @@
1
+ // The runtime a generated plugin carries lives in `runtime/*.ts`, real code that is type-checked and tested here. `tsc`
2
+ // does not ship a `.ts` file as one, so the generator reads the runtime from `runtime-sources.ts`, which is those files as
3
+ // strings. `scripts/embed-runtime.ts` writes it; a test fails when it is out of date.
4
+ export const RUNTIME_NAMES = ["types", "json-schema", "client"];
5
+ /** The text of `runtime-sources.ts` for these sources, one string per runtime file. */
6
+ export const embeddedText = (sources) => [
7
+ "// Generated from internal/runtime/*.ts by scripts/embed-runtime.ts. Do not edit.",
8
+ "// The generator's runtime files as text, so a built package needs no source folder (internal/embed.ts says why).",
9
+ "",
10
+ "export const RUNTIME: Readonly<Record<string, string>> = {",
11
+ ...RUNTIME_NAMES.map((name) => ` ${JSON.stringify(name)}: ${JSON.stringify(sources[name])},`),
12
+ "};",
13
+ "",
14
+ ].join("\n");
@@ -0,0 +1,16 @@
1
+ import type { Event, Node, Op } from "./extract.ts";
2
+ export declare const generatedLine: (title: string, version: string) => string;
3
+ export declare const operationsFile: (ops: ReadonlyArray<Op>) => string;
4
+ export declare const componentsFile: (components: Readonly<Record<string, Node>>) => string;
5
+ export declare const eventsFile: (events: ReadonlyArray<Event>) => string;
6
+ interface Tree {
7
+ [name: string]: Tree | null;
8
+ }
9
+ /** The calls as nested groups. A name two operations come to, or one that is both a call and a group, has no one place in the tree: it is told to the caller. */
10
+ export declare const treeOf: (ops: ReadonlyArray<Op>) => {
11
+ readonly tree: Tree;
12
+ readonly clashes: ReadonlyArray<string>;
13
+ };
14
+ export declare const indexFile: (head: string, name: string, title: string, version: string, tree: Tree, events: ReadonlyArray<Event>) => string;
15
+ export declare const clientFile: (head: string) => string;
16
+ export {};
@@ -0,0 +1,81 @@
1
+ import { errorsOf } from "./names.js";
2
+ export const generatedLine = (title, version) => `// Generated from ${title} ${version}. Do not edit.`;
3
+ /** A JSON value as one TypeScript expression: a string literal handed to `JSON.parse`. */
4
+ const json = (value, type) => `JSON.parse(${JSON.stringify(JSON.stringify(value))}) as ${type}`;
5
+ const byName = (items) => [...items].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
6
+ const byParts = (ops) => [...ops].sort((a, b) => { const [x, y] = [a.parts.join("."), b.parts.join(".")]; return x < y ? -1 : x > y ? 1 : 0; });
7
+ export const operationsFile = (ops) => [
8
+ `import type { Operation } from "../runtime/types.ts";`, "",
9
+ `export const operations = ${json(byParts(ops).map((o) => ({ name: o.parts, method: o.method, path: o.path, params: o.params, body: o.body, auth: o.auth, successes: o.successes })), "ReadonlyArray<Operation>")};`, "",
10
+ ].join("\n");
11
+ export const componentsFile = (components) => [
12
+ `import type { Components } from "../runtime/types.ts";`, "",
13
+ `export const components = ${json(components, "Components")};`, "",
14
+ ].join("\n");
15
+ export const eventsFile = (events) => [
16
+ `import type { EventPayloads } from "../runtime/types.ts";`, "",
17
+ `export const eventPayloads = ${json(Object.fromEntries(byName(events).map((e) => [e.name, e.payloads])), "EventPayloads")};`, "",
18
+ ].join("\n");
19
+ /** The calls as nested groups. A name two operations come to, or one that is both a call and a group, has no one place in the tree: it is told to the caller. */
20
+ export const treeOf = (ops) => {
21
+ const tree = Object.create(null);
22
+ const clashes = [];
23
+ for (const op of byParts(ops)) {
24
+ let at = tree;
25
+ const path = op.parts.slice(0, -1);
26
+ const last = op.parts[op.parts.length - 1];
27
+ const blocked = path.findIndex((part) => {
28
+ if (at[part] === null)
29
+ return true;
30
+ at = (at[part] ??= Object.create(null));
31
+ return false;
32
+ });
33
+ if (blocked >= 0)
34
+ clashes.push(op.parts.slice(0, blocked + 1).join("."));
35
+ else if (at[last] !== undefined)
36
+ clashes.push(op.parts.join("."));
37
+ else
38
+ at[last] = null;
39
+ }
40
+ return { tree, clashes };
41
+ };
42
+ /** A key as an object literal writes it: `__proto__` must be computed, or it would set the prototype instead of a property. */
43
+ const key = (name) => (name === "__proto__" ? `[${JSON.stringify(name)}]` : JSON.stringify(name));
44
+ const callsText = (tree, indent) => Object.entries(tree).map(([name, sub]) => sub === null
45
+ ? `${indent}${key(name)}: Blueprint.call({ errors }),`
46
+ : `${indent}${key(name)}: {\n${callsText(sub, `${indent} `)}\n${indent}},`).join("\n");
47
+ export const indexFile = (head, name, title, version, tree, events) => [
48
+ head, `import { Blueprint } from "orthograph";`,
49
+ `import { ${errorsOf(name).join(", ")} } from "../blueprint/things/${name}/errors.ts";`,
50
+ ...(events.length === 0 ? [] : [
51
+ `import { schemaOf } from "./runtime/json-schema.ts";`,
52
+ `import { components } from "./spec/components.ts";`,
53
+ `import { eventPayloads } from "./spec/events.ts";`
54
+ ]),
55
+ `import { door, events as written, standIn } from "./written.ts";`, "",
56
+ `export { ${errorsOf(name).join(", ")} };`, "",
57
+ `/** What every call may fail with: the client's four failures, as errors an operation can refuse with. */`,
58
+ `const errors = [${errorsOf(name).join(", ")}];`, "",
59
+ ...(events.length === 0 ? [] : [
60
+ `/** The payload of an event: any one of the payloads its service documents for it. */`,
61
+ `const payload = (event: string) => Blueprint.incoming(schemaOf(components, { oneOf: eventPayloads[event] ?? [] }));`, ""
62
+ ]),
63
+ `export default Blueprint.adapter({`,
64
+ ` description: ${JSON.stringify(`${title} ${version}: every call and event its published description lists.`)},`,
65
+ ` calls: {`, callsText(tree, " "), ` },`,
66
+ ` events: {`, ...byName(events).map((e) => ` ${JSON.stringify(e.name)}: payload(${JSON.stringify(e.name)}),`), ` ...written,`, ` },`,
67
+ ` standIn,`,
68
+ ` ...(door === undefined ? {} : { door }),`,
69
+ `});`, "",
70
+ ].join("\n");
71
+ export const clientFile = (head) => [
72
+ head,
73
+ `import type adapter from "./index.ts";`,
74
+ `import { makeClient, type ClientOptions, type Input } from "./runtime/client.ts";`,
75
+ `import { components } from "./spec/components.ts";`,
76
+ `import { operations } from "./spec/operations.ts";`, "",
77
+ `export { AnswerRefused, ApiFailure, InputRefused, Unreachable, type ClientOptions, type Input } from "./runtime/client.ts";`, "",
78
+ `type Calls<T> = { readonly [K in keyof T]: T[K] extends { readonly kind: "call" } ? (input?: Input) => Promise<unknown> : Calls<T[K]> };`, "",
79
+ `/** \`client({ baseUrl, token? }).calls.<group>.<call>(input)\` is a promise of the answer's JSON, as it came. */`,
80
+ `export const client = (options: ClientOptions): { readonly calls: Calls<typeof adapter.calls> } => makeClient(operations, components, options) as never;`, "",
81
+ ].join("\n");
@@ -0,0 +1,54 @@
1
+ export type Node = {
2
+ readonly [key: string]: any;
3
+ };
4
+ export interface Description {
5
+ readonly raw: Node;
6
+ readonly swagger: boolean;
7
+ }
8
+ export interface Param {
9
+ readonly name: string;
10
+ readonly in: "path" | "query" | "header" | "body";
11
+ readonly required: boolean;
12
+ readonly schema: Node;
13
+ }
14
+ /** How a call sends the client's token: as `Authorization: Bearer`, in the header an `apiKey` scheme names, or not at all (`security: []`). */
15
+ export type Auth = "bearer" | "none" | {
16
+ readonly header: string;
17
+ };
18
+ /** A request body of alternatives (`oneOf` / `anyOf`): its fields are any alternative's, and the input's body is judged against it whole. */
19
+ export interface Body {
20
+ readonly schema: Node;
21
+ readonly required: boolean;
22
+ }
23
+ export interface Op {
24
+ readonly id: string;
25
+ readonly parts: ReadonlyArray<string>;
26
+ readonly method: "get" | "post" | "put" | "patch" | "delete";
27
+ readonly path: string;
28
+ readonly params: ReadonlyArray<Param>;
29
+ readonly body: Body | null;
30
+ readonly auth: Auth;
31
+ /** One per documented 2xx status; a null schema is a status with no body (204). */
32
+ readonly successes: ReadonlyArray<{
33
+ readonly status: number;
34
+ readonly schema: Node | null;
35
+ }>;
36
+ }
37
+ export interface Event {
38
+ readonly name: string;
39
+ readonly payloads: ReadonlyArray<Node>;
40
+ }
41
+ /** Follows `$ref`s to the node they name. */
42
+ export declare const deref: (d: Description, node: Node | undefined) => Node;
43
+ /**
44
+ * Whether the description requires a key: a requirement naming a scheme, in its own `security` or any operation's
45
+ * (G16-adapter-mounts call 1). A scheme no requirement names, or only the anonymous `[{}]`, requires none; a key made
46
+ * optional (`[{}, { bearer: [] }]`) still does.
47
+ */
48
+ export declare const requiresKey: (d: Description) => boolean;
49
+ /** Every operation, in the description's order, named by its `operationId` or else by its method and path. */
50
+ export declare const operationsOf: (d: Description) => ReadonlyArray<Op>;
51
+ /** A webhook event is what GitHub calls one (`x-github.subcategory`); its payload is any one of the actions the description lists for it. */
52
+ export declare const eventsOf: (d: Description) => ReadonlyArray<Event>;
53
+ /** Every schema the given ones refer to, by the `$ref` string the description writes, followed through each other. */
54
+ export declare const componentsOf: (d: Description, roots: ReadonlyArray<Node>) => Readonly<Record<string, Node>>;
@@ -0,0 +1,175 @@
1
+ // What a description says, read out of it: its operations (each with the fields a caller supplies, how its token is sent
2
+ // and its success schema), its webhook events, and the schemas they refer to.
3
+ import { camel, nameParts } from "./names.js";
4
+ const METHODS = ["get", "post", "put", "patch", "delete"];
5
+ /** What a parameter says about its own value, as a schema: the rest of its node is about the parameter. */
6
+ const ABOUT_THE_PARAMETER = new Set(["name", "in", "required", "description", "example", "examples", "allowEmptyValue", "collectionFormat", "style", "explode", "deprecated", "x-codeSamples"]);
7
+ const pointer = (raw, ref) => ref.replace(/^#\//, "").split("/").reduce((at, part) => at?.[part.replace(/~1/g, "/").replace(/~0/g, "~")], raw);
8
+ /** Follows `$ref`s to the node they name. */
9
+ export const deref = (d, node) => {
10
+ let at = node;
11
+ for (let hops = 0; at !== undefined && typeof at["$ref"] === "string" && hops < 50; hops += 1)
12
+ at = pointer(d.raw, at["$ref"]);
13
+ return at ?? {};
14
+ };
15
+ /** An object schema's properties, with an `allOf`'s parts merged in. */
16
+ const fieldsOf = (d, schema, seen = 0) => {
17
+ const node = deref(d, schema);
18
+ const parts = seen < 8 && Array.isArray(node["allOf"]) ? node["allOf"].map((p) => fieldsOf(d, p, seen + 1)) : [];
19
+ return {
20
+ properties: Object.assign({}, ...parts.map((p) => p.properties), node["properties"] ?? {}),
21
+ required: [...parts.flatMap((p) => p.required), ...(node["required"] ?? [])],
22
+ };
23
+ };
24
+ /** The header a call's caller may give, else the client makes a fresh one: so it is never required. */
25
+ const IDEMPOTENCY_KEY = /^idempotency-key$/i;
26
+ /**
27
+ * A body schema's fields. Of alternatives (`oneOf` / `anyOf`), every field any of them or the schema itself has, none required and each
28
+ * judged only with the whole body (one alternative's `type: individual` is another's misfit); otherwise its properties.
29
+ */
30
+ const bodyOf = (d, schema, required) => {
31
+ const node = deref(d, schema);
32
+ const alternatives = (node["oneOf"] ?? node["anyOf"]);
33
+ if (Array.isArray(alternatives)) {
34
+ // the schema's own fields (its properties, an allOf's) are common to every alternative
35
+ const names = [...new Set([node, ...alternatives].flatMap((a) => Object.keys(fieldsOf(d, a).properties)))];
36
+ return { fields: names.map((name) => ({ name, in: "body", required: false, schema: {} })), body: { schema, required } };
37
+ }
38
+ const { properties, required: needed } = fieldsOf(d, schema);
39
+ return { fields: Object.entries(properties).map(([name, s]) => ({ name, in: "body", required: needed.includes(name), schema: s })), body: null };
40
+ };
41
+ const paramsOf = (d, item, op, auth) => {
42
+ const found = [];
43
+ let body = null;
44
+ const take = (b) => { found.push(...b.fields); body = b.body ?? body; };
45
+ const credential = auth === "none" ? undefined : auth === "bearer" ? "authorization" : auth.header.toLowerCase();
46
+ for (const p of [...(item["parameters"] ?? []), ...(op["parameters"] ?? [])].map((x) => deref(d, x))) {
47
+ // the token is the client's credential, never a field (Slack declares it as a header)
48
+ // (a path parameter that happens to be called `token` is a field like any other)
49
+ // and so is a header the spec also declares where the credential goes (`Authorization`, an apiKey's own)
50
+ if ((p["name"] === "token" && p["in"] !== "path") || p["in"] === "cookie" || (p["in"] === "header" && String(p["name"]).toLowerCase() === credential))
51
+ continue;
52
+ if (p["in"] === "body")
53
+ take(bodyOf(d, p["schema"] ?? {}, p["required"] === true));
54
+ else {
55
+ const where = p["in"] === "formData" ? "body" : p["in"];
56
+ const schema = p["schema"] ?? Object.fromEntries(Object.entries(p).filter(([k]) => !ABOUT_THE_PARAMETER.has(k)));
57
+ const name = String(p["name"]);
58
+ const required = (p["required"] === true || where === "path") && !(where === "header" && IDEMPOTENCY_KEY.test(name));
59
+ found.push({ name, in: where, required, schema });
60
+ }
61
+ }
62
+ const requestBody = op["requestBody"] === undefined ? undefined : deref(d, op["requestBody"]);
63
+ const schema = requestBody?.["content"]?.["application/json"]?.["schema"];
64
+ if (schema !== undefined)
65
+ take(bodyOf(d, schema, requestBody?.["required"] === true));
66
+ // an operation's own parameter overrides the path item's of the same name and place
67
+ const merged = [];
68
+ for (const p of found) {
69
+ const at = merged.findIndex((q) => q.name === p.name && q.in === p.in);
70
+ if (at >= 0)
71
+ merged[at] = p;
72
+ else
73
+ merged.push(p);
74
+ }
75
+ return { params: merged, body };
76
+ };
77
+ /**
78
+ * The operation's security, else the document's. An `apiKey` scheme `in: header` (OpenAPI's `securitySchemes`, Swagger's
79
+ * `securityDefinitions`) names the header; `[]` sends no credential; any other scheme, or none declared, is a bearer.
80
+ */
81
+ const authOf = (d, op) => {
82
+ const security = op["security"] ?? d.raw["security"];
83
+ if (!Array.isArray(security))
84
+ return "bearer";
85
+ const first = security.find((r) => typeof r === "object" && r !== null && Object.keys(r).length > 0);
86
+ if (first === undefined)
87
+ return "none";
88
+ const schemes = (d.swagger ? d.raw["securityDefinitions"] : d.raw["components"]?.["securitySchemes"]) ?? {};
89
+ const scheme = deref(d, schemes[Object.keys(first)[0]]);
90
+ return scheme["type"] === "apiKey" && scheme["in"] === "header" && typeof scheme["name"] === "string" ? { header: scheme["name"] } : "bearer";
91
+ };
92
+ /**
93
+ * Whether the description requires a key: a requirement naming a scheme, in its own `security` or any operation's
94
+ * (G16-adapter-mounts call 1). A scheme no requirement names, or only the anonymous `[{}]`, requires none; a key made
95
+ * optional (`[{}, { bearer: [] }]`) still does.
96
+ */
97
+ export const requiresKey = (d) => {
98
+ const names = (security) => Array.isArray(security) && security.some((r) => typeof r === "object" && r !== null && Object.keys(r).length > 0);
99
+ return names(d.raw["security"]) || Object.values(d.raw["paths"] ?? {}).some((item) => METHODS.some((m) => names(item?.[m]?.["security"])));
100
+ };
101
+ /** The method's word on a collection (the path ends in a fixed part) and on an item (it ends in a `{parameter}`). */
102
+ const WORDS = {
103
+ collection: { get: "list", post: "create", put: "update", patch: "update", delete: "delete" },
104
+ item: { get: "get", post: "create", put: "update", patch: "update", delete: "delete" },
105
+ };
106
+ /** A call with no `operationId`: its path's fixed parts, camel-cased, then its method's word (`GET /widgets/{id}/spare_parts` is `widgets.spareParts.list`). */
107
+ const pathName = (method, path) => {
108
+ const parts = path.split("/").filter((p) => p !== "");
109
+ const onItem = (parts[parts.length - 1] ?? "").includes("{");
110
+ return [...parts.filter((p) => !p.includes("{")).map(camel), WORDS[onItem ? "item" : "collection"][method]];
111
+ };
112
+ /** Every operation, in the description's order, named by its `operationId` or else by its method and path. */
113
+ export const operationsOf = (d) => {
114
+ const base = d.swagger ? String(d.raw["basePath"] ?? "").replace(/\/$/, "") : "";
115
+ const found = [];
116
+ for (const [path, item] of Object.entries(d.raw["paths"] ?? {})) {
117
+ for (const method of METHODS) {
118
+ const op = item[method];
119
+ if (op === undefined)
120
+ continue;
121
+ const statuses = Object.keys(op["responses"] ?? {}).map(Number).filter((s) => s >= 200 && s < 300).sort((a, b) => a - b);
122
+ const successes = statuses.map((status) => {
123
+ const response = deref(d, op["responses"][String(status)]);
124
+ const schema = d.swagger ? response["schema"] : response["content"]?.["application/json"]?.["schema"];
125
+ return { status, schema: schema ?? null };
126
+ });
127
+ const id = op["operationId"];
128
+ const auth = authOf(d, op);
129
+ found.push({
130
+ id: typeof id === "string" ? id : `${method.toUpperCase()} ${path}`,
131
+ parts: typeof id === "string" ? nameParts(id) : pathName(method, path),
132
+ method, path: base + path, ...paramsOf(d, item, op, auth), auth, successes,
133
+ });
134
+ }
135
+ }
136
+ return found;
137
+ };
138
+ /** A webhook event is what GitHub calls one (`x-github.subcategory`); its payload is any one of the actions the description lists for it. */
139
+ export const eventsOf = (d) => {
140
+ const byEvent = new Map();
141
+ for (const item of Object.values(d.raw["webhooks"] ?? {})) {
142
+ const schema = item["post"]?.["requestBody"]?.["content"]?.["application/json"]?.["schema"];
143
+ const event = item["post"]?.["x-github"]?.["subcategory"];
144
+ if (schema !== undefined && event !== undefined)
145
+ byEvent.set(event, [...(byEvent.get(event) ?? []), schema]);
146
+ }
147
+ return [...byEvent].map(([key, payloads]) => ({ name: camel(key), payloads }));
148
+ };
149
+ /** Every schema the given ones refer to, by the `$ref` string the description writes, followed through each other. */
150
+ export const componentsOf = (d, roots) => {
151
+ const table = {};
152
+ const visit = (node) => {
153
+ if (Array.isArray(node)) {
154
+ for (const n of node)
155
+ visit(n);
156
+ return;
157
+ }
158
+ if (typeof node !== "object" || node === null)
159
+ return;
160
+ for (const [key, value] of Object.entries(node)) {
161
+ if (key === "$ref" && typeof value === "string") {
162
+ const target = table[value] === undefined ? pointer(d.raw, value) : undefined;
163
+ if (target !== undefined) {
164
+ table[value] = target;
165
+ visit(target);
166
+ }
167
+ }
168
+ else
169
+ visit(value);
170
+ }
171
+ };
172
+ for (const root of roots)
173
+ visit(root);
174
+ return Object.fromEntries(Object.entries(table).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
175
+ };
@@ -0,0 +1,8 @@
1
+ export declare const camel: (word: string) => string;
2
+ export declare const nameParts: (operationId: string) => ReadonlyArray<string>;
3
+ /** Lower case words joined by dashes: `github`, `error-tracking`. */
4
+ export declare const isName: (name: string) => boolean;
5
+ /** An adapter's name in Pascal case, its errors' prefix: `fx-rates` is `FxRates`. */
6
+ export declare const pascalOf: (name: string) => string;
7
+ /** The four errors every call of a generated adapter declares (G16-adapter-mounts call 1), in the adapter's name. */
8
+ export declare const errorsOf: (name: string) => ReadonlyArray<string>;
@@ -0,0 +1,12 @@
1
+ // The one naming rule: a call is named from its `operationId`, split at `/` and `.` into groups, each piece camel-cased at
2
+ // `-` and `_` (`issues/create-comment` is `issues.createComment`; `chat_postMessage` is the flat `chatPostMessage`). An
3
+ // event is the service's own event name, camel-cased the same way (`issue_comment` is `issueComment`).
4
+ export const camel = (word) => word.split(/[-_]/).filter((p) => p !== "")
5
+ .map((p, i) => (i === 0 ? p.charAt(0).toLowerCase() + p.slice(1) : p.charAt(0).toUpperCase() + p.slice(1))).join("");
6
+ export const nameParts = (operationId) => operationId.split(/[/.]/).map(camel);
7
+ /** Lower case words joined by dashes: `github`, `error-tracking`. */
8
+ export const isName = (name) => /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(name);
9
+ /** An adapter's name in Pascal case, its errors' prefix: `fx-rates` is `FxRates`. */
10
+ export const pascalOf = (name) => name.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
11
+ /** The four errors every call of a generated adapter declares (G16-adapter-mounts call 1), in the adapter's name. */
12
+ export const errorsOf = (name) => ["ApiFailure", "InputRefused", "AnswerRefused", "Unreachable"].map((e) => `${pascalOf(name)}${e}`);