@typespec/http-client-js 0.16.2-dev.1 → 0.16.2-dev.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 (225) hide show
  1. package/dist/tsconfig.tsbuildinfo +1 -1
  2. package/package.json +13 -9
  3. package/.github/copilot-instructions.md +0 -180
  4. package/.testignore +0 -19
  5. package/.turbo/turbo-build.log +0 -3
  6. package/CHANGELOG.md +0 -159
  7. package/eng/scripts/calculate-coverage.ts +0 -33
  8. package/eng/scripts/emit-e2e.ts +0 -317
  9. package/eng/scripts/run-e2e-tests.ts +0 -166
  10. package/eng/scripts/tspconfig.yaml +0 -6
  11. package/eng/scripts/upload-spector-results.ts +0 -139
  12. package/src/components/client-context/client-context-declaration.tsx +0 -26
  13. package/src/components/client-context/client-context-factory.tsx +0 -218
  14. package/src/components/client-context/client-context-options.tsx +0 -36
  15. package/src/components/client-context/client-context.tsx +0 -23
  16. package/src/components/client-context/parametrized-endpoint.tsx +0 -51
  17. package/src/components/client-directory.tsx +0 -51
  18. package/src/components/client-operation.tsx +0 -102
  19. package/src/components/client.tsx +0 -177
  20. package/src/components/encoding-provider.tsx +0 -17
  21. package/src/components/external-packages/ts-http-runtime.ts +0 -28
  22. package/src/components/external-packages/uri-template.ts +0 -11
  23. package/src/components/http-request-options.tsx +0 -88
  24. package/src/components/http-request-parameters-expression.tsx +0 -191
  25. package/src/components/http-request.tsx +0 -80
  26. package/src/components/http-response.tsx +0 -74
  27. package/src/components/index.ts +0 -12
  28. package/src/components/models.tsx +0 -26
  29. package/src/components/operation-handlers/index.tsx +0 -2
  30. package/src/components/operation-handlers/operation-pipeline.tsx +0 -33
  31. package/src/components/operation-handlers/paging/page-item.tsx +0 -14
  32. package/src/components/operation-handlers/paging/page-response.tsx +0 -57
  33. package/src/components/operation-handlers/paging/page-settings.tsx +0 -53
  34. package/src/components/operation-handlers/paging/paginated-operation-handler.tsx +0 -200
  35. package/src/components/operation-handlers/paging/request-send.tsx +0 -85
  36. package/src/components/operation-handlers/paging/response-deserialize.tsx +0 -60
  37. package/src/components/operation-handlers/paging/util.ts +0 -70
  38. package/src/components/operation-handlers/types.tsx +0 -18
  39. package/src/components/operation-options.tsx +0 -42
  40. package/src/components/operation-parameters.tsx +0 -44
  41. package/src/components/output.tsx +0 -32
  42. package/src/components/serializers.tsx +0 -74
  43. package/src/components/static-helpers/bytes-encoding.tsx +0 -61
  44. package/src/components/static-helpers/interfaces.tsx +0 -31
  45. package/src/components/static-helpers/multipart-helpers.tsx +0 -80
  46. package/src/components/static-helpers/paging-helper.tsx +0 -202
  47. package/src/components/static-helpers/rest-error.tsx +0 -102
  48. package/src/components/testing/client-options.tsx +0 -30
  49. package/src/components/transforms/content-type-encoding-provider.tsx +0 -26
  50. package/src/components/transforms/data-transform.tsx +0 -40
  51. package/src/components/transforms/json/json-array-transform.tsx +0 -87
  52. package/src/components/transforms/json/json-model-additional-properties-transform.tsx +0 -54
  53. package/src/components/transforms/json/json-model-base-transform.tsx +0 -24
  54. package/src/components/transforms/json/json-model-property-transform.tsx +0 -53
  55. package/src/components/transforms/json/json-model-transform.tsx +0 -115
  56. package/src/components/transforms/json/json-record-transform.tsx +0 -88
  57. package/src/components/transforms/json/json-transform-discriminator.tsx +0 -111
  58. package/src/components/transforms/json/json-transform.tsx +0 -120
  59. package/src/components/transforms/json/union-transform.tsx +0 -87
  60. package/src/components/transforms/json/utils/transport-namer.ts +0 -12
  61. package/src/components/transforms/multipart/array-part-transform.tsx +0 -44
  62. package/src/components/transforms/multipart/file-part-transform.tsx +0 -45
  63. package/src/components/transforms/multipart/multipart-transform.tsx +0 -30
  64. package/src/components/transforms/multipart/part-transform.tsx +0 -22
  65. package/src/components/transforms/multipart/simple-part-transform.tsx +0 -42
  66. package/src/components/transforms/operation-transform-declaration.tsx +0 -83
  67. package/src/components/transforms/operation-transform-expression.tsx +0 -62
  68. package/src/components/transforms/scalar-transform.tsx +0 -301
  69. package/src/components/transforms/transform-name-policy.ts +0 -134
  70. package/src/components/utils/unpack-model-property.ts +0 -44
  71. package/src/components/utils/url-template.tsx +0 -25
  72. package/src/context/encoding/encoding-context.tsx +0 -28
  73. package/src/context/encoding/types.ts +0 -6
  74. package/src/emitter.tsx +0 -85
  75. package/src/index.ts +0 -5
  76. package/src/lib.ts +0 -120
  77. package/src/testing/index.ts +0 -11
  78. package/src/utils/client-discovery.ts +0 -28
  79. package/src/utils/multipart.ts +0 -29
  80. package/src/utils/operations.ts +0 -112
  81. package/src/utils/parameters.tsx +0 -155
  82. package/test/e2e/assets/image.jpg +0 -0
  83. package/test/e2e/assets/image.png +0 -0
  84. package/test/e2e/http/authentication/api-key/main.test.ts +0 -38
  85. package/test/e2e/http/authentication/oauth2/main.test.ts +0 -31
  86. package/test/e2e/http/authentication/union/main.test.ts +0 -26
  87. package/test/e2e/http/encode/bytes/main.test.ts +0 -191
  88. package/test/e2e/http/encode/datetime/main.test.ts +0 -176
  89. package/test/e2e/http/encode/duration/main.test.ts +0 -126
  90. package/test/e2e/http/encode/numeric/main.test.ts +0 -26
  91. package/test/e2e/http/parameters/basic/main.test.ts +0 -35
  92. package/test/e2e/http/parameters/body-optionality/main.test.ts +0 -43
  93. package/test/e2e/http/parameters/collection-format/main.test.ts +0 -40
  94. package/test/e2e/http/parameters/spread/main.test.ts +0 -56
  95. package/test/e2e/http/payload/content-negotiation/main.test.ts +0 -40
  96. package/test/e2e/http/payload/json-merge-patch/main.test.ts +0 -122
  97. package/test/e2e/http/payload/media-type/main.test.ts +0 -28
  98. package/test/e2e/http/payload/multipart/main.test.ts +0 -200
  99. package/test/e2e/http/payload/pageable/main.test.ts +0 -78
  100. package/test/e2e/http/payload/xml/main.test.ts +0 -287
  101. package/test/e2e/http/routes/main.test.ts +0 -284
  102. package/test/e2e/http/serialization/encoded-name/json/main.test.ts +0 -20
  103. package/test/e2e/http/server/endpoint/not-defined/main.test.ts +0 -11
  104. package/test/e2e/http/server/path/multiple/main.test.ts +0 -22
  105. package/test/e2e/http/server/path/single/main.test.ts +0 -11
  106. package/test/e2e/http/server/versions/not-versioned/main.test.ts +0 -22
  107. package/test/e2e/http/server/versions/versioned/main.test.ts +0 -28
  108. package/test/e2e/http/special-headers/conditional-request/main.test.ts +0 -35
  109. package/test/e2e/http/special-headers/repeatability/main.test.ts +0 -18
  110. package/test/e2e/http/special-words/main.test.ts +0 -434
  111. package/test/e2e/http/type/array/array.test.ts +0 -256
  112. package/test/e2e/http/type/dictionary/main.test.ts +0 -229
  113. package/test/e2e/http/type/enum/extensible/main.test.ts +0 -34
  114. package/test/e2e/http/type/enum/fixed/main.test.ts +0 -29
  115. package/test/e2e/http/type/model/empty/main.test.ts +0 -21
  116. package/test/e2e/http/type/model/inheritance/enum-discriminator/main.test.ts +0 -51
  117. package/test/e2e/http/type/model/inheritance/nested-discriminator/main.test.ts +0 -168
  118. package/test/e2e/http/type/model/inheritance/not-discriminated/main.test.ts +0 -42
  119. package/test/e2e/http/type/model/inheritance/recursive/main.test.ts +0 -46
  120. package/test/e2e/http/type/model/inheritance/single-discriminator/main.test.ts +0 -99
  121. package/test/e2e/http/type/model/visibility/main.test.ts +0 -64
  122. package/test/e2e/http/type/property/additional-properties/main.test.ts +0 -185
  123. package/test/e2e/http/type/property/additional-properties/spreads.test.ts +0 -448
  124. package/test/e2e/http/type/property/nullable/main.test.ts +0 -275
  125. package/test/e2e/http/type/property/optionality/main.test.ts +0 -256
  126. package/test/e2e/http/type/property/value-types/main.test.ts +0 -193
  127. package/test/e2e/http/type/scalar/main.test.ts +0 -133
  128. package/test/e2e/http/type/scalar/scalar.test.ts +0 -95
  129. package/test/e2e/http/type/union/main.test.ts +0 -207
  130. package/test/e2e/http/versioning/added/main.test.ts +0 -60
  131. package/test/e2e/http/versioning/madeOptional/main.test.ts +0 -34
  132. package/test/e2e/http/versioning/removed/main.test.ts +0 -75
  133. package/test/e2e/http/versioning/renamedFrom/main.test.ts +0 -52
  134. package/test/e2e/http/versioning/returnTypeChangedFrom/main.test.ts +0 -22
  135. package/test/e2e/http/versioning/typeChangedFrom/main.test.ts +0 -31
  136. package/test/scenarios/additional-properties/extends.md +0 -67
  137. package/test/scenarios/additional-properties/is.md +0 -42
  138. package/test/scenarios/additional-properties/spread.md +0 -68
  139. package/test/scenarios/auth/basic_auth.md +0 -68
  140. package/test/scenarios/auth/bearer.md +0 -68
  141. package/test/scenarios/auth/client_parameters.md +0 -78
  142. package/test/scenarios/auth/client_structure.md +0 -36
  143. package/test/scenarios/auth/key_credential.md +0 -69
  144. package/test/scenarios/auth/oauth2.md +0 -90
  145. package/test/scenarios/auth/sub_client_override.md +0 -114
  146. package/test/scenarios/client/client_context.md +0 -34
  147. package/test/scenarios/client/dotted_namespace.md +0 -27
  148. package/test/scenarios/client/global_namespace.md +0 -69
  149. package/test/scenarios/client/multiple_top_level_clients.md +0 -72
  150. package/test/scenarios/client/nested_client.md +0 -102
  151. package/test/scenarios/client/wrapping_namespace.md +0 -41
  152. package/test/scenarios/encoding/bytes_body.md +0 -44
  153. package/test/scenarios/encoding/bytes_json_property.md +0 -55
  154. package/test/scenarios/encoding/bytes_nullable.md +0 -139
  155. package/test/scenarios/encoding/header_bytes.md +0 -130
  156. package/test/scenarios/encoding/header_date.md +0 -216
  157. package/test/scenarios/encoding/model_with_bytes_property.md +0 -45
  158. package/test/scenarios/encoding/query_bytes.md +0 -42
  159. package/test/scenarios/encoding/query_date.md +0 -216
  160. package/test/scenarios/http-operations/basic-request.md +0 -144
  161. package/test/scenarios/http-operations/basic-response.md +0 -219
  162. package/test/scenarios/http-operations/basic.md +0 -128
  163. package/test/scenarios/http-operations/constant-header.md +0 -33
  164. package/test/scenarios/http-operations/create-operation.md +0 -58
  165. package/test/scenarios/http-operations/on_response.md +0 -52
  166. package/test/scenarios/http-operations/optional-request-body.md +0 -50
  167. package/test/scenarios/http-operations/paging.md +0 -242
  168. package/test/scenarios/http-operations/path-parameter-in-model.md +0 -53
  169. package/test/scenarios/http-operations/path-parameter.md +0 -48
  170. package/test/scenarios/http-operations/query-parameter.md +0 -41
  171. package/test/scenarios/http-operations/scalar-payload.md +0 -57
  172. package/test/scenarios/http-operations/with-parameters.md +0 -78
  173. package/test/scenarios/models/array-properties.md +0 -47
  174. package/test/scenarios/models/basic.md +0 -118
  175. package/test/scenarios/models/dictionary-properties.md +0 -44
  176. package/test/scenarios/models/inheritance_2_discriminators.md +0 -346
  177. package/test/scenarios/models/inheritance_discriminator.md +0 -88
  178. package/test/scenarios/models/inline-models.md +0 -29
  179. package/test/scenarios/models/model_additional_properties.md +0 -75
  180. package/test/scenarios/models/model_extends.md +0 -97
  181. package/test/scenarios/models/model_spread.md +0 -63
  182. package/test/scenarios/models/nested_property.md +0 -41
  183. package/test/scenarios/models/property_references_property.md +0 -150
  184. package/test/scenarios/multipart/anonymous_part.md +0 -53
  185. package/test/scenarios/multipart/file.md +0 -154
  186. package/test/scenarios/multipart/file_content_type.md +0 -92
  187. package/test/scenarios/multipart/non-string-float.md +0 -55
  188. package/test/scenarios/multipart/simple_part.md +0 -65
  189. package/test/scenarios/operation-parameters/body_root_anonymous.md +0 -87
  190. package/test/scenarios/operation-parameters/constant_as_optional.md +0 -54
  191. package/test/scenarios/operation-parameters/default_value_as_optional.md +0 -54
  192. package/test/scenarios/operation-parameters/no_content_type.md +0 -62
  193. package/test/scenarios/operation-parameters/no_parameters.md +0 -50
  194. package/test/scenarios/operation-parameters/only_optional.md +0 -62
  195. package/test/scenarios/operation-parameters/only_required.md +0 -58
  196. package/test/scenarios/operation-parameters/reserved_names.md +0 -60
  197. package/test/scenarios/operation-parameters/spread_body.md +0 -70
  198. package/test/scenarios/operation-parameters/spread_with_nested.md +0 -82
  199. package/test/scenarios/operation-parameters/union_body.md +0 -86
  200. package/test/scenarios/operation-parameters/with_body_property.md +0 -67
  201. package/test/scenarios/operation-parameters/with_body_root.md +0 -69
  202. package/test/scenarios/serializers/arrays.md +0 -191
  203. package/test/scenarios/serializers/basic_model.md +0 -111
  204. package/test/scenarios/serializers/basic_model_wire_name.md +0 -48
  205. package/test/scenarios/serializers/discriminated_union.md +0 -86
  206. package/test/scenarios/serializers/discriminated_union_spread.md +0 -115
  207. package/test/scenarios/serializers/file.md +0 -67
  208. package/test/scenarios/serializers/model_date_time.md +0 -65
  209. package/test/scenarios/serializers/multipart.md +0 -62
  210. package/test/scenarios/serializers/polymorphic_single_level_inheritance.md +0 -157
  211. package/test/scenarios/serializers/property_references_property.md +0 -72
  212. package/test/scenarios/serializers/record.md +0 -97
  213. package/test/scenarios/serializers/scalars.md +0 -34
  214. package/test/scenarios/serializers/spread.md +0 -69
  215. package/test/scenarios/serializers/string_union.md +0 -55
  216. package/test/scenarios/server/default_url.md +0 -45
  217. package/test/scenarios/server/multiple-parameters.md +0 -55
  218. package/test/scenarios/server/no-server.md +0 -37
  219. package/test/scenarios/server/parametrized-endpoint.md +0 -51
  220. package/test/scenarios.test.ts +0 -24
  221. package/test/test-host.ts +0 -22
  222. package/tsconfig.json +0 -16
  223. package/tsconfig.test.json +0 -9
  224. package/vitest.config.e2e.ts +0 -16
  225. package/vitest.config.ts +0 -15
@@ -1,317 +0,0 @@
1
- #!/usr/bin/env node
2
- /* eslint-disable no-console */
3
- import { select } from "@inquirer/prompts";
4
- import { execa } from "execa";
5
- import { access, copyFile, glob, mkdir, readFile, rm, stat, writeFile } from "fs/promises";
6
- import ora from "ora";
7
- import pLimit from "p-limit";
8
- import { basename, dirname, join, resolve } from "path";
9
- import pc from "picocolors";
10
- import { hideBin } from "yargs/helpers";
11
- import yargs from "yargs/yargs";
12
-
13
- async function pathExists(path) {
14
- return access(path).then(
15
- () => true,
16
- () => false,
17
- );
18
- }
19
-
20
- const projectRoot = join(import.meta.dirname, "../..");
21
- const tspConfig = join(import.meta.dirname, "tspconfig.yaml");
22
-
23
- const basePath = join(projectRoot, "node_modules", "@typespec", "http-specs", "specs");
24
- const ignoreFilePath = join(projectRoot, ".testignore");
25
- const logDirRoot = join(projectRoot, "temp", "emit-e2e-logs");
26
- const reportFilePath = join(logDirRoot, "report.txt");
27
-
28
- // Remove the log directory if it exists.
29
- async function clearLogDirectory() {
30
- if (await pathExists(logDirRoot)) {
31
- await rm(logDirRoot, { recursive: true, force: true });
32
- }
33
- }
34
-
35
- // Parse command-line arguments.
36
- const argv = yargs(hideBin(process.argv))
37
- .option("main-only", {
38
- type: "boolean",
39
- describe: "Use only main.tsp, even if client.tsp is found",
40
- default: false,
41
- })
42
- .option("interactive", {
43
- type: "boolean",
44
- describe: "Enable interactive mode",
45
- default: false,
46
- })
47
- .positional("paths", {
48
- describe: "Optional list of specific file or directory paths to process (relative to basePath)",
49
- type: "string",
50
- array: true,
51
- default: [],
52
- })
53
- .option("build", {
54
- type: "boolean",
55
- describe: "Build the generated projects",
56
- default: false,
57
- })
58
- .help().argv;
59
-
60
- // Read and parse the ignore file.
61
- async function getIgnoreList() {
62
- try {
63
- const content = await readFile(ignoreFilePath, "utf8");
64
- return content
65
- .split(/\r?\n/)
66
- .filter((line) => line.trim() && !line.startsWith("#"))
67
- .map((line) => line.trim());
68
- } catch {
69
- console.warn(pc.yellow("No ignore file found."));
70
- return [];
71
- }
72
- }
73
-
74
- // Recursively process paths (files or directories relative to basePath).
75
- async function processPaths(paths, ignoreList, mainOnly) {
76
- const results = [];
77
- for (const relativePath of paths) {
78
- const fullPath = resolve(basePath, relativePath);
79
-
80
- if (!(await pathExists(fullPath))) {
81
- console.warn(pc.yellow(`Path not found: ${relativePath}`));
82
- continue;
83
- }
84
-
85
- const stats = await stat(fullPath);
86
- if (stats.isFile() && (fullPath.endsWith("client.tsp") || fullPath.endsWith("main.tsp"))) {
87
- if (ignoreList.some((ignore) => relativePath.startsWith(ignore))) continue;
88
- results.push({ fullPath, relativePath });
89
- } else if (stats.isDirectory()) {
90
- const patterns = mainOnly ? ["**/main.tsp"] : ["**/client.tsp", "**/main.tsp"];
91
- const discoveredPaths = [];
92
- for await (const p of glob(patterns, { cwd: fullPath })) {
93
- discoveredPaths.push(p);
94
- }
95
- const validFiles = discoveredPaths
96
- .map((p) => ({
97
- fullPath: join(fullPath, p),
98
- relativePath: join(relativePath, p),
99
- }))
100
- .filter((file) => !ignoreList.some((ignore) => file.relativePath.startsWith(ignore)));
101
- results.push(...validFiles);
102
- } else {
103
- console.warn(pc.yellow(`Skipping unsupported path: ${relativePath}`));
104
- }
105
- }
106
-
107
- // Deduplicate and prioritize client.tsp over main.tsp.
108
- const filesByDir = new Map();
109
- for (const file of results) {
110
- const dir = dirname(file.relativePath);
111
- const existing = filesByDir.get(dir);
112
- if (!existing || (!mainOnly && file.relativePath.endsWith("client.tsp"))) {
113
- filesByDir.set(dir, file);
114
- }
115
- }
116
- return Array.from(filesByDir.values());
117
- }
118
-
119
- // Run a shell command silently.
120
- async function runCommand(command, args, options = {}) {
121
- // Remove clutter by not printing anything; capture output by setting stdio to 'pipe'.
122
- return await execa(command, args, {
123
- stdio: "pipe",
124
- env: { NODE_ENV: "test", TYPESPEC_JS_EMITTER_TESTING: "true", ...process.env },
125
- ...options,
126
- });
127
- }
128
-
129
- // Process a single file.
130
- async function processFile(file, options) {
131
- const { fullPath, relativePath } = file;
132
- const { build, interactive } = options;
133
- const outputDir = join("test", "e2e", "generated", dirname(relativePath));
134
- const specCopyPath = join(outputDir, "spec.tsp");
135
- const logDir = join(projectRoot, "temp", "emit-e2e-logs", dirname(relativePath));
136
-
137
- let spinner;
138
- if (interactive) {
139
- spinner = ora({ text: `Processing: ${relativePath}`, color: "cyan" }).start();
140
- }
141
-
142
- try {
143
- if (await pathExists(outputDir)) {
144
- if (spinner) spinner.text = `Clearing directory: ${outputDir}`;
145
- await rm(outputDir, { recursive: true, force: true });
146
- }
147
- if (spinner) spinner.text = `Creating directory: ${outputDir}`;
148
- await mkdir(outputDir, { recursive: true });
149
-
150
- if (spinner) spinner.text = `Copying spec to: ${specCopyPath}`;
151
- await copyFile(fullPath, specCopyPath);
152
-
153
- if (spinner) spinner.text = `Compiling: ${relativePath}`;
154
- await runCommand("npx", [
155
- "tsp",
156
- "compile",
157
- fullPath,
158
- "--emit",
159
- resolve(import.meta.dirname, "../.."),
160
- "--config",
161
- tspConfig,
162
- "--output-dir",
163
- outputDir,
164
- ]);
165
-
166
- if (spinner) spinner.text = `Formatting with Prettier: ${relativePath}`;
167
- await runCommand("npx", ["prettier", outputDir, "--write"]);
168
-
169
- if (build) {
170
- if (spinner) spinner.text = `Building project: ${relativePath}`;
171
- await runCommand("npm", ["run", "build"], { cwd: outputDir });
172
- }
173
-
174
- if (spinner) {
175
- spinner.succeed(`Finished processing: ${relativePath}`);
176
- }
177
- return { status: "succeeded", relativePath };
178
- } catch (error) {
179
- if (spinner) {
180
- spinner.fail(`Failed processing: ${relativePath}`);
181
- }
182
- const errorDetails = error.stdout || error.stderr || error.message;
183
-
184
- // Write error details to a log file.
185
- await mkdir(logDir, { recursive: true });
186
- const logFilePath = join(logDir, `${basename(relativePath, ".tsp")}-error.log`);
187
- await writeFile(logFilePath, errorDetails, "utf8");
188
-
189
- if (interactive) {
190
- const action = await select({
191
- message: `Processing failed for ${relativePath}. What would you like to do?`,
192
- choices: [
193
- { name: "Retry", value: "retry" },
194
- { name: "Skip to next file", value: "next" },
195
- { name: "Abort processing", value: "abort" },
196
- ],
197
- });
198
-
199
- if (action === "retry") {
200
- if (spinner) spinner.start(`Retrying: ${relativePath}`);
201
- return await processFile(file, options);
202
- } else if (action === "next") {
203
- console.log(pc.yellow(`Skipping: ${relativePath}`));
204
- } else if (action === "abort") {
205
- console.log(pc.red("Aborting processing."));
206
- throw new Error("Processing aborted by user", { cause: error });
207
- }
208
- }
209
- return { status: "failed", relativePath, errorDetails };
210
- }
211
- }
212
-
213
- // Process all files.
214
- async function processFiles(files, options) {
215
- const { interactive } = options;
216
- const succeeded = [];
217
- const failed = [];
218
-
219
- if (interactive) {
220
- // Sequential processing so each spinner is visible.
221
- for (const file of files) {
222
- try {
223
- const result = await processFile(file, options);
224
- if (result.status === "succeeded") {
225
- succeeded.push(result.relativePath);
226
- } else {
227
- failed.push({ relativePath: result.relativePath, errorDetails: result.errorDetails });
228
- }
229
- } catch (err) {
230
- break;
231
- }
232
- }
233
- } else {
234
- // Global progress spinner.
235
- const total = files.length;
236
- let completed = 0;
237
- const globalSpinner = ora({ text: `Processing 0/${total} files...`, color: "cyan" }).start();
238
- const limit = pLimit(4);
239
- const tasks = files.map((file) =>
240
- limit(() =>
241
- processFile(file, options).then((result) => {
242
- completed++;
243
- globalSpinner.text = `Processing ${completed}/${total} files...`;
244
- return result;
245
- }),
246
- ),
247
- );
248
- const results = await Promise.all(tasks);
249
- globalSpinner.succeed(`Processed ${total} files`);
250
- for (const result of results) {
251
- if (result.status === "succeeded") {
252
- succeeded.push(result.relativePath);
253
- } else {
254
- failed.push({ relativePath: result.relativePath, errorDetails: result.errorDetails });
255
- }
256
- }
257
- }
258
-
259
- console.log(pc.bold(pc.green("\nProcessing Complete:")));
260
- console.log(pc.green(`Succeeded: ${succeeded.length}`));
261
- console.log(pc.red(`Failed: ${failed.length}`));
262
-
263
- if (failed.length > 0) {
264
- console.log(pc.red("\nFailed Specs:"));
265
- failed.forEach((f) => {
266
- console.log(pc.red(` - ${f.relativePath}`));
267
- });
268
- console.log(pc.blue(`\nLogs available at: ${logDirRoot}`));
269
- }
270
-
271
- // Ensure the log directory exists before writing the report.
272
- await mkdir(logDirRoot, { recursive: true });
273
- const report = [
274
- "Succeeded Files:",
275
- ...succeeded.map((f) => ` - ${f}`),
276
- "Failed Files:",
277
- ...failed.map((f) => ` - ${f.relativePath}\n Error: ${f.errorDetails}`),
278
- ].join("\n");
279
- await writeFile(reportFilePath, report, "utf8");
280
- console.log(pc.blue(`Report written to: ${reportFilePath}`));
281
- }
282
- // Main execution function
283
- async function main() {
284
- const startTime = process.hrtime.bigint(); // āœ… High precision time tracking
285
- let exitCode = 0; // āœ… Track success/failure
286
-
287
- try {
288
- await clearLogDirectory(); // āœ… Clear logs at the start
289
-
290
- const ignoreList = await getIgnoreList();
291
- const paths = argv._.length
292
- ? await processPaths(argv._, ignoreList, argv["main-only"])
293
- : await processPaths(["."], ignoreList, argv["main-only"]);
294
-
295
- if (paths.length === 0) {
296
- console.log(pc.yellow("āš ļø No files to process."));
297
- return;
298
- }
299
-
300
- await processFiles(paths, {
301
- interactive: argv.interactive,
302
- build: argv.build,
303
- });
304
- } catch (error) {
305
- console.error(pc.red(`āŒ Fatal Error: ${error.message}`));
306
- exitCode = 1; // āœ… Ensure graceful failure handling
307
- } finally {
308
- // āœ… Always log execution time before exit
309
- const endTime = process.hrtime.bigint();
310
- const duration = Number(endTime - startTime) / 1e9; // Convert nanoseconds to seconds
311
- console.log(pc.blue(`ā±ļø Total execution time: ${duration.toFixed(2)} seconds`));
312
-
313
- process.exit(exitCode); // āœ… Ensures proper exit handling
314
- }
315
- }
316
-
317
- await main();
@@ -1,166 +0,0 @@
1
- /* eslint-disable no-console */
2
- import { exec, spawn } from "child_process";
3
- import fs from "fs";
4
- import http from "http";
5
- import ora from "ora";
6
- import path from "path";
7
- import pc from "picocolors";
8
- import { promisify } from "util";
9
- import yargs from "yargs";
10
- import { hideBin } from "yargs/helpers";
11
- import { calculateCoverage } from "./calculate-coverage.ts";
12
- import { runCoverageUpload } from "./upload-spector-results.ts";
13
-
14
- const execPromise = promisify(exec);
15
- const spinner = ora();
16
- const SERVER_URL = "http://localhost:3000/routes/in-interface/fixed";
17
-
18
- // āœ… Setup logging to a file
19
- const logFile = path.join(process.cwd(), "script.log");
20
- const logStream = fs.createWriteStream(logFile, { flags: "a" });
21
- const log = (message: string): void => {
22
- console.log(message);
23
- logStream.write(`${new Date().toISOString()} - ${message}\n`);
24
- };
25
-
26
- // āœ… Parse CLI arguments
27
- // āœ… Parse CLI arguments (Fix for --force-upload)
28
- const argv = yargs(hideBin(process.argv))
29
- .option("force-upload", {
30
- alias: "f",
31
- type: "boolean",
32
- describe: "Force coverage upload (bypass condition checks)",
33
- default: false, // Ensure it defaults to false
34
- })
35
- .option("test-path", {
36
- alias: "t",
37
- type: "string",
38
- describe: "Specify a test file to run",
39
- })
40
- .help()
41
- .alias("help", "h").argv;
42
-
43
- const testPath = argv["test-path"] || argv.t || argv.testPath || "";
44
- const forceUpload = argv["force-upload"] || argv.f || argv.forceUpload;
45
- const vitestArgs = ["vitest", "run"];
46
-
47
- if (testPath) {
48
- vitestArgs.push(testPath);
49
- } else {
50
- vitestArgs.push(...["--config", "./vitest.config.e2e.ts"]);
51
- }
52
-
53
- /**
54
- * Waits until the mock server responds with HTTP 204 on /routes
55
- */
56
- const waitForServer = async (url: string, retries = 20, delay = 2000): Promise<void> => {
57
- for (let attempt = 1; attempt <= retries; attempt++) {
58
- try {
59
- const res = await new Promise<http.IncomingMessage>((resolve, reject) => {
60
- http.get(url, resolve).on("error", reject);
61
- });
62
-
63
- if (res.statusCode === 204) {
64
- spinner.succeed(pc.green(`āœ… Server is ready (received 204 from ${url})`));
65
- return;
66
- } else {
67
- log(pc.yellow(`āš ļø Attempt ${attempt}: Received ${res.statusCode}, retrying...`));
68
- }
69
- } catch {
70
- log(pc.gray(`šŸ”„ Attempt ${attempt}: Server not ready yet...`));
71
- }
72
-
73
- await new Promise((resolve) => setTimeout(resolve, delay));
74
- }
75
-
76
- spinner.fail(pc.red(`āŒ Server did not start in time (no 204 from ${url})`));
77
- throw new Error("Server did not start in time.");
78
- };
79
-
80
- /**
81
- * Main function to start the server, run tests, and stop the server
82
- */
83
- const runE2eTests = async (): Promise<void> => {
84
- log(pc.blue(pc.bold("\nšŸš€ Starting mock server...")));
85
- spinner.start("Launching mock server...");
86
-
87
- // āœ… Start the server using spawn
88
- const serverProcess = spawn("npm", ["run", "start:server"], {
89
- shell: true,
90
- stdio: ["ignore", "pipe", "pipe"],
91
- });
92
-
93
- // āœ… Handle logs from server
94
- serverProcess.stdout.on("data", (data) => log(pc.gray(`[Server] ${data.toString().trim()}`)));
95
- serverProcess.stderr.on("data", (data) =>
96
- log(pc.red(`[Server Error] ${data.toString().trim()}`)),
97
- );
98
-
99
- // āœ… Ensure cleanup on exit
100
- const stopServer = async (): Promise<void> => {
101
- spinner.start("Shutting down mock server...");
102
- try {
103
- await execPromise("pnpm stop:server");
104
- spinner.succeed(pc.green("āœ… Mock server stopped successfully."));
105
- } catch {
106
- spinner.fail(pc.red("āŒ Failed to stop the server gracefully."));
107
- }
108
- };
109
-
110
- process.on("exit", stopServer);
111
- process.on("SIGINT", async () => {
112
- log(pc.yellow("\nšŸ›‘ Interrupt received, stopping server..."));
113
- await stopServer();
114
- process.exit();
115
- });
116
-
117
- try {
118
- await waitForServer(SERVER_URL);
119
-
120
- log(pc.green("\n🧪 Running tests...\n"));
121
- log(pc.cyan(`> ${vitestArgs.join(" ")}`));
122
-
123
- // āœ… Run Vitest and stream output live
124
- await new Promise<void>((resolve, reject) => {
125
- const testProcess = spawn("npx", vitestArgs, { stdio: "inherit", shell: true });
126
-
127
- testProcess.on("exit", async (code) => {
128
- log(pc.yellow("\nšŸ›‘ Stopping server..."));
129
- await stopServer();
130
- await calculateCoverage(); // āœ… Call calculateCoverage after the server is stopped
131
-
132
- if (code === 0) {
133
- resolve();
134
- } else {
135
- reject(new Error(`Tests failed with exit code ${code}`));
136
- }
137
- });
138
- });
139
- } catch (err) {
140
- log(pc.red(`\nāŒ Error: ${getErrorMessage(err)}`));
141
- await stopServer();
142
- process.exit(1);
143
- }
144
- };
145
-
146
- function getErrorMessage(error: unknown): string {
147
- return error instanceof Error ? error.message : String(error);
148
- }
149
- const startTime = process.hrtime.bigint(); // āœ… High precision time tracking
150
- let exitCode = 0; // āœ… Track exit status
151
-
152
- try {
153
- await runE2eTests();
154
- await runCoverageUpload({ force: forceUpload });
155
- } catch (error) {
156
- log(pc.red(`āŒ Fatal Error: ${getErrorMessage(error)}`));
157
- exitCode = 1; // āœ… Mark as failure but do NOT exit yet
158
- } finally {
159
- // āœ… Ensure time is always logged
160
- const endTime = process.hrtime.bigint();
161
- const duration = Number(endTime - startTime) / 1e9; // Convert to seconds
162
- console.log(pc.blue(`Total time taken: ${duration.toFixed(2)} seconds`));
163
-
164
- // āœ… Exit after logging (0 = success, 1 = failure)
165
- process.exit(exitCode);
166
- }
@@ -1,6 +0,0 @@
1
- emit:
2
- - "@typespec/http-client-js"
3
-
4
- options:
5
- "@typespec/http-client-js":
6
- emitter-output-dir: "{output-dir}"
@@ -1,139 +0,0 @@
1
- import { spawn } from "child_process";
2
- import fs from "fs";
3
- import ora from "ora";
4
- import path from "path";
5
- import pc from "picocolors";
6
-
7
- /* eslint-disable no-console */
8
-
9
- type CoverageUploadOptions = {
10
- force?: boolean;
11
- };
12
-
13
- /** Uploads Spector coverage when CI environment conditions allow it. */
14
- export async function runCoverageUpload({
15
- force = false,
16
- }: CoverageUploadOptions = {}): Promise<void> {
17
- console.log(pc.blue("\nšŸ” Checking conditions before uploading coverage..."));
18
-
19
- // Retrieve environment variables
20
- const buildReason = process.env.BUILD_REASON;
21
- const teamProject = process.env.SYSTEM_TEAMPROJECT;
22
-
23
- // Condition checks
24
- if (!force) {
25
- if (buildReason === "PullRequest") {
26
- console.log(pc.yellow("āš ļø Skipping upload: Running on a Pull Request."));
27
- return;
28
- }
29
- if (teamProject !== "internal") {
30
- console.log(pc.yellow("āš ļø Skipping upload: Not an internal team project."));
31
- return;
32
- }
33
- } else {
34
- console.log(pc.magenta("šŸš€ Force mode enabled: Skipping condition checks."));
35
- }
36
-
37
- // File and package details
38
- const projectRoot = process.cwd();
39
- const coverageFilePath = path.join(
40
- projectRoot,
41
- "temp",
42
- "tsp-spector-coverage-javascript-standard.json",
43
- );
44
- const packageJsonPath = path.join(projectRoot, "package.json");
45
-
46
- if (!fs.existsSync(coverageFilePath)) {
47
- console.error(pc.red(`āŒ Coverage file missing: ${coverageFilePath}`));
48
- process.exit(1);
49
- }
50
-
51
- if (!fs.existsSync(packageJsonPath)) {
52
- console.error(pc.red(`āŒ Missing package.json file in ${projectRoot}`));
53
- process.exit(1);
54
- }
55
-
56
- // Extract generator details
57
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as {
58
- name?: string;
59
- version?: string;
60
- };
61
- const generatorName = packageJson.name;
62
- const generatorVersion = packageJson.version;
63
-
64
- if (!generatorName) {
65
- console.error(pc.red("āŒ Generator name not found in package.json"));
66
- process.exit(1);
67
- }
68
-
69
- if (!generatorVersion) {
70
- console.error(pc.red("āŒ Generator version not found in package.json"));
71
- process.exit(1);
72
- }
73
-
74
- console.log(pc.green("āœ… All conditions met. Proceeding with coverage upload...\n"));
75
-
76
- // Construct command and arguments
77
- const args = [
78
- "tsp-spector",
79
- "upload-coverage",
80
- "--coverageFile",
81
- coverageFilePath,
82
- "--generatorName",
83
- generatorName,
84
- "--storageAccountName",
85
- "typespec",
86
- "--containerName",
87
- "coverages",
88
- "--generatorVersion",
89
- generatorVersion,
90
- "--generatorMode",
91
- "standard",
92
- ];
93
-
94
- // Create a spinner for user feedback
95
- const spinner = ora({
96
- text: "Uploading coverage data...",
97
- color: "cyan",
98
- spinner: "dots",
99
- }).start();
100
-
101
- try {
102
- await new Promise<void>((resolve, reject) => {
103
- const uploadProcess = spawn("npx", args, { stdio: "pipe", shell: true });
104
-
105
- // Capture output and errors
106
- uploadProcess.stdout.on("data", (data) =>
107
- console.log(pc.gray(`šŸ“„ ${data.toString().trim()}`)),
108
- );
109
- uploadProcess.stderr.on("data", (data) =>
110
- console.error(pc.red(`āŒ ${data.toString().trim()}`)),
111
- );
112
-
113
- // Handle process completion
114
- uploadProcess.on("close", (code) => {
115
- if (code === 0) {
116
- spinner.succeed(pc.green("šŸŽ‰ Coverage upload successful!"));
117
- resolve();
118
- } else {
119
- spinner.fail(pc.red(`āŒ Coverage upload failed with exit code ${code}`));
120
- reject(new Error(`Process exited with code ${code}`));
121
- }
122
- });
123
-
124
- // Handle unexpected errors
125
- uploadProcess.on("error", (error) => {
126
- spinner.fail(pc.red("āŒ An error occurred while uploading coverage."));
127
- console.error(pc.red(error.message));
128
- reject(error);
129
- });
130
- });
131
- } catch (error) {
132
- console.error(pc.red(`āŒ Error: ${getErrorMessage(error)}`));
133
- process.exit(1);
134
- }
135
- }
136
-
137
- function getErrorMessage(error: unknown): string {
138
- return error instanceof Error ? error.message : String(error);
139
- }
@@ -1,26 +0,0 @@
1
- import { refkey } from "@alloy-js/core";
2
- import * as ts from "@alloy-js/typescript";
3
- import type * as cl from "@typespec/http-client";
4
- import { httpRuntimeTemplateLib } from "../external-packages/ts-http-runtime.js";
5
-
6
- export interface ClientContextDeclarationProps {
7
- client: cl.Client;
8
- }
9
-
10
- export function getClientcontextDeclarationRef(client: cl.Client) {
11
- return refkey(client, "declaration");
12
- }
13
-
14
- export function ClientContextDeclaration(props: ClientContextDeclarationProps) {
15
- const ref = getClientcontextDeclarationRef(props.client);
16
- const namePolicy = ts.useTSNamePolicy();
17
- const name = namePolicy.getName(`${props.client.name}Context`, "class");
18
- return (
19
- <ts.InterfaceDeclaration
20
- export
21
- name={name}
22
- refkey={ref}
23
- extends={httpRuntimeTemplateLib.Client}
24
- />
25
- );
26
- }