@yolean/evidence-sdk 0.0.0-stage → 4.2.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 (186) hide show
  1. package/CHANGELOG.md +544 -0
  2. package/LICENSE.md +9 -0
  3. package/README.md +237 -2
  4. package/package.json +161 -3
  5. package/src/build-dev/cli/add/addServerHook.js +30 -0
  6. package/src/build-dev/cli/add/addTypeRef.js +19 -0
  7. package/src/build-dev/cli/add/updateGitIgnore.js +33 -0
  8. package/src/build-dev/cli/add/updatePackageJson.js +26 -0
  9. package/src/build-dev/cli/add/updateSvelteConfig.js +199 -0
  10. package/src/build-dev/cli/add/updateViteConfig.js +152 -0
  11. package/src/build-dev/cli/add.js +95 -0
  12. package/src/build-dev/cli/build.js +30 -0
  13. package/src/build-dev/cli/dev.js +49 -0
  14. package/src/build-dev/cli/index.js +14 -0
  15. package/src/build-dev/cli/upgrade.js +54 -0
  16. package/src/build-dev/svelte/index.js +54 -0
  17. package/src/build-dev/svelte/lib/isTargetFile.js +6 -0
  18. package/src/build-dev/svelte/metadatas.js +39 -0
  19. package/src/build-dev/svelte/processors/addBasePathToHrefAndSrc/addBasePathToHrefAndSrc.js +29 -0
  20. package/src/build-dev/svelte/processors/addBasePathToHrefAndSrc/addBasePathToHrefAndSrc.spec.js +82 -0
  21. package/src/build-dev/svelte/processors/addScriptTags.js +17 -0
  22. package/src/build-dev/svelte/processors/convertToHtml/convertToHtml.js +19 -0
  23. package/src/build-dev/svelte/processors/convertToHtml/convertToHtml.spec.js +123 -0
  24. package/src/build-dev/svelte/processors/convertToHtml/processMarkdown.js +59 -0
  25. package/src/build-dev/svelte/processors/extractQueries/extractQueries.js +49 -0
  26. package/src/build-dev/svelte/processors/extractQueries/extractQueries.spec.js +54 -0
  27. package/src/build-dev/svelte/processors/highlight/highlight.js +52 -0
  28. package/src/build-dev/svelte/processors/highlight/highlight.spec.js +31 -0
  29. package/src/build-dev/svelte/processors/initializeUniversalSql.js +15 -0
  30. package/src/build-dev/svelte/processors/injectComponents/injectComponents.js +56 -0
  31. package/src/build-dev/svelte/processors/injectHighlightStyles.js +14 -0
  32. package/src/build-dev/svelte/processors/injectQueries/injectQueries.js +77 -0
  33. package/src/build-dev/svelte/processors/markRootLayoutPrerenderable.js +56 -0
  34. package/src/build-dev/svelte/processors/obfuscateCode/obfuscateCode.js +17 -0
  35. package/src/build-dev/svelte/processors/obfuscateCode/obfuscateCode.spec.js +21 -0
  36. package/src/build-dev/svelte/processors/transformQueries/transformQueries.js +58 -0
  37. package/src/build-dev/vite/config-virtual.js +24 -0
  38. package/src/build-dev/vite/constants.js +7 -0
  39. package/src/build-dev/vite/datasource-plugins/source-query-hmr.js +117 -0
  40. package/src/build-dev/vite/evidence-config.d.ts +6 -0
  41. package/src/build-dev/vite/index.js +214 -0
  42. package/src/build-dev/vite/layout-plugins/copy-to-layout.js +71 -0
  43. package/src/build-dev/vite/plugins.js +4 -0
  44. package/src/build-dev/vite/query-directory-hmr.js +32 -0
  45. package/src/build-dev/vite/sidecar-app.js +79 -0
  46. package/src/build-dev/vite/virtuals/QuerySSR.svelte +13 -0
  47. package/src/build-dev/vite/virtuals/__tests/proxyStack.spec.js +52 -0
  48. package/src/build-dev/vite/virtuals/bootstrapContexts.svelte.js +27 -0
  49. package/src/build-dev/vite/virtuals/browser/static-assets.js +3 -0
  50. package/src/build-dev/vite/virtuals/contextKeys.js +3 -0
  51. package/src/build-dev/vite/virtuals/initUsql.js +23 -0
  52. package/src/build-dev/vite/virtuals/node/static-assets.js +56 -0
  53. package/src/build-dev/vite/virtuals/proxyStack.js +37 -0
  54. package/src/build-dev/vite/virtuals/queries.svelte.js +150 -0
  55. package/src/build-dev/vite/virtuals/ssrHook.svelte.js +60 -0
  56. package/src/build-dev/vite/virtuals/updateQueryContext.svelte.js +31 -0
  57. package/src/build-dev/vite/virtuals-dynamic.js +12 -0
  58. package/src/cli.js +5 -0
  59. package/src/cli.root.js +90 -0
  60. package/src/configuration/cli/create.js +20 -0
  61. package/src/configuration/cli/index.js +12 -0
  62. package/src/configuration/createEvidenceConfig.js +51 -0
  63. package/src/configuration/getEvidenceConfig.js +60 -0
  64. package/src/configuration/getEvidenceConfig.legacy.js +27 -0
  65. package/src/configuration/index.js +1 -0
  66. package/src/configuration/schemas/config.schema.js +11 -0
  67. package/src/configuration/schemas/deployment.schema.js +18 -0
  68. package/src/configuration/schemas/deployment.schema.spec.js +34 -0
  69. package/src/configuration/updateEvidenceConfig.js +25 -0
  70. package/src/legacy-compat.js +8 -0
  71. package/src/lib/EvidenceError.js +35 -0
  72. package/src/lib/b64Deep.js +55 -0
  73. package/src/lib/check-import.js +12 -0
  74. package/src/lib/cleanZodErrors.js +22 -0
  75. package/src/lib/cli/cmdFail.js +33 -0
  76. package/src/lib/cli/notices.js +44 -0
  77. package/src/lib/debug.js +40 -0
  78. package/src/lib/flows.d.ts +21 -0
  79. package/src/lib/forceLink.js +28 -0
  80. package/src/lib/history/index.js +70 -0
  81. package/src/lib/history/types.d.ts +8 -0
  82. package/src/lib/pkg-types.helpers.js +16 -0
  83. package/src/lib/processing-queue.js +96 -0
  84. package/src/lib/processing-queue.spec.js +148 -0
  85. package/src/lib/projectPaths.js +29 -0
  86. package/src/lib/projectRoot.js +12 -0
  87. package/src/lib/sharedPromise.js +77 -0
  88. package/src/lib/sharedPromise.spec.js +23 -0
  89. package/src/lib/strict.js +19 -0
  90. package/src/lib/tests/fs.js +21 -0
  91. package/src/lib/tokens.js +7 -0
  92. package/src/lib/unnest-zod-error.js +14 -0
  93. package/src/logger/EvidenceLogger.js +164 -0
  94. package/src/logger/index.js +4 -0
  95. package/src/meta.js +8 -0
  96. package/src/plugins/cli/index.js +13 -0
  97. package/src/plugins/cli/install.js +26 -0
  98. package/src/plugins/cli/install.prompt.js +121 -0
  99. package/src/plugins/components/getAllComponents.js +82 -0
  100. package/src/plugins/components/getComponentsInPlugin.js +33 -0
  101. package/src/plugins/components/loadComponentPlugins.js +48 -0
  102. package/src/plugins/components/loaders/file-loader.js +125 -0
  103. package/src/plugins/components/loaders/manifest-loader.js +53 -0
  104. package/src/plugins/components/schemas/component-manifest.schema.js +5 -0
  105. package/src/plugins/components/types.d.ts +21 -0
  106. package/src/plugins/components/validateOverrides.js +30 -0
  107. package/src/plugins/components/validateOverrides.spec.js +32 -0
  108. package/src/plugins/datasources/Datasources.js +85 -0
  109. package/src/plugins/datasources/Datasources.spec.js +78 -0
  110. package/src/plugins/datasources/SourceResultCache.js +62 -0
  111. package/src/plugins/datasources/buildSourceDirectoryProxy.js +21 -0
  112. package/src/plugins/datasources/cli/edit/Options.fixtures.js +69 -0
  113. package/src/plugins/datasources/cli/edit/Options.js +253 -0
  114. package/src/plugins/datasources/cli/edit/Options.spec.js +496 -0
  115. package/src/plugins/datasources/cli/edit/editSourceConfig.js +201 -0
  116. package/src/plugins/datasources/cli/edit.js +20 -0
  117. package/src/plugins/datasources/cli/edit.prompt.js +100 -0
  118. package/src/plugins/datasources/cli/index.js +18 -0
  119. package/src/plugins/datasources/cli/sources.js +77 -0
  120. package/src/plugins/datasources/evalSources.js +257 -0
  121. package/src/plugins/datasources/getPublishedDatasources.js +62 -0
  122. package/src/plugins/datasources/index.js +6 -0
  123. package/src/plugins/datasources/loadSourceConfig.js +147 -0
  124. package/src/plugins/datasources/loadSourceConfig.spec.js +127 -0
  125. package/src/plugins/datasources/loadSourcePlugins.js +49 -0
  126. package/src/plugins/datasources/loadSources.js +48 -0
  127. package/src/plugins/datasources/schemas/datasource.schema.js +52 -0
  128. package/src/plugins/datasources/schemas/datasourceCache.schema.js +3 -0
  129. package/src/plugins/datasources/schemas/datasourcePlugin.schema.js +37 -0
  130. package/src/plugins/datasources/schemas/datasourcePluginOptions.schema.js +64 -0
  131. package/src/plugins/datasources/schemas/index.js +2 -0
  132. package/src/plugins/datasources/schemas/manifest.schema.js +8 -0
  133. package/src/plugins/datasources/schemas/results.schema.js +126 -0
  134. package/src/plugins/datasources/sub-source-vars.js +55 -0
  135. package/src/plugins/datasources/sub-source-vars.spec.js +46 -0
  136. package/src/plugins/datasources/types.d.ts +53 -0
  137. package/src/plugins/datasources/updateManifest.js +115 -0
  138. package/src/plugins/datasources/updateManifest.spec.js +200 -0
  139. package/src/plugins/datasources/wrapSimpleConnector.js +95 -0
  140. package/src/plugins/datasources/writeSourceConfig.js +60 -0
  141. package/src/plugins/index.js +2 -0
  142. package/src/plugins/layouts/copyMethods/index.js +10 -0
  143. package/src/plugins/layouts/copyMethods/svelte.js +53 -0
  144. package/src/plugins/layouts/copyMethods/sveltekit.js +75 -0
  145. package/src/plugins/layouts/copyToLayout.js +106 -0
  146. package/src/plugins/layouts/loadLayoutPlugin.js +23 -0
  147. package/src/plugins/loadPluginPackage.js +77 -0
  148. package/src/plugins/schemas/index.js +1 -0
  149. package/src/plugins/schemas/plugin-config.schema.js +41 -0
  150. package/src/plugins/schemas/plugin-config.schema.spec.js +21 -0
  151. package/src/plugins/schemas/plugin-package.schema.js +154 -0
  152. package/src/plugins/schemas/plugin-package.schema.spec.js +30 -0
  153. package/src/query-builder.d.ts +1 -0
  154. package/src/query-builder.js +1 -0
  155. package/src/types/duckdb-wellknown.d.ts +35 -0
  156. package/src/types/html-attributes.ts +13 -0
  157. package/src/types/index.d.ts +18 -0
  158. package/src/types/mosaic-sql.d.ts +27 -0
  159. package/src/types/sveltekit-autoimport.d.ts +13 -0
  160. package/src/types/virtuals.d.ts +113 -0
  161. package/src/types.d.ts +1 -0
  162. package/src/usql/index.d.ts +4 -0
  163. package/src/usql/index.js +3 -0
  164. package/src/usql/query/Query.js +1391 -0
  165. package/src/usql/query/Query.spec.js +827 -0
  166. package/src/usql/query/queryScore.js +92 -0
  167. package/src/usql/query/queryScore.spec.js +26 -0
  168. package/src/usql/query/sterilizeQuery.js +89 -0
  169. package/src/usql/query/sterilizeQuery.spec.js +172 -0
  170. package/src/usql/setTrackProxy/setTrackProxy.js +80 -0
  171. package/src/usql/setTrackProxy/setTrackProxy.spec.js +166 -0
  172. package/src/usql/types.ts +86 -0
  173. package/src/usql/utilities/duckdbSerialize.js +29 -0
  174. package/src/usql/utilities/index.js +2 -0
  175. package/src/usql/utilities/resolveMaybePromise.js +30 -0
  176. package/src/utils/batchUp.js +22 -0
  177. package/src/utils/batchUp.spec.js +69 -0
  178. package/src/utils/browserDebounce.js +16 -0
  179. package/src/utils/index.js +7 -0
  180. package/src/utils/svelte/addBasePath.js +74 -0
  181. package/src/utils/svelte/addBasePath.spec.js +108 -0
  182. package/src/utils/svelte/index.js +13 -0
  183. package/src/utils/svelte/inputs.js +138 -0
  184. package/tsconfig.json +22 -0
  185. package/vite.config.js +3 -0
  186. package/vitest.config.js +15 -0
@@ -0,0 +1,20 @@
1
+ import { createEvidenceConfig } from '../createEvidenceConfig.js';
2
+
3
+ /** @type {import("@brianmd/citty").CommandDef} */
4
+ export const createConfig = {
5
+ meta: {
6
+ name: 'create',
7
+ description: 'Bootstraps an evidence configuration file'
8
+ },
9
+ args: {
10
+ update: {
11
+ type: 'boolean',
12
+ description: 'Add any missing fields to the evidence configuration file',
13
+ default: false
14
+ }
15
+ },
16
+ async run({ args }) {
17
+ const configPath = await createEvidenceConfig(Boolean(args.update));
18
+ console.log(`Configuration file written to ${configPath}`);
19
+ }
20
+ };
@@ -0,0 +1,12 @@
1
+ import { createConfig } from './create.js';
2
+
3
+ /** @type {import("@brianmd/citty").CommandDef} */
4
+ export const config = {
5
+ meta: {
6
+ name: 'config',
7
+ description: 'Configure Evidence, add or remove component plugins and datasources'
8
+ },
9
+ subCommands: {
10
+ create: createConfig
11
+ }
12
+ };
@@ -0,0 +1,51 @@
1
+ import { findFile } from 'pkg-types';
2
+ import yaml from 'yaml';
3
+ import fs from 'fs/promises';
4
+ import { getEvidenceConfig } from './getEvidenceConfig.js';
5
+ import { EvidenceError } from '../lib/EvidenceError.js';
6
+ import path from 'path';
7
+
8
+ /**
9
+ * @param {boolean} [update = false]
10
+ * @returns {Promise<string>}
11
+ */
12
+ export const createEvidenceConfig = async (update) => {
13
+ const configPath = await findFile('evidence.config.yaml').catch(() =>
14
+ path.join(process.cwd(), 'evidence.config.yaml')
15
+ );
16
+
17
+ let existingConfig;
18
+ try {
19
+ existingConfig = getEvidenceConfig();
20
+ } catch {
21
+ /* Do nothing */
22
+ }
23
+
24
+ const config = {
25
+ plugins: {
26
+ components: {},
27
+ datasources: {}
28
+ }
29
+ };
30
+
31
+ if (existingConfig) {
32
+ if (!update) {
33
+ throw new EvidenceError(
34
+ 'Refusing to create evidence configuration file. Configuration file already exists.',
35
+ 'Run this command again with --update to add any missing fields to your existing configuration'
36
+ );
37
+ }
38
+ Object.assign(config, existingConfig);
39
+ }
40
+
41
+ const comments = [
42
+ 'This file was automatically generated by the Evidence command line',
43
+ 'To easily configure Evidence, use `npx evidence config`'
44
+ ];
45
+
46
+ const content = `# ${comments.join('\n# ')}\n\n${yaml.stringify(config)}`;
47
+
48
+ await fs.writeFile(configPath, content);
49
+
50
+ return configPath;
51
+ };
@@ -0,0 +1,60 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import chalk from 'chalk';
4
+ import yaml from 'yaml';
5
+ import { EvidenceConfigSchema } from './schemas/config.schema.js';
6
+ import { EvidenceError } from '../lib/EvidenceError.js';
7
+ import { getEvidenceConfigLegacy } from './getEvidenceConfig.legacy.js';
8
+ import { projectRoot } from '../lib/projectPaths.js';
9
+ import z from 'zod';
10
+ import { unnestZodError } from '../lib/unnest-zod-error.js';
11
+
12
+ /** @typedef {import("zod").AnyZodObject} AnyZodObject */
13
+ /** @typedef {z.infer<typeof EvidenceConfigSchema>} EvidenceConfig */
14
+
15
+ /**
16
+ * @template {z.ZodSchema} [Schema=EvidenceConfigSchema]
17
+ * @param {Schema} [schema]
18
+ * @returns {import("zod").infer<Schema>}
19
+ */
20
+ export const getEvidenceConfig = (
21
+ // The typecasting here is necessary because Typescript
22
+ // https://stackoverflow.com/a/59363875/9080819
23
+ // Technically, this function could be misused by passing a template type
24
+ // that doesn't match the default parameter, but that shouldn't happen
25
+ // with normal usage (especially since we're using JS, not TS directly)
26
+ schema = /** @type {Schema} */ (/** @type {unknown} */ (EvidenceConfigSchema)),
27
+ mergeLegacy = true
28
+ ) => {
29
+ try {
30
+ const configFilePath = path.join(projectRoot, 'evidence.config.yaml');
31
+ const configFileContent = fs.readFileSync(configFilePath, 'utf-8');
32
+ const result = yaml.parse(configFileContent.replaceAll(/($|\s)(@.+):/g, '$1"$2":'));
33
+
34
+ if (mergeLegacy) {
35
+ const legacyConfig = getEvidenceConfigLegacy();
36
+ return schema.parse({ ...legacyConfig, ...result });
37
+ }
38
+
39
+ return schema.parse(result);
40
+ } catch (e) {
41
+ if (
42
+ e instanceof Error &&
43
+ (e.message.startsWith('Cannot find matching evidence.config.yaml') ||
44
+ e.message.includes('no such file or directory'))
45
+ ) {
46
+ return getEvidenceConfigLegacy();
47
+ }
48
+
49
+ if (e instanceof z.ZodError) {
50
+ const errors = Object.entries(unnestZodError(e))
51
+ .map(([path, error]) => ` ${chalk.gray(path)}: ${chalk.redBright(error)}`)
52
+ .join('\n');
53
+ console.error(`${chalk.red(`Invalid evidence.config.yaml file:`)}\n${errors}`);
54
+ } else {
55
+ console.log(e);
56
+ }
57
+
58
+ throw new EvidenceError('Unknown Error while loading Evidence Configuration', [], { cause: e });
59
+ }
60
+ };
@@ -0,0 +1,27 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import yaml from 'yaml';
4
+ import { EvidenceError } from '../lib/EvidenceError.js';
5
+ import { EvidenceConfigSchema } from './schemas/config.schema.js';
6
+ import { projectRoot } from '../lib/projectPaths.js';
7
+ import chalk from 'chalk';
8
+
9
+ export const getEvidenceConfigLegacy = () => {
10
+ let fileContents;
11
+ try {
12
+ const filepath = path.join(projectRoot, 'evidence.plugins.yaml');
13
+ fileContents = fs.readFileSync(filepath, 'utf-8');
14
+ console.warn(
15
+ `\n\n⚠ ${chalk.yellow('evidence.plugins.yaml has been deprecated')} ⚠\nSupport will be removed in a future update. evidence.config.yaml should be used instead.\n\nSee here for an example evidence.config.yaml file:\nhttps://github.com/evidence-dev/template/blob/main/evidence.config.yaml \n`
16
+ );
17
+ } catch (e) {
18
+ // Do nothing if `evidence.plugins.yaml` isnt found. `evidence.plugins.yaml` is deprecated and `evidence.config.yaml` should be used instead.
19
+ return;
20
+ }
21
+
22
+ const result = yaml.parse(fileContents.replaceAll(/($|\s)(@.+):/g, '$1"$2":'));
23
+
24
+ const { success, data, error } = EvidenceConfigSchema.safeParse({ plugins: result });
25
+ if (!success) throw new EvidenceError(`Invalid evidence.plugins.yaml file detected: ${error}`);
26
+ return data;
27
+ };
@@ -0,0 +1 @@
1
+ export * from './getEvidenceConfig.js';
@@ -0,0 +1,11 @@
1
+ import { z } from 'zod';
2
+ import { PluginConfigSchema } from '../../plugins/schemas/plugin-config.schema.js';
3
+ import { DeploymentConfigSchema } from './deployment.schema.js';
4
+
5
+ export const EvidenceConfigSchema = z.object({
6
+ layout: z.string().or(z.literal(false).default(false)).optional(),
7
+ plugins: PluginConfigSchema,
8
+ deployment: DeploymentConfigSchema.optional().default({})
9
+ });
10
+
11
+ /** @typedef {z.infer<typeof EvidenceConfigSchema>} EvidenceConfig */
@@ -0,0 +1,18 @@
1
+ import { z } from 'zod';
2
+
3
+ export const DeploymentConfigSchema = z.object({
4
+ basePath: z
5
+ .string()
6
+ .optional()
7
+ .default('')
8
+ .refine((value) => !value || value.startsWith('/'), { message: 'basePath must start with /' }),
9
+ // A route parameter, e.g. orgslug: pages that have it load data/ and api/ from
10
+ // <basePath>/<value>/ and prerender their query results there, so each value's
11
+ // data can be served from its own prefix
12
+ dataScope: z
13
+ .string()
14
+ .optional()
15
+ .refine((value) => !value || /^[A-Za-z_][A-Za-z0-9_]*$/.test(value), {
16
+ message: 'dataScope must be a route parameter name'
17
+ })
18
+ });
@@ -0,0 +1,34 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { DeploymentConfigSchema } from './deployment.schema';
3
+
4
+ describe('DeploymentConfigSchema', () => {
5
+ describe('basePath', () => {
6
+ it('should allow undefined', () => {
7
+ const config = {
8
+ basePath: undefined
9
+ };
10
+ const { success, error } = DeploymentConfigSchema.safeParse(config);
11
+ console.log({ error });
12
+ expect(success).toBeTruthy();
13
+ });
14
+ it('should default to empty string', () => {
15
+ const config = {};
16
+ const { data } = DeploymentConfigSchema.safeParse(config);
17
+ expect(data.basePath).toBe('');
18
+ });
19
+ it('should not allow protocol', () => {
20
+ const config = {
21
+ basePath: 'http://example.com'
22
+ };
23
+ const { success } = DeploymentConfigSchema.safeParse(config);
24
+ expect(success).toBeFalsy();
25
+ });
26
+ it('should not allow path that doesnt start with /', () => {
27
+ const config = {
28
+ basePath: 'my-base-path'
29
+ };
30
+ const { success } = DeploymentConfigSchema.safeParse(config);
31
+ expect(success).toBeFalsy();
32
+ });
33
+ });
34
+ });
@@ -0,0 +1,25 @@
1
+ import { findFile } from 'pkg-types';
2
+ import yaml from 'yaml';
3
+ import fs from 'fs/promises';
4
+ import path from 'path';
5
+
6
+ /**
7
+ * @param {import("zod").infer<typeof import("./schemas/config.schema.js").EvidenceConfigSchema>} cfg
8
+ * @returns {Promise<string>}
9
+ */
10
+ export const updateEvidenceConfig = async (cfg) => {
11
+ const configPath = await findFile('evidence.config.yaml').catch(() =>
12
+ path.join(process.cwd(), 'evidence.config.yaml')
13
+ );
14
+
15
+ const comments = [
16
+ 'This file was automatically generated by the Evidence command line',
17
+ 'To easily configure Evidence, use `npx evidence config`'
18
+ ];
19
+
20
+ const content = `# ${comments.join('\n# ')}\n\n${yaml.stringify(cfg)}`;
21
+
22
+ await fs.writeFile(configPath, content);
23
+
24
+ return configPath;
25
+ };
@@ -0,0 +1,8 @@
1
+ import { runMain } from '@brianmd/citty';
2
+ import { rootCli } from './cli.root.js';
3
+
4
+ /**
5
+ * This function is provided to create a compatibility layer between the legacy Evidence CLI and the new SDK CLI
6
+ * @returns {Promise<void>}
7
+ */
8
+ export const cli = () => runMain(rootCli);
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @extends {Error}
3
+ * @property {string[]} context
4
+ * @property {any} metadata
5
+ */
6
+ export class EvidenceError extends Error {
7
+ /**
8
+ * @param {string} message
9
+ * @param {string[] | string} [context]
10
+ * @param {ErrorOptions} [opts]
11
+ * @param {any} [metadata]
12
+ */
13
+ constructor(message, context, opts, metadata) {
14
+ super(message, opts);
15
+
16
+ this.context = Array.isArray(context) ? context : [context ?? ''];
17
+ if (!context) this.context = /** @type {string[]} */ ([]);
18
+ this.#metadata = metadata;
19
+ if (!Array.isArray(this.context)) this.context = [];
20
+ }
21
+
22
+ /** @type {string[]} */
23
+ context = [];
24
+
25
+ /** @type {any} */
26
+ #metadata;
27
+
28
+ set metadata(data) {
29
+ this.#metadata = data;
30
+ }
31
+ get metadata() {
32
+ if (!this.#metadata) this.#metadata = {};
33
+ return this.#metadata;
34
+ }
35
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Encodes a value or an array of values into Base64 recursively.
3
+ * @param {*} v - The value or array of values to encode.
4
+ * @returns {*} - The encoded value or array of values.
5
+ */
6
+ export const encodeBase64Deep = (v) => {
7
+ if (Array.isArray(v)) {
8
+ const mapped = v.map(encodeBase64Deep);
9
+ return mapped;
10
+ } else if (typeof v === 'string') {
11
+ return btoa(v);
12
+ } else if (v && v.constructor === Object) {
13
+ // bare object
14
+ return Object.fromEntries(
15
+ Object.entries(v).map(
16
+ /**
17
+ * Maps each key-value pair of the object.
18
+ * @param {[string, object]} entry - The key-value pair.
19
+ * @returns {[string, object|string]} - The encoded key-value pair.
20
+ */
21
+ ([k, v]) => [k, encodeBase64Deep(v)]
22
+ )
23
+ );
24
+ } else {
25
+ return v;
26
+ }
27
+ };
28
+
29
+ /**
30
+ * Dencodes a value or an array of values from Base64 recursively.
31
+ * @param {*} v - The value or array of values to encode.
32
+ * @returns {*} - The encoded value or array of values.
33
+ */
34
+ export const decodeBase64Deep = (v) => {
35
+ if (Array.isArray(v)) {
36
+ const mapped = v.map(decodeBase64Deep);
37
+ return mapped;
38
+ } else if (typeof v === 'string') {
39
+ return atob(v);
40
+ } else if (v && v.constructor === Object) {
41
+ // bare object
42
+ return Object.fromEntries(
43
+ Object.entries(v).map(
44
+ /**
45
+ * Maps each key-value pair of the object.
46
+ * @param {[string, object]} entry - The key-value pair.
47
+ * @returns {[string, object|string]} - The encoded key-value pair.
48
+ */
49
+ ([k, v]) => [k, decodeBase64Deep(v)]
50
+ )
51
+ );
52
+ } else {
53
+ return v;
54
+ }
55
+ };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @param {string} importName
3
+ * @param {string} sourcePackage
4
+ * @param {string} content
5
+ * @returns
6
+ */
7
+ export const checkImport = (importName, sourcePackage, content) => {
8
+ const regex = new RegExp(
9
+ `import {?.*${importName}.*}? from ["']${sourcePackage.replaceAll('$', '\\$')}["']`
10
+ );
11
+ return regex.test(content);
12
+ };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Renames the '_errors' property to 'errors' in the given object and its nested objects recursively.
3
+ * It also removes any empty errors arrays
4
+ *
5
+ * @param {any} obj - The object to rename the '_errors' property in.
6
+ * @return {Object} The object with the renamed property.
7
+ */
8
+ export function cleanZodErrors(obj) {
9
+ for (const key in obj) {
10
+ if (typeof obj[key] === 'object') {
11
+ cleanZodErrors(obj[key]); // recursively traverse nested objects
12
+ }
13
+ if (key === '_errors') {
14
+ if (obj['_errors'].length) {
15
+ // De-duplicate
16
+ obj['errors'] = Array.from(new Set(obj['_errors']));
17
+ }
18
+ delete obj['_errors'];
19
+ }
20
+ }
21
+ return obj;
22
+ }
@@ -0,0 +1,33 @@
1
+ import chalk from 'chalk';
2
+ import { logFatal } from '../tokens.js';
3
+ import { EvidenceError } from '../EvidenceError.js';
4
+ import { isDebug } from '../debug.js';
5
+
6
+ /**
7
+ *
8
+ * @param {string | Error | EvidenceError} message
9
+ * @param {string | string[]} [detail] String message or an array of lines
10
+ */
11
+ export const cmdFail = (message, detail) => {
12
+ if (message instanceof EvidenceError) {
13
+ detail = message.context;
14
+ message = message.message;
15
+ } else if (message instanceof Error) {
16
+ if (isDebug()) detail = message.stack;
17
+ message = message.message;
18
+ }
19
+ console.error(`${logFatal} ${chalk.red(message)}`);
20
+ if (detail) {
21
+ let detailMsg = '';
22
+
23
+ const newline = '\n' + ' '.repeat(6);
24
+ if (Array.isArray(detail)) {
25
+ detailMsg = detail.join(newline);
26
+ } else {
27
+ detailMsg = detail.split('\n').join(newline);
28
+ }
29
+
30
+ console.error(` ${chalk.dim(detailMsg)}`);
31
+ }
32
+ process.exit(1);
33
+ };
@@ -0,0 +1,44 @@
1
+ import { getEvidenceConfig } from '../../configuration/getEvidenceConfig.js';
2
+ import { cmdFail } from './cmdFail.js';
3
+ import chalk from 'chalk';
4
+
5
+ /**
6
+ * @param {string} cmdName
7
+ * @returns {import("@brianmd/citty").CommandDef}
8
+ */
9
+ export const deprecationNotice = (cmdName) => ({
10
+ meta: { name: cmdName },
11
+ run: () => {
12
+ throw new Error(`${cmdName} has been deprecated`);
13
+ }
14
+ });
15
+
16
+ /**
17
+ * @param {string} cmdName
18
+ * @param {import("@brianmd/citty").CommandDef} cmd
19
+ * @param {boolean} [requiresLayout = false]
20
+ * @returns {import("@brianmd/citty").CommandDef}
21
+ */
22
+ export const evidenceProjectOnlyNotice = (cmdName, cmd, requiresLayout) => {
23
+ return {
24
+ ...cmd,
25
+ run(...args) {
26
+ /** @type {boolean} */
27
+ let isEvidenceProject = false;
28
+
29
+ const config = getEvidenceConfig();
30
+ if (config) isEvidenceProject = true;
31
+ if (config && requiresLayout && !config.layout) isEvidenceProject = false;
32
+
33
+ if (isEvidenceProject) return cmd.run?.(...args);
34
+ else
35
+ cmdFail(
36
+ `${chalk.bold(`\`evidence ${cmdName}\``)} is only available in Evidence projects.`,
37
+ [
38
+ 'If this is meant to be an Evidence project',
39
+ `please create an evidence.config.yaml with ${chalk.bold(`\`evidence config create\``)}`
40
+ ]
41
+ );
42
+ }
43
+ };
44
+ };
@@ -0,0 +1,40 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ import chalk from 'chalk';
4
+
5
+ /** @type {Set<() => unknown>} */
6
+ const enableFns = new Set();
7
+ /** @param {() => unknown} fn */
8
+ export const onEnableDebug = (fn) => {
9
+ if (isDebug()) fn();
10
+ else enableFns.add(fn);
11
+ };
12
+
13
+ export const enableDebug = () => {
14
+ if (typeof process === 'undefined') {
15
+ throw new Error('Debug must be enabled server-side');
16
+ }
17
+ console.debug(chalk.bold.yellow('Evidence running with debug logging'));
18
+ process.env.EVIDENCE_DEBUG = 'true';
19
+ process.env.VITE_EVIDENCE_DEBUG = 'true';
20
+ process.env.VITE_PUBLIC_EVIDENCE_DEBUG = 'true';
21
+
22
+ enableFns.forEach((fn) => fn());
23
+ };
24
+
25
+ export const isDebug = () => {
26
+ if (typeof process !== 'undefined')
27
+ return Boolean(
28
+ process.env.EVIDENCE_DEBUG ||
29
+ process.env.VITE_PUBLIC_EVIDENCE_DEBUG ||
30
+ (process.env.NODE_ENV === 'test' && !process.env.EVIDENCE_DISABLE_TEST_DEBUG)
31
+ );
32
+ if (typeof import.meta.env !== 'undefined')
33
+ return (
34
+ Boolean(import.meta.env.EVIDENCE_DEBUG) || Boolean(import.meta.env.VITE_PUBLIC_EVIDENCE_DEBUG)
35
+ );
36
+ };
37
+ export const disableDebug = () => {
38
+ delete process.env.EVIDENCE_DEBUG;
39
+ delete process.env.VITE_PUBLIC_EVIDENCE_DEBUG;
40
+ };
@@ -0,0 +1,21 @@
1
+ /*
2
+
3
+ The Evidence SDK is designed to be used in many environments to prevent
4
+ re-writing the same logic many times. With this in mind, there are
5
+ several user interfaces where the same flow may occur (e.g. updating
6
+ source configurations). In the CLI, a user may be prompted for some
7
+ input using clack, whereas in the VS Code extension, they may be
8
+ prompted by the native UI.
9
+
10
+ We want to provide a scaffolding for common workflow / ui patterns that
11
+ can be provided by the _consumer_ of the flow to define how the user
12
+ will interact with it. Classic dependency inversion!
13
+ https://en.wikipedia.org/wiki/Dependency_inversion_principle
14
+
15
+ */
16
+
17
+ export type EvidenceLoadIndicator = {
18
+ start: (msg?: string) => void;
19
+ stop: (msg?: string) => void;
20
+ message: (msg?: string) => void;
21
+ };
@@ -0,0 +1,28 @@
1
+ import fs from 'fs/promises';
2
+ import { EvidenceError } from './EvidenceError.js';
3
+
4
+ /**
5
+ *
6
+ * @param {string} from
7
+ * @param {string} to
8
+ * @returns {Promise<void>}
9
+ */
10
+ export const forceLink = async (from, to) => {
11
+ /** @type {import("fs").Stats | false} */
12
+ const toStat = await fs.stat(to).catch(() => false);
13
+ /** @type {import("fs").Stats | false} */
14
+ const fromStat = await fs.stat(from).catch(() => false);
15
+ if (!fromStat) {
16
+ throw new EvidenceError(`Failed to create symlink, ${from} does not exist`);
17
+ }
18
+ if (toStat) {
19
+ if (toStat.isDirectory()) {
20
+ await fs.rm(to, { recursive: true, force: true });
21
+ } else if (toStat.isSymbolicLink()) {
22
+ await fs.unlink(to);
23
+ } else {
24
+ throw new EvidenceError(`Failed to create symlink ${to} is not a link or a directory`);
25
+ }
26
+ }
27
+ await fs.symlink(from, to, 'dir');
28
+ };
@@ -0,0 +1,70 @@
1
+ import { detailedDiff } from 'deep-object-diff';
2
+
3
+ /** @typedef {import("./types.js").Diff} Diff */
4
+
5
+ /**
6
+ * @template {Object} [T=any]
7
+ */
8
+ export class History {
9
+ /** @type {Diff[]} */
10
+ #history = [];
11
+ get generations() {
12
+ return [...this.#history];
13
+ }
14
+ constructor() {}
15
+
16
+ /** @type {T | {}} */
17
+ #prev = {};
18
+ /**
19
+ * @param {T} value
20
+ */
21
+ push(value) {
22
+ /** @param {Object} o */
23
+ const organize = (o) => {
24
+ let entries = Object.entries(o);
25
+ entries.sort((a, b) => a[0].localeCompare(b[0]));
26
+ const newObject = Object.fromEntries(entries);
27
+ return JSON.parse(JSON.stringify(newObject));
28
+ };
29
+
30
+ const pre = organize(this.#prev);
31
+ const post = organize(value);
32
+ const diff = detailedDiff(pre, post);
33
+ this.#history.push({
34
+ ...diff,
35
+ before: pre,
36
+ after: post,
37
+ asof: new Date()
38
+ });
39
+ this.#prev = post;
40
+ this.publish();
41
+ }
42
+
43
+ ////////////////////////////////////
44
+ /// < Implement Store Contract > ///
45
+ ////////////////////////////////////
46
+ /** @type {Set<(v: Diff[]) => void>} */
47
+ #subscribers = new Set();
48
+
49
+ /**
50
+ * @param {(v: Diff[]) => void} fn
51
+ * @returns {() => void} Unsubscribe function
52
+ */
53
+ subscribe = (fn) => {
54
+ this.#subscribers.add(fn);
55
+ fn(this.generations);
56
+ return () => this.#subscribers.delete(fn);
57
+ };
58
+
59
+ #publishIdx = 0;
60
+ /**
61
+ * @protected
62
+ */
63
+ publish = () => {
64
+ if (this.#publishIdx++ > 100000) throw new Error('History published too many times.');
65
+ this.#subscribers.forEach((fn) => fn(this.generations));
66
+ };
67
+ //////////////////////////////////////
68
+ /// </ Implement Store Contract /> ///
69
+ //////////////////////////////////////
70
+ }
@@ -0,0 +1,8 @@
1
+ export type Diff = {
2
+ before: any;
3
+ after: any;
4
+ added: any;
5
+ deleted: any;
6
+ updated: any;
7
+ asof: Date;
8
+ };
@@ -0,0 +1,16 @@
1
+ import { findFile } from 'pkg-types';
2
+ import fs from 'fs/promises';
3
+
4
+ /**
5
+ * @param {string} dirname
6
+ * @returns {Promise<string>}
7
+ */
8
+ export const findDirectory = (dirname) => {
9
+ return findFile(dirname, {
10
+ test: (filename) =>
11
+ fs
12
+ .stat(filename)
13
+ .then((stat) => stat.isDirectory())
14
+ .catch(() => false)
15
+ });
16
+ };