@azure-tools/rlc-common 0.11.0

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 (232) hide show
  1. package/.eslintrc.json +23 -0
  2. package/.prettierignore +1 -0
  3. package/.prettierrc +7 -0
  4. package/.rush/temp/package-deps_build.json +53 -0
  5. package/.rush/temp/shrinkwrap-deps.json +147 -0
  6. package/CHANGELOG.md +61 -0
  7. package/CONTRIBUTING.md +30 -0
  8. package/README.md +3 -0
  9. package/dist/buildClient.js +268 -0
  10. package/dist/buildClient.js.map +1 -0
  11. package/dist/buildClientDefinitions.js +160 -0
  12. package/dist/buildClientDefinitions.js.map +1 -0
  13. package/dist/buildIndexFile.js +170 -0
  14. package/dist/buildIndexFile.js.map +1 -0
  15. package/dist/buildIsUnexpectedHelper.js +220 -0
  16. package/dist/buildIsUnexpectedHelper.js.map +1 -0
  17. package/dist/buildMethodShortcuts.js +50 -0
  18. package/dist/buildMethodShortcuts.js.map +1 -0
  19. package/dist/buildObjectTypes.js +286 -0
  20. package/dist/buildObjectTypes.js.map +1 -0
  21. package/dist/buildPaginateHelper.js +30 -0
  22. package/dist/buildPaginateHelper.js.map +1 -0
  23. package/dist/buildParameterTypes.js +315 -0
  24. package/dist/buildParameterTypes.js.map +1 -0
  25. package/dist/buildPollingHelper.js +21 -0
  26. package/dist/buildPollingHelper.js.map +1 -0
  27. package/dist/buildResponseTypes.js +135 -0
  28. package/dist/buildResponseTypes.js.map +1 -0
  29. package/dist/buildSchemaType.js +65 -0
  30. package/dist/buildSchemaType.js.map +1 -0
  31. package/dist/buildSerializeHelper.js +35 -0
  32. package/dist/buildSerializeHelper.js.map +1 -0
  33. package/dist/buildTopLevelIndexFile.js +48 -0
  34. package/dist/buildTopLevelIndexFile.js.map +1 -0
  35. package/dist/helpers/nameConstructors.js +41 -0
  36. package/dist/helpers/nameConstructors.js.map +1 -0
  37. package/dist/helpers/nameUtils.js +196 -0
  38. package/dist/helpers/nameUtils.js.map +1 -0
  39. package/dist/helpers/operationHelpers.js +103 -0
  40. package/dist/helpers/operationHelpers.js.map +1 -0
  41. package/dist/helpers/pathUtils.js +13 -0
  42. package/dist/helpers/pathUtils.js.map +1 -0
  43. package/dist/helpers/schemaHelpers.js +27 -0
  44. package/dist/helpers/schemaHelpers.js.map +1 -0
  45. package/dist/helpers/shortcutMethods.js +46 -0
  46. package/dist/helpers/shortcutMethods.js.map +1 -0
  47. package/dist/index.js +45 -0
  48. package/dist/index.js.map +1 -0
  49. package/dist/interfaces.js +18 -0
  50. package/dist/interfaces.js.map +1 -0
  51. package/dist/metadata/buildApiExtractorConfig.js +56 -0
  52. package/dist/metadata/buildApiExtractorConfig.js.map +1 -0
  53. package/dist/metadata/buildESLintConfig.js +33 -0
  54. package/dist/metadata/buildESLintConfig.js.map +1 -0
  55. package/dist/metadata/buildLicenseFile.js +41 -0
  56. package/dist/metadata/buildLicenseFile.js.map +1 -0
  57. package/dist/metadata/buildPackageFile.js +274 -0
  58. package/dist/metadata/buildPackageFile.js.map +1 -0
  59. package/dist/metadata/buildReadmeFile.js +170 -0
  60. package/dist/metadata/buildReadmeFile.js.map +1 -0
  61. package/dist/metadata/buildRollupConfig.js +144 -0
  62. package/dist/metadata/buildRollupConfig.js.map +1 -0
  63. package/dist/metadata/buildTsConfig.js +72 -0
  64. package/dist/metadata/buildTsConfig.js.map +1 -0
  65. package/dist/package.json +1 -0
  66. package/dist/static/paginateContent.js +214 -0
  67. package/dist/static/paginateContent.js.map +1 -0
  68. package/dist/static/pollingContent.js +98 -0
  69. package/dist/static/pollingContent.js.map +1 -0
  70. package/dist/static/serializeHelper.js +30 -0
  71. package/dist/static/serializeHelper.js.map +1 -0
  72. package/dist/test/buildEnvFile.js +31 -0
  73. package/dist/test/buildEnvFile.js.map +1 -0
  74. package/dist/test/buildKarmaConfig.js +19 -0
  75. package/dist/test/buildKarmaConfig.js.map +1 -0
  76. package/dist/test/buildRecordedClient.js +22 -0
  77. package/dist/test/buildRecordedClient.js.map +1 -0
  78. package/dist/test/buildSampleTest.js +19 -0
  79. package/dist/test/buildSampleTest.js.map +1 -0
  80. package/dist/test/template.js +191 -0
  81. package/dist/test/template.js.map +1 -0
  82. package/dist-esm/buildClient.js +261 -0
  83. package/dist-esm/buildClient.js.map +1 -0
  84. package/dist-esm/buildClientDefinitions.js +155 -0
  85. package/dist-esm/buildClientDefinitions.js.map +1 -0
  86. package/dist-esm/buildIndexFile.js +165 -0
  87. package/dist-esm/buildIndexFile.js.map +1 -0
  88. package/dist-esm/buildIsUnexpectedHelper.js +216 -0
  89. package/dist-esm/buildIsUnexpectedHelper.js.map +1 -0
  90. package/dist-esm/buildMethodShortcuts.js +46 -0
  91. package/dist-esm/buildMethodShortcuts.js.map +1 -0
  92. package/dist-esm/buildObjectTypes.js +288 -0
  93. package/dist-esm/buildObjectTypes.js.map +1 -0
  94. package/dist-esm/buildPaginateHelper.js +26 -0
  95. package/dist-esm/buildPaginateHelper.js.map +1 -0
  96. package/dist-esm/buildParameterTypes.js +321 -0
  97. package/dist-esm/buildParameterTypes.js.map +1 -0
  98. package/dist-esm/buildPollingHelper.js +17 -0
  99. package/dist-esm/buildPollingHelper.js.map +1 -0
  100. package/dist-esm/buildResponseTypes.js +140 -0
  101. package/dist-esm/buildResponseTypes.js.map +1 -0
  102. package/dist-esm/buildSchemaType.js +60 -0
  103. package/dist-esm/buildSchemaType.js.map +1 -0
  104. package/dist-esm/buildSerializeHelper.js +31 -0
  105. package/dist-esm/buildSerializeHelper.js.map +1 -0
  106. package/dist-esm/buildTopLevelIndexFile.js +44 -0
  107. package/dist-esm/buildTopLevelIndexFile.js.map +1 -0
  108. package/dist-esm/helpers/nameConstructors.js +34 -0
  109. package/dist-esm/helpers/nameConstructors.js.map +1 -0
  110. package/dist-esm/helpers/nameUtils.js +187 -0
  111. package/dist-esm/helpers/nameUtils.js.map +1 -0
  112. package/dist-esm/helpers/operationHelpers.js +84 -0
  113. package/dist-esm/helpers/operationHelpers.js.map +1 -0
  114. package/dist-esm/helpers/pathUtils.js +9 -0
  115. package/dist-esm/helpers/pathUtils.js.map +1 -0
  116. package/dist-esm/helpers/schemaHelpers.js +21 -0
  117. package/dist-esm/helpers/schemaHelpers.js.map +1 -0
  118. package/dist-esm/helpers/shortcutMethods.js +42 -0
  119. package/dist-esm/helpers/shortcutMethods.js.map +1 -0
  120. package/dist-esm/index.js +29 -0
  121. package/dist-esm/index.js.map +1 -0
  122. package/dist-esm/interfaces.js +15 -0
  123. package/dist-esm/interfaces.js.map +1 -0
  124. package/dist-esm/metadata/buildApiExtractorConfig.js +51 -0
  125. package/dist-esm/metadata/buildApiExtractorConfig.js.map +1 -0
  126. package/dist-esm/metadata/buildESLintConfig.js +28 -0
  127. package/dist-esm/metadata/buildESLintConfig.js.map +1 -0
  128. package/dist-esm/metadata/buildLicenseFile.js +36 -0
  129. package/dist-esm/metadata/buildLicenseFile.js.map +1 -0
  130. package/dist-esm/metadata/buildPackageFile.js +276 -0
  131. package/dist-esm/metadata/buildPackageFile.js.map +1 -0
  132. package/dist-esm/metadata/buildReadmeFile.js +167 -0
  133. package/dist-esm/metadata/buildReadmeFile.js.map +1 -0
  134. package/dist-esm/metadata/buildRollupConfig.js +139 -0
  135. package/dist-esm/metadata/buildRollupConfig.js.map +1 -0
  136. package/dist-esm/metadata/buildTsConfig.js +67 -0
  137. package/dist-esm/metadata/buildTsConfig.js.map +1 -0
  138. package/dist-esm/package.json +1 -0
  139. package/dist-esm/static/paginateContent.js +211 -0
  140. package/dist-esm/static/paginateContent.js.map +1 -0
  141. package/dist-esm/static/pollingContent.js +95 -0
  142. package/dist-esm/static/pollingContent.js.map +1 -0
  143. package/dist-esm/static/serializeHelper.js +27 -0
  144. package/dist-esm/static/serializeHelper.js.map +1 -0
  145. package/dist-esm/test/buildEnvFile.js +24 -0
  146. package/dist-esm/test/buildEnvFile.js.map +1 -0
  147. package/dist-esm/test/buildKarmaConfig.js +14 -0
  148. package/dist-esm/test/buildKarmaConfig.js.map +1 -0
  149. package/dist-esm/test/buildRecordedClient.js +17 -0
  150. package/dist-esm/test/buildRecordedClient.js.map +1 -0
  151. package/dist-esm/test/buildSampleTest.js +14 -0
  152. package/dist-esm/test/buildSampleTest.js.map +1 -0
  153. package/dist-esm/test/template.js +188 -0
  154. package/dist-esm/test/template.js.map +1 -0
  155. package/package.json +46 -0
  156. package/publishPackage.js +11 -0
  157. package/rlc-common.build.log +2 -0
  158. package/src/buildClient.ts +353 -0
  159. package/src/buildClientDefinitions.ts +235 -0
  160. package/src/buildIndexFile.ts +202 -0
  161. package/src/buildIsUnexpectedHelper.ts +240 -0
  162. package/src/buildMethodShortcuts.ts +75 -0
  163. package/src/buildObjectTypes.ts +449 -0
  164. package/src/buildPaginateHelper.ts +33 -0
  165. package/src/buildParameterTypes.ts +477 -0
  166. package/src/buildPollingHelper.ts +18 -0
  167. package/src/buildResponseTypes.ts +186 -0
  168. package/src/buildSchemaType.ts +85 -0
  169. package/src/buildSerializeHelper.ts +42 -0
  170. package/src/buildTopLevelIndexFile.ts +52 -0
  171. package/src/helpers/nameConstructors.ts +93 -0
  172. package/src/helpers/nameUtils.ts +227 -0
  173. package/src/helpers/operationHelpers.ts +119 -0
  174. package/src/helpers/pathUtils.ts +9 -0
  175. package/src/helpers/schemaHelpers.ts +25 -0
  176. package/src/helpers/shortcutMethods.ts +60 -0
  177. package/src/index.ts +29 -0
  178. package/src/interfaces.ts +227 -0
  179. package/src/metadata/buildApiExtractorConfig.ts +59 -0
  180. package/src/metadata/buildESLintConfig.ts +34 -0
  181. package/src/metadata/buildLicenseFile.ts +39 -0
  182. package/src/metadata/buildPackageFile.ts +334 -0
  183. package/src/metadata/buildReadmeFile.ts +231 -0
  184. package/src/metadata/buildRollupConfig.ts +147 -0
  185. package/src/metadata/buildTsConfig.ts +79 -0
  186. package/src/static/paginateContent.ts +210 -0
  187. package/src/static/pollingContent.ts +94 -0
  188. package/src/static/serializeHelper.ts +29 -0
  189. package/src/test/buildEnvFile.ts +26 -0
  190. package/src/test/buildKarmaConfig.ts +15 -0
  191. package/src/test/buildRecordedClient.ts +18 -0
  192. package/src/test/buildSampleTest.ts +15 -0
  193. package/src/test/template.ts +191 -0
  194. package/tsconfig-cjs.json +9 -0
  195. package/tsconfig-common.json +13 -0
  196. package/tsconfig.json +13 -0
  197. package/types/buildClient.d.ts +2 -0
  198. package/types/buildClientDefinitions.d.ts +5 -0
  199. package/types/buildIndexFile.d.ts +5 -0
  200. package/types/buildIsUnexpectedHelper.d.ts +5 -0
  201. package/types/buildMethodShortcuts.d.ts +4 -0
  202. package/types/buildObjectTypes.d.ts +15 -0
  203. package/types/buildPaginateHelper.d.ts +5 -0
  204. package/types/buildParameterTypes.d.ts +13 -0
  205. package/types/buildPollingHelper.d.ts +5 -0
  206. package/types/buildResponseTypes.d.ts +5 -0
  207. package/types/buildSchemaType.d.ts +19 -0
  208. package/types/buildSerializeHelper.d.ts +5 -0
  209. package/types/buildTopLevelIndexFile.d.ts +5 -0
  210. package/types/helpers/nameConstructors.d.ts +28 -0
  211. package/types/helpers/nameUtils.d.ts +25 -0
  212. package/types/helpers/operationHelpers.d.ts +13 -0
  213. package/types/helpers/pathUtils.d.ts +1 -0
  214. package/types/helpers/schemaHelpers.d.ts +4 -0
  215. package/types/helpers/shortcutMethods.d.ts +3 -0
  216. package/types/index.d.ts +26 -0
  217. package/types/interfaces.d.ts +200 -0
  218. package/types/metadata/buildApiExtractorConfig.d.ts +5 -0
  219. package/types/metadata/buildESLintConfig.d.ts +5 -0
  220. package/types/metadata/buildLicenseFile.d.ts +5 -0
  221. package/types/metadata/buildPackageFile.d.ts +5 -0
  222. package/types/metadata/buildReadmeFile.d.ts +5 -0
  223. package/types/metadata/buildRollupConfig.d.ts +5 -0
  224. package/types/metadata/buildTsConfig.d.ts +5 -0
  225. package/types/static/paginateContent.d.ts +1 -0
  226. package/types/static/pollingContent.d.ts +1 -0
  227. package/types/static/serializeHelper.d.ts +4 -0
  228. package/types/test/buildEnvFile.d.ts +9 -0
  229. package/types/test/buildKarmaConfig.d.ts +5 -0
  230. package/types/test/buildRecordedClient.d.ts +5 -0
  231. package/types/test/buildSampleTest.d.ts +5 -0
  232. package/types/test/template.d.ts +5 -0
@@ -0,0 +1,147 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+
4
+ import { Project } from "ts-morph";
5
+ import { RLCModel } from "../interfaces.js";
6
+
7
+ export function buildRollupConfig(model: RLCModel) {
8
+ const generateMetadata = Boolean(model.options?.generateMetadata),
9
+ azureSdkForJs = Boolean(model.options?.azureSdkForJs);
10
+ // when it's generating rlc codes, only generate rollup config in codegen test
11
+ if (!generateMetadata || azureSdkForJs) {
12
+ return;
13
+ }
14
+
15
+ const project = new Project();
16
+ const filePath = "rollup.config.js";
17
+ const rollupFile = project.createSourceFile(filePath, undefined, {
18
+ overwrite: true
19
+ });
20
+
21
+ rollupFile.addStatements(
22
+ `import nodeResolve from "@rollup/plugin-node-resolve";
23
+ import cjs from "@rollup/plugin-commonjs";
24
+ import sourcemaps from "rollup-plugin-sourcemaps";
25
+ import multiEntry from "@rollup/plugin-multi-entry";
26
+ import json from "@rollup/plugin-json";
27
+
28
+ import nodeBuiltins from "builtin-modules";
29
+
30
+ // #region Warning Handler
31
+
32
+ /**
33
+ * A function that can determine whether a rollup warning should be ignored. If
34
+ * the function returns \`true\`, then the warning will not be displayed.
35
+ */
36
+
37
+ function ignoreNiseSinonEval(warning) {
38
+ return (
39
+ warning.code === "EVAL" &&
40
+ (warning.id && ((warning.id.includes("node_modules/nise")) ||
41
+ warning.id.includes("node_modules/sinon")) === true)
42
+ );
43
+ }
44
+
45
+ function ignoreChaiCircularDependency(warning) {
46
+ return (
47
+ warning.code === "CIRCULAR_DEPENDENCY" &&
48
+ (warning.importer && warning.importer.includes("node_modules/chai") === true)
49
+ );
50
+ }
51
+
52
+ const warningInhibitors = [
53
+ ignoreChaiCircularDependency,
54
+ ignoreNiseSinonEval
55
+ ];
56
+
57
+ /**
58
+ * Construct a warning handler for the shared rollup configuration
59
+ * that ignores certain warnings that are not relevant to testing.
60
+ */
61
+ function makeOnWarnForTesting() {
62
+ return (warning, warn) => {
63
+ // If every inhibitor returns false (i.e. no inhibitors), then show the warning
64
+ if (warningInhibitors.every(inhib => !inhib(warning))) {
65
+ warn(warning);
66
+ }
67
+ };
68
+ }
69
+
70
+ // #endregion
71
+
72
+ function makeBrowserTestConfig() {
73
+ const config = {
74
+ input: {
75
+ include: ["dist-esm/test/**/*.spec.js"],
76
+ exclude: ["dist-esm/test/**/node/**"]
77
+ },
78
+ output: {
79
+ file: \`dist-test/index.browser.js\`,
80
+ format: "umd",
81
+ sourcemap: true
82
+ },
83
+ preserveSymlinks: false,
84
+ plugins: [
85
+ multiEntry({ exports: false }),
86
+ nodeResolve({
87
+ mainFields: ["module", "browser"]
88
+ }),
89
+ cjs(),
90
+ json(),
91
+ sourcemaps()
92
+ //viz({ filename: "dist-test/browser-stats.html", sourcemap: true })
93
+ ],
94
+ onwarn: makeOnWarnForTesting(),
95
+ // Disable tree-shaking of test code. In rollup-plugin-node-resolve@5.0.0,
96
+ // rollup started respecting the "sideEffects" field in package.json. Since
97
+ // our package.json sets "sideEffects=false", this also applies to test
98
+ // code, which causes all tests to be removed by tree-shaking.
99
+ treeshake: false
100
+ };
101
+
102
+ return config;
103
+ }
104
+
105
+ const defaultConfigurationOptions = {
106
+ disableBrowserBundle: false
107
+ };
108
+
109
+ export function makeConfig(
110
+ pkg,
111
+ options
112
+ ) {
113
+ options = {
114
+ ...defaultConfigurationOptions,
115
+ ...(options || {})
116
+ };
117
+
118
+ const baseConfig = {
119
+ // Use the package's module field if it has one
120
+ input: pkg["module"] || "dist-esm/src/index.js",
121
+ external: [
122
+ ...nodeBuiltins,
123
+ ...Object.keys(pkg.dependencies),
124
+ ...Object.keys(pkg.devDependencies)
125
+ ],
126
+ output: { file: "dist/index.js", format: "cjs", sourcemap: true },
127
+ preserveSymlinks: false,
128
+ plugins: [sourcemaps(), nodeResolve()]
129
+ };
130
+
131
+ const config = [baseConfig];
132
+
133
+ if (!options.disableBrowserBundle) {
134
+ config.push(makeBrowserTestConfig());
135
+ }
136
+
137
+ return config;
138
+ }
139
+
140
+ export default makeConfig(require("./package.json"));`
141
+ );
142
+
143
+ return {
144
+ path: filePath,
145
+ content: rollupFile.getFullText()
146
+ };
147
+ }
@@ -0,0 +1,79 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+
4
+ import { Project } from "ts-morph";
5
+ import { RLCModel } from "../interfaces.js";
6
+
7
+ const restLevelTsConfigInAzureSdkForJs: Record<string, any> = {
8
+ extends: "../../../tsconfig.package",
9
+ compilerOptions: {
10
+ outDir: "./dist-esm",
11
+ declarationDir: "./types"
12
+ },
13
+ include: ["src/**/*.ts"]
14
+ };
15
+
16
+ const restLevelTsConfigNotInAzureSdkForJs: Record<string, any> = {
17
+ compilerOptions: {
18
+ target: "ES2017",
19
+ module: "es6",
20
+ lib: [],
21
+ declaration: true,
22
+ declarationMap: true,
23
+ inlineSources: true,
24
+ sourceMap: true,
25
+ importHelpers: true,
26
+ strict: true,
27
+ alwaysStrict: true,
28
+ noUnusedLocals: true,
29
+ noUnusedParameters: true,
30
+ noImplicitReturns: true,
31
+ noFallthroughCasesInSwitch: true,
32
+ forceConsistentCasingInFileNames: true,
33
+ moduleResolution: "node",
34
+ allowSyntheticDefaultImports: true,
35
+ esModuleInterop: true,
36
+ outDir: "./dist-esm",
37
+ declarationDir: "./types"
38
+ },
39
+ include: ["./src/**/*.ts"]
40
+ };
41
+
42
+ export function buildTsConfig(model: RLCModel, hasSamplesGenerated = false) {
43
+ const generateMetadata = Boolean(model.options?.generateMetadata);
44
+ if (!generateMetadata) {
45
+ return;
46
+ }
47
+ const { generateTest, packageDetails, generateSample, azureSdkForJs } =
48
+ model.options || {};
49
+ const clientPackageName = packageDetails?.name ?? "";
50
+ const project = new Project();
51
+
52
+ const restLevelTsConfig = azureSdkForJs
53
+ ? restLevelTsConfigInAzureSdkForJs
54
+ : restLevelTsConfigNotInAzureSdkForJs;
55
+
56
+ if (generateTest) {
57
+ restLevelTsConfig.include.push("./test/**/*.ts");
58
+ }
59
+ if (generateSample && hasSamplesGenerated) {
60
+ restLevelTsConfig.include.push("samples-dev/**/*.ts");
61
+ restLevelTsConfig.compilerOptions["paths"] = {};
62
+ restLevelTsConfig.compilerOptions["paths"][clientPackageName] = [
63
+ "./src/index"
64
+ ];
65
+ }
66
+
67
+ const filePath = "tsconfig.json";
68
+ const configFile = project.createSourceFile(
69
+ filePath,
70
+ JSON.stringify(restLevelTsConfig),
71
+ {
72
+ overwrite: true
73
+ }
74
+ );
75
+ return {
76
+ path: filePath,
77
+ content: configFile.getFullText()
78
+ };
79
+ }
@@ -0,0 +1,210 @@
1
+ export const paginateContent = `
2
+ import {
3
+ getPagedAsyncIterator,
4
+ PagedAsyncIterableIterator,
5
+ PagedResult
6
+ } from "@azure/core-paging";
7
+ import {
8
+ Client,
9
+ createRestError,
10
+ PathUncheckedResponse
11
+ } from "@azure-rest/core-client";
12
+
13
+ /**
14
+ * Helper type to extract the type of an array
15
+ */
16
+ export type GetArrayType<T> = T extends Array<infer TData> ? TData : never;
17
+
18
+ /**
19
+ * The type of a custom function that defines how to get a page and a link to the next one if any.
20
+ */
21
+ export type GetPage<TPage> = (
22
+ pageLink: string,
23
+ maxPageSize?: number
24
+ ) => Promise<{
25
+ page: TPage;
26
+ nextPageLink?: string;
27
+ }>;
28
+
29
+ /**
30
+ * Options for the paging helper
31
+ */
32
+ export interface PagingOptions<TResponse> {
33
+ /**
34
+ * Custom function to extract pagination details for crating the PagedAsyncIterableIterator
35
+ */
36
+ customGetPage?: GetPage<PaginateReturn<TResponse>[]>
37
+ }
38
+
39
+ /**
40
+ * Helper type to infer the Type of the paged elements from the response type
41
+ * This type is generated based on the swagger information for x-ms-pageable
42
+ * specifically on the itemName property which indicates the property of the response
43
+ * where the page items are found. The default value is \`value\`.
44
+ * This type will allow us to provide strongly typed Iterator based on the response we get as second parameter
45
+ */
46
+ export type PaginateReturn<TResult> = TResult extends {{#each itemNames}}
47
+ {
48
+
49
+ body: { {{this}}?: infer TPage }
50
+
51
+ } {{#if @last }}{{else}} | {{/if}}
52
+ {{/each}}
53
+ ? GetArrayType<TPage>
54
+ : Array<unknown>;
55
+
56
+ /**
57
+ * Helper to paginate results from an initial response that follows the specification of Autorest \`x-ms-pageable\` extension
58
+ * @param client - Client to use for sending the next page requests
59
+ * @param initialResponse - Initial response containing the nextLink and current page of elements
60
+ * @param customGetPage - Optional - Function to define how to extract the page and next link to be used to paginate the results
61
+ * @returns - PagedAsyncIterableIterator to iterate the elements
62
+ */
63
+ export function paginate<TResponse extends PathUncheckedResponse>(
64
+ client: Client,
65
+ initialResponse: TResponse,
66
+ options: PagingOptions<TResponse> = {}
67
+ ): PagedAsyncIterableIterator<PaginateReturn<TResponse>> {
68
+ // Extract element type from initial response
69
+ type TElement = PaginateReturn<TResponse>;
70
+ let firstRun = true;
71
+ {{#if isComplexPaging}}
72
+ // We need to check the response for success before trying to inspect it looking for
73
+ // the properties to use for nextLink and itemName
74
+ checkPagingRequest(initialResponse);
75
+ const { itemName, nextLinkName } = getPaginationProperties(initialResponse);
76
+ {{else}}
77
+ const itemName = {{ quoteWrap itemNames }};
78
+ const nextLinkName = {{quoteWrap nextLinkNames}};
79
+ {{/if}}
80
+ const { customGetPage } = options;
81
+ const pagedResult: PagedResult<TElement[]> = {
82
+ firstPageLink: "",
83
+ getPage:
84
+ typeof customGetPage === "function"
85
+ ? customGetPage
86
+ : async (pageLink: string) => {
87
+ const result = firstRun
88
+ ? initialResponse
89
+ : await client.pathUnchecked(pageLink).get();
90
+ firstRun = false;
91
+ checkPagingRequest(result);
92
+ const nextLink = getNextLink(result.body, nextLinkName);
93
+ const values = getElements<TElement>(result.body, itemName);
94
+ return {
95
+ page: values,
96
+ nextPageLink: nextLink
97
+ };
98
+ }
99
+ };
100
+
101
+ return getPagedAsyncIterator(pagedResult);
102
+ }
103
+
104
+ /**
105
+ * Gets for the value of nextLink in the body
106
+ */
107
+ function getNextLink(body: unknown, nextLinkName?: string): string | undefined {
108
+ if (!nextLinkName) {
109
+ return undefined;
110
+ }
111
+
112
+ const nextLink = (body as Record<string, unknown>)[nextLinkName];
113
+
114
+ if (typeof nextLink !== "string" && typeof nextLink !== "undefined") {
115
+ throw new Error(
116
+ \`Body Property \${nextLinkName} should be a string or undefined\`
117
+ );
118
+ }
119
+
120
+ return nextLink;
121
+ }
122
+
123
+ /**
124
+ * Gets the elements of the current request in the body.
125
+ */
126
+ function getElements<T = unknown>(body: unknown, itemName: string): T[] {
127
+ const value = (body as Record<string, unknown>)[itemName] as T[];
128
+
129
+ // value has to be an array according to the x-ms-pageable extension.
130
+ // The fact that this must be an array is used above to calculate the
131
+ // type of elements in the page in PaginateReturn
132
+ if (!Array.isArray(value)) {
133
+ throw new Error(
134
+ \`Couldn't paginate response\\n Body doesn't contain an array property with name: \${itemName}\`
135
+ );
136
+ }
137
+
138
+ return value ?? [];
139
+ }
140
+
141
+ /**
142
+ * Checks if a request failed
143
+ */
144
+ function checkPagingRequest(response: PathUncheckedResponse): void {
145
+ const Http2xxStatusCodes = [
146
+ "200",
147
+ "201",
148
+ "202",
149
+ "203",
150
+ "204",
151
+ "205",
152
+ "206",
153
+ "207",
154
+ "208",
155
+ "226"
156
+ ];
157
+ if (!Http2xxStatusCodes.includes(response.status)) {
158
+ throw createRestError(
159
+ \`Pagination failed with unexpected statusCode \${response.status}\`,
160
+ response
161
+ );
162
+ }
163
+ }
164
+
165
+ {{#if isComplexPaging}}
166
+ /**
167
+ * Extracts the itemName and nextLinkName from the initial response to use them for pagination
168
+ */
169
+ function getPaginationProperties(initialResponse: PathUncheckedResponse) {
170
+ // Build a set with the passed custom nextLinkNames
171
+ const nextLinkNames = new Set([{{ quoteWrap nextLinkNames }}]);
172
+
173
+ // Build a set with the passed custom set of itemNames
174
+ const itemNames = new Set([{{ quoteWrap itemNames }}]);
175
+
176
+ let nextLinkName: string | undefined;
177
+ let itemName: string | undefined;
178
+
179
+ for (const name of nextLinkNames) {
180
+ const nextLink = (initialResponse.body as Record<string, unknown>)[
181
+ name
182
+ ] as string;
183
+ if (nextLink) {
184
+ nextLinkName = name;
185
+ break;
186
+ }
187
+ }
188
+
189
+ for (const name of itemNames) {
190
+ const item = (initialResponse.body as Record<string, unknown>)[
191
+ name
192
+ ] as string;
193
+ if (item) {
194
+ itemName = name;
195
+ break;
196
+ }
197
+ }
198
+
199
+ if (!itemName) {
200
+ throw new Error(
201
+ \`Couldn't paginate response\\n Body doesn't contain an array property with name: \${[
202
+ ...itemNames
203
+ ].join(" OR ")}\`
204
+ );
205
+ }
206
+
207
+ return { itemName, nextLinkName };
208
+ }
209
+ {{/if}}
210
+ `;
@@ -0,0 +1,94 @@
1
+ export const pollingContent = `
2
+ import { Client, HttpResponse } from "@azure-rest/core-client";
3
+ {{#if useLegacyLro}}
4
+ import {
5
+ LongRunningOperation,
6
+ LroEngine,
7
+ LroEngineOptions,
8
+ LroResponse,
9
+ PollerLike,
10
+ PollOperationState
11
+ } from "@azure/core-lro";
12
+ {{else}}
13
+ import {
14
+ CreateHttpPollerOptions,
15
+ LongRunningOperation,
16
+ LroResponse,
17
+ OperationState,
18
+ SimplePollerLike,
19
+ createHttpPoller
20
+ } from "@azure/core-lro";
21
+ {{/if}}
22
+ /**
23
+ * Helper function that builds a Poller object to help polling a long running operation.
24
+ * @param client - Client to use for sending the request to get additional pages.
25
+ * @param initialResponse - The initial response.
26
+ * @param options - Options to set a resume state or custom polling interval.
27
+ * @returns - A poller object to poll for operation state updates and eventually get the final response.
28
+ */
29
+ export {{#unless useLegacyLro}}async {{/unless}}function getLongRunningPoller<TResult extends HttpResponse>(
30
+ client: Client,
31
+ initialResponse: TResult,
32
+ {{#if useLegacyLro}}
33
+ options: LroEngineOptions<TResult, PollOperationState<TResult>> = {}
34
+ ): PollerLike<PollOperationState<TResult>, TResult> {
35
+ {{else}}
36
+ options: CreateHttpPollerOptions<TResult, OperationState<TResult>> = {}
37
+ ): Promise<SimplePollerLike<OperationState<TResult>, TResult>> {
38
+ {{/if}}
39
+ const poller: LongRunningOperation<TResult> = {
40
+ requestMethod: initialResponse.request.method,
41
+ requestPath: initialResponse.request.url,
42
+ sendInitialRequest: async () => {
43
+ // In the case of Rest Clients we are building the LRO poller object from a response that's the reason
44
+ // we are not triggering the initial request here, just extracting the information from the
45
+ // response we were provided.
46
+ return getLroResponse(initialResponse);
47
+ },
48
+ sendPollRequest: async path => {
49
+ // This is the callback that is going to be called to poll the service
50
+ // to get the latest status. We use the client provided and the polling path
51
+ // which is an opaque URL provided by caller, the service sends this in one of the following headers: operation-location, azure-asyncoperation or location
52
+ // depending on the lro pattern that the service implements. If non is provided we default to the initial path.
53
+ const response = await client
54
+ .pathUnchecked(path ?? initialResponse.request.url)
55
+ .get();
56
+ const lroResponse = getLroResponse(response as TResult);
57
+ lroResponse.rawResponse.headers["x-ms-original-url"] =
58
+ initialResponse.request.url;
59
+ return lroResponse;
60
+ }
61
+ };
62
+
63
+ {{#if useLegacyLro}}
64
+ return new LroEngine(poller, options);
65
+ {{else}}
66
+ options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true;
67
+ return await createHttpPoller(poller, options);
68
+ {{/if}}
69
+ }
70
+
71
+ /**
72
+ * Converts a Rest Client response to a response that the LRO implementation understands
73
+ * @param response - a rest client http response
74
+ * @returns - An LRO response that the LRO implementation understands
75
+ */
76
+ function getLroResponse<TResult extends HttpResponse>(
77
+ response: TResult
78
+ ): LroResponse<TResult> {
79
+ if (Number.isNaN(response.status)) {
80
+ throw new TypeError(
81
+ \`Status code of the response is not a number. Value: \${response.status}\`
82
+ );
83
+ }
84
+
85
+ return {
86
+ flatResponse: response,
87
+ rawResponse: {
88
+ ...response,
89
+ statusCode: Number.parseInt(response.status),
90
+ body: response.body
91
+ }
92
+ };
93
+ }
94
+ `;
@@ -0,0 +1,29 @@
1
+ export const buildMultiCollectionContent = `
2
+ export function buildMultiCollection(
3
+ queryParameters: string[],
4
+ parameterName: string
5
+ ) {
6
+ return queryParameters
7
+ .map((item, index) => {
8
+ if (index === 0) {
9
+ return item;
10
+ }
11
+ return \`\${parameterName}=\${item}\`;
12
+ })
13
+ .join("&");
14
+ }`;
15
+
16
+ export const buildPipeCollectionContent = `
17
+ export function buildPipeCollection(queryParameters: string[]): string {
18
+ return queryParameters.join("|");
19
+ }`;
20
+
21
+ export const buildSsvCollectionContent = `
22
+ export function buildSsvCollection(queryParameters: string[]): string {
23
+ return queryParameters.join(" ");
24
+ }`;
25
+
26
+ export const buildTsvCollectionContent = `
27
+ export function buildTsvCollection(queryParameters: string[]) {
28
+ return queryParameters.join("\\t");
29
+ }`;
@@ -0,0 +1,26 @@
1
+ // @ts-ignore: to fix the handlebars issue
2
+ import hbs from "handlebars";
3
+ import { envContent } from "./template.js";
4
+ import { RLCModel } from "../interfaces.js";
5
+
6
+ export function buildEnvFile(model: RLCModel) {
7
+ const generateTest = Boolean(model.options?.generateTest);
8
+ if (!generateTest) {
9
+ return;
10
+ }
11
+ return {
12
+ path: "test/public/utils/env.ts",
13
+ content: hbs.compile(envContent, { noEscape: true })({})
14
+ };
15
+ }
16
+
17
+ export function buildEnvBrowserFile(model: RLCModel) {
18
+ const generateTest = Boolean(model.options?.generateTest);
19
+ if (!generateTest) {
20
+ return;
21
+ }
22
+ return {
23
+ path: "test/public/utils/env.browser.ts",
24
+ content: hbs.compile("", { noEscape: true })({})
25
+ };
26
+ }
@@ -0,0 +1,15 @@
1
+ // @ts-ignore: to fix the handlebars issue
2
+ import hbs from "handlebars";
3
+ import { RLCModel } from "../interfaces.js";
4
+ import { karmaConfig } from "./template.js";
5
+
6
+ export function buildKarmaConfigFile(model: RLCModel) {
7
+ const generateTest = Boolean(model.options?.generateTest);
8
+ if (!generateTest) {
9
+ return;
10
+ }
11
+ return {
12
+ path: "karma.conf.js",
13
+ content: hbs.compile(karmaConfig, { noEscape: true })({})
14
+ };
15
+ }
@@ -0,0 +1,18 @@
1
+ // @ts-ignore: to fix the handlebars issue
2
+ import hbs from "handlebars";
3
+ import { RLCModel } from "../interfaces.js";
4
+ import { recordedClientContent } from "./template.js";
5
+
6
+ export function buildRecordedClientFile(model: RLCModel) {
7
+ const generateTest = Boolean(model.options?.generateTest);
8
+ if (!generateTest) {
9
+ return;
10
+ }
11
+ const recordedClientFileContents = hbs.compile(recordedClientContent, {
12
+ noEscape: true
13
+ });
14
+ return {
15
+ path: "test/public/utils/recordedClient.ts",
16
+ content: recordedClientFileContents({})
17
+ };
18
+ }
@@ -0,0 +1,15 @@
1
+ // @ts-ignore: to fix the handlebars issue
2
+ import hbs from "handlebars";
3
+ import { sampleTestContent } from "./template.js";
4
+ import { RLCModel } from "../interfaces.js";
5
+
6
+ export function buildSampleTest(model: RLCModel) {
7
+ const generateTest = Boolean(model.options?.generateTest);
8
+ if (!generateTest) {
9
+ return;
10
+ }
11
+ return {
12
+ path: "test/public/sampleTest.spec.ts",
13
+ content: hbs.compile(sampleTestContent, { noEscape: true })({})
14
+ };
15
+ }