@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,86 @@
1
+ import type { Query as QueryBuilder } from '@uwdata/mosaic-sql';
2
+ // This file has a .ts instead of .d.ts to ensure that it is included in the built types.
3
+ // It should not be used as anything other than a .d.ts file
4
+ import type { DescribeResultRow } from '../types/duckdb-wellknown.d.ts';
5
+ import type { ChainableSharedPromise, Query, QueryValue } from './query/Query.js';
6
+
7
+ export type EventHandler<
8
+ Events extends Record<string, any> = {},
9
+ Event extends keyof Events = keyof Events
10
+ > = (value: Events[Event], event: Event) => void;
11
+
12
+ export type EventEmitter<Events extends Record<string, any> = {}> = {
13
+ addEventListener<Event extends keyof Events>(event: Event, handler: EventHandler<Events>): void;
14
+ removeEventListener<Event extends keyof Events>(
15
+ event: Event,
16
+ handler: EventHandler<Events>
17
+ ): void;
18
+ on<Event extends keyof Events>(event: Event, handler: EventHandler<Events>): void;
19
+ off<Event extends keyof Events>(event: Event, handler: EventHandler<Events>): void;
20
+ };
21
+
22
+ export type EventMap<Events extends Record<string, any>> = {
23
+ [Event in keyof Events]: Set<EventHandler<Events, Event>>;
24
+ };
25
+
26
+ export type QueryResultRow = Record<string, number | string | Date | boolean | null>;
27
+ export type MaybePromise<T> = Promise<T> | T;
28
+
29
+ export type Runner<RowType extends QueryResultRow = QueryResultRow> = (
30
+ query: string,
31
+ query_name: string
32
+ ) => MaybePromise<RowType[]>;
33
+ export type Subscriber<T> = (value: T) => unknown;
34
+
35
+ export type QueryOpts<RowType extends QueryResultRow = QueryResultRow> = {
36
+ initialData?: RowType[];
37
+ /**
38
+ * @deprecated Use Query.reactive instead
39
+ */
40
+ initialDataDirty?: boolean;
41
+
42
+ knownColumns?: DescribeResultRow[];
43
+
44
+ initialError?: Error;
45
+ id?: string;
46
+ disableCache?: boolean;
47
+ autoScore?: boolean;
48
+ /**
49
+ * When true, this prevents the query from ever fetching or presenting data.
50
+ **/
51
+ noResolve?: boolean;
52
+ };
53
+
54
+ export type QueryReactivityOpts<T extends QueryResultRow = QueryResultRow> = {
55
+ loadGracePeriod?: number;
56
+ callback: (v: QueryValue<T>) => void;
57
+ execFn: Runner<T>;
58
+ };
59
+
60
+ export interface CreateQuery<RowType extends QueryResultRow = QueryResultRow> {
61
+ (
62
+ query: QueryBuilder | string,
63
+ executeQuery: Runner,
64
+ opts: QueryOpts<RowType>,
65
+ _?: never
66
+ ): QueryValue<RowType>;
67
+
68
+ /**
69
+ * @deprecated id has been moved to the options argument
70
+ */
71
+ (
72
+ query: QueryBuilder | string,
73
+ executeQuery: Runner,
74
+ id?: string,
75
+ opts?: Omit<QueryOpts<RowType>, 'id'>
76
+ ): QueryValue<RowType>;
77
+ }
78
+
79
+ export type LengthResultRow = { rowCount: number };
80
+
81
+ export type MaybeAliasedCol = string | { col: string; as: string };
82
+
83
+ export type QueryDebugPayload = {
84
+ raw: Query<any>;
85
+ proxied: QueryValue<any>;
86
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @typedef {Object} DuckdbSerializeOpts
3
+ * @property {boolean} [serializeStrings=true]
4
+ */
5
+ /**
6
+ * Serializes a value into a format suitable for use in a DuckDB query.
7
+ *
8
+ * @param {any} value - The value to be serialized.
9
+ * @return {string} The serialized value.
10
+ */
11
+ export const duckdbSerialize = (value, opts = { serializeStrings: true }) => {
12
+ if (value == null) return 'null';
13
+
14
+ if (typeof value === 'string') {
15
+ if (opts.serializeStrings !== false) return `'${value.replaceAll("'", "''")}'`;
16
+ else {
17
+ return value;
18
+ }
19
+ }
20
+
21
+ if (typeof value === 'number' || typeof value === 'bigint' || typeof value === 'boolean')
22
+ return String(value);
23
+
24
+ if (value instanceof Date) return `'${value.toISOString()}'::TIMESTAMP_MS`;
25
+
26
+ if (Array.isArray(value)) return `[${value.map((x) => duckdbSerialize(x, opts)).join(', ')}]`;
27
+
28
+ return JSON.stringify(value);
29
+ };
@@ -0,0 +1,2 @@
1
+ export * from './duckdbSerialize.js';
2
+ export * from './resolveMaybePromise.js';
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @template T
3
+ * @template [Returns=void]
4
+ * @param {(v: T, isPromise: boolean) => import("../types.js").MaybePromise<Returns>} handler
5
+ * @param {import("../types.js").MaybePromise<T> | (() => import("../types.js").MaybePromise<T>)} value
6
+ * @param {(e: Error, isPromise: boolean) => import("../types.js").MaybePromise<Returns>} [onError]
7
+ */
8
+ export const resolveMaybePromise = (handler, value, onError) => {
9
+ try {
10
+ const v =
11
+ typeof value === 'function'
12
+ ? /** @type {() => import("../types.js").MaybePromise<T>} */ (value)()
13
+ : value;
14
+ if (v instanceof Promise) {
15
+ return v
16
+ .then((v) => handler(v, true))
17
+ .catch((e) => {
18
+ const error = e instanceof Error ? e : new Error('Unknown Error', { cause: e });
19
+ if (onError) return onError(error, true);
20
+ throw error;
21
+ });
22
+ } else {
23
+ return handler(v, false);
24
+ }
25
+ } catch (e) {
26
+ const error = e instanceof Error ? e : new Error('Unknown Error', { cause: e });
27
+ if (onError) return onError(error, false);
28
+ else throw error;
29
+ }
30
+ };
@@ -0,0 +1,22 @@
1
+ import { browserDebounce } from './browserDebounce.js';
2
+
3
+ /**
4
+ * @template Input
5
+ * @param {((inputs: Input[]) => unknown) | ((...i: (Input[] | Input)[]) => unknown)} fn
6
+ * @param {number} [timeout=200]
7
+ * @returns {(i: Input) => unknown}
8
+ */
9
+ export const batchUp = (fn, timeout = 200) => {
10
+ /** @type {Input[]} */
11
+ const collected = [];
12
+
13
+ const finalize = browserDebounce(() => {
14
+ fn([...collected]); // clone collected array before resetting it
15
+ collected.length = 0;
16
+ }, timeout);
17
+
18
+ return (...i) => {
19
+ collected.push(...i);
20
+ return finalize();
21
+ };
22
+ };
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
6
+ import { batchUp } from './batchUp.js';
7
+
8
+ describe('batchUp', () => {
9
+ beforeEach(() => {
10
+ vi.useFakeTimers();
11
+ });
12
+ afterEach(() => {
13
+ vi.useRealTimers();
14
+ });
15
+ it('should not call the callback if the return function is never called', () => {
16
+ const callback = vi.fn();
17
+ batchUp(callback);
18
+ vi.advanceTimersByTime(201);
19
+ expect(callback).toHaveBeenCalledTimes(0);
20
+ });
21
+ it(
22
+ 'should debounce the callback',
23
+ () => {
24
+ // Currently skipped because debounce has been disabled
25
+ const callback = vi.fn();
26
+ const fn = batchUp(callback);
27
+ fn();
28
+ vi.advanceTimersByTime(199);
29
+ expect(callback).not.toHaveBeenCalled();
30
+ fn();
31
+ vi.advanceTimersByTime(200);
32
+ expect(callback).toHaveBeenCalledTimes(1);
33
+ },
34
+ { skip: true }
35
+ );
36
+ it(
37
+ 'should pass any provided arguments to the callback',
38
+ () => {
39
+ // Currently skipped because debounce has been disabled
40
+ const callback = vi.fn();
41
+ const fn = batchUp(callback);
42
+ fn(1);
43
+ fn(2);
44
+ fn(3);
45
+ vi.advanceTimersByTime(200);
46
+ expect(callback).toHaveBeenCalledWith([1, 2, 3]);
47
+ },
48
+ { skip: true }
49
+ );
50
+
51
+ it('should be reusable', async () => {
52
+ const callback = vi.fn();
53
+ const fn = batchUp(callback);
54
+
55
+ fn(1);
56
+ await vi.advanceTimersByTimeAsync(200);
57
+ expect(callback).toHaveBeenCalledTimes(1);
58
+ expect(callback).toHaveBeenCalledWith([1]);
59
+
60
+ fn(2);
61
+ await vi.advanceTimersByTimeAsync(200);
62
+ expect(callback).toHaveBeenCalledWith([2]);
63
+
64
+ fn(3);
65
+ await vi.advanceTimersByTimeAsync(200);
66
+ expect(callback).toHaveBeenCalledTimes(3);
67
+ expect(callback).toHaveBeenCalledWith([3]);
68
+ });
69
+ });
@@ -0,0 +1,16 @@
1
+ // import { debounce } from 'perfect-debounce';
2
+
3
+ /** @type {typeof import("perfect-debounce").debounce}*/
4
+ export function browserDebounce(
5
+ fn
6
+ // wait, options
7
+ ) {
8
+ // 🚩 This will get undone with the DAG PR, for now this is required to prevent rendering jank
9
+ return (...args) => Promise.resolve(fn(...args));
10
+ // if (typeof window === 'undefined') {
11
+ // // debounce()() returns a promise
12
+ // return (...args) => Promise.resolve(fn(...args));
13
+ // } else {
14
+ // return debounce(fn, wait, options);
15
+ // }
16
+ }
@@ -0,0 +1,7 @@
1
+ export { EvidenceError } from '../lib/EvidenceError.js';
2
+ export * from './batchUp.js';
3
+ export * from '../lib/sharedPromise.js';
4
+ export * from '../lib/history/index.js';
5
+ export * from '../lib/debug.js';
6
+ export * from './browserDebounce.js';
7
+ export * from '../lib/strict.js';
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Adjusts a path to include the configured base path
3
+ * Ignores undefined, and absolute URLs
4
+ * @template T
5
+ * @param {T} path
6
+ * @param {import("../../configuration/schemas/config.schema.js").EvidenceConfig} config
7
+ * @example addBasePath('http://localhost:3000/test') // 'http://localhost:3000/test'
8
+ * @example addBasePath('/test') // '/base/test'
9
+ * @example addBasePath(undefined) // undefined
10
+ *
11
+ * @returns {T | string}
12
+ */
13
+ export const addBasePath = (path, config) => {
14
+ /** @type {string} */
15
+ let _path;
16
+
17
+ if (path instanceof String) {
18
+ _path = path.toString();
19
+ } else if (typeof path !== 'string') {
20
+ return path;
21
+ } else {
22
+ _path = path;
23
+ }
24
+
25
+ if (_path.startsWith('http')) return _path;
26
+ if (_path.startsWith('#')) return _path; // ignore hash links
27
+ if (/^[^/]*:/.test(_path)) return _path; // ignore other protocols
28
+
29
+ let basePath = config.deployment.basePath;
30
+ if (basePath) {
31
+ if (!basePath?.startsWith('/')) {
32
+ basePath = `/${basePath}`;
33
+ }
34
+ if (basePath.endsWith('/')) {
35
+ basePath = basePath.slice(0, -1);
36
+ }
37
+ if (_path.startsWith(basePath)) return _path;
38
+ if (!_path.startsWith('/')) {
39
+ _path = `/${_path}`;
40
+ }
41
+ return `${basePath}${_path}`;
42
+ } else {
43
+ return _path;
44
+ }
45
+ };
46
+
47
+ /**
48
+ * The data scope of a page: the value of the route parameter named by
49
+ * deployment.dataScope, or null when it isn't configured or the page lacks it
50
+ * @param {Record<string, string> | undefined} params
51
+ * @param {import("../../configuration/schemas/config.schema.js").EvidenceConfig} config
52
+ * @returns {string | null}
53
+ */
54
+ export const getDataScope = (params, config) => {
55
+ const param = config.deployment.dataScope;
56
+ if (!param || !params?.[param]) return null;
57
+ return params[param];
58
+ };
59
+
60
+ /**
61
+ * Like addBasePath, under /<scope> for pages with a data scope
62
+ * @param {string} path
63
+ * @param {string | null} scope
64
+ * @param {import("../../configuration/schemas/config.schema.js").EvidenceConfig} config
65
+ * @example addScopedBasePath('/data/manifest.json', 'org1', config) // '/base/org1/data/manifest.json'
66
+ * @returns {string}
67
+ */
68
+ export const addScopedBasePath = (path, scope, config) => {
69
+ if (!scope) return addBasePath(path, config);
70
+ return addBasePath(
71
+ `/${encodeURIComponent(scope)}${path.startsWith('/') ? '' : '/'}${path}`,
72
+ config
73
+ );
74
+ };
@@ -0,0 +1,108 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ /** @type {undefined | string} */
3
+ let basePath = undefined;
4
+ const config = {
5
+ deployment: {
6
+ get basePath() {
7
+ return basePath;
8
+ }
9
+ }
10
+ };
11
+
12
+ import { addBasePath } from './addBasePath.js';
13
+ describe('addBasePath', () => {
14
+ it('should return path if basePath is not set', () => {
15
+ basePath = undefined;
16
+ expect(addBasePath('/test', config)).toBe('/test');
17
+ });
18
+ it('should return path with basePath if basePath is set', () => {
19
+ basePath = '/base';
20
+ expect(addBasePath('/test', config)).toBe('/base/test');
21
+ });
22
+ it('should leave absolute paths as is', () => {
23
+ basePath = '/base';
24
+ expect(addBasePath('https://example.com/test', config)).toBe('https://example.com/test');
25
+ });
26
+ it('should always delimit with only one /', () => {
27
+ basePath = '/base/';
28
+ expect(addBasePath('/test', config)).toBe('/base/test');
29
+ });
30
+ it('should always start with /', () => {
31
+ basePath = 'base';
32
+ expect(addBasePath('/test', config)).toBe('/base/test');
33
+ });
34
+ it('should pass through undefined', () => {
35
+ basePath = '/base';
36
+ expect(addBasePath(undefined)).toBe(undefined);
37
+ });
38
+ it('should not double up the base path', () => {
39
+ basePath = '/base';
40
+ expect(addBasePath('/base/test', config)).toBe('/base/test');
41
+ });
42
+ it('should not modify hash links', () => {
43
+ basePath = '/base';
44
+ expect(addBasePath('#test', config)).toBe('#test');
45
+ });
46
+ it.each([
47
+ 'http://example.com',
48
+ 'https://example.com',
49
+ 'ftp://example.com/file.txt',
50
+ 'mailto:someone@example.com',
51
+ 'tel:+1234567890',
52
+ 'file:///C:/path/to/file',
53
+ 'data:text/plain;base64,aGVsbG8gd29ybGQ=',
54
+ 'javascript:alert("Hello")',
55
+ 'blob:hajsfklayhslfjkahslfkahjslkf',
56
+ 'sms:+1234567890',
57
+ 'vscode:extension/Evidence.evidence-vscode',
58
+ 'someprotocol:',
59
+ 'someotherprotocol://'
60
+ ])('should not modify urls with a protocol (%s)', (href) => {
61
+ basePath = '/base';
62
+ expect(addBasePath(href, config)).toBe(href);
63
+ });
64
+ it('should add base path to relative path with colon in it', () => {
65
+ basePath = '/base';
66
+ expect(addBasePath('/test:123', config)).toBe('/base/test:123');
67
+ });
68
+ it('should properly handle String wrapper or non-string values', () => {
69
+ basePath = '/base';
70
+ expect(addBasePath(new String('/test'), config)).toBe('/base/test');
71
+ expect(addBasePath(123, config)).toBe(123);
72
+ expect(addBasePath(123n, config)).toBe(123n);
73
+ expect(addBasePath(true, config)).toBe(true);
74
+ expect(addBasePath(Symbol.for('test'), config)).toBe(Symbol.for('test'));
75
+ const fn = () => {};
76
+ expect(addBasePath(fn, config)).toBe(fn);
77
+ expect(addBasePath(null, config)).toBe(null);
78
+ expect(addBasePath(undefined, config)).toBe(undefined);
79
+ const obj = {};
80
+ expect(addBasePath(obj, config)).toBe(obj);
81
+ });
82
+ it('should add slash', () => {
83
+ basePath = '/base';
84
+ expect(addBasePath('test', config)).toBe('/base/test');
85
+ });
86
+ });
87
+
88
+ import { addScopedBasePath, getDataScope } from './addBasePath.js';
89
+ describe('data scope', () => {
90
+ const scoped = { deployment: { basePath: '/base', dataScope: 'orgslug' } };
91
+ it('is the value of the configured route parameter', () => {
92
+ expect(getDataScope({ orgslug: 'org1' }, scoped)).toBe('org1');
93
+ });
94
+ it('is null for pages without the parameter, or without dataScope', () => {
95
+ expect(getDataScope({ site: 's' }, scoped)).toBe(null);
96
+ expect(getDataScope(undefined, scoped)).toBe(null);
97
+ expect(getDataScope({ orgslug: 'org1' }, { deployment: { basePath: '/base' } })).toBe(null);
98
+ });
99
+ it('puts scoped paths under /<scope> after the base path', () => {
100
+ expect(addScopedBasePath('/data/manifest.json', 'org1', scoped)).toBe(
101
+ '/base/org1/data/manifest.json'
102
+ );
103
+ expect(addScopedBasePath('api/x.json', 'org1', scoped)).toBe('/base/org1/api/x.json');
104
+ });
105
+ it('leaves unscoped paths to addBasePath', () => {
106
+ expect(addScopedBasePath('/data/manifest.json', null, scoped)).toBe('/base/data/manifest.json');
107
+ });
108
+ });
@@ -0,0 +1,13 @@
1
+ export * from './inputs.js';
2
+ import {
3
+ addBasePath as _addBasePath,
4
+ addScopedBasePath as _addScopedBasePath,
5
+ getDataScope as _getDataScope
6
+ } from './addBasePath.js';
7
+ import { config } from '$evidence/config';
8
+ /** @type {(path: string) => string} */
9
+ export const addBasePath = (path) => _addBasePath(path, config);
10
+ /** @type {(params: Record<string, string> | undefined) => string | null} */
11
+ export const getDataScope = (params) => _getDataScope(params, config);
12
+ /** @type {(path: string, scope: string | null) => string} */
13
+ export const addScopedBasePath = (path, scope) => _addScopedBasePath(path, scope, config);
@@ -0,0 +1,138 @@
1
+ import { getAllContexts, getContext, setContext } from 'svelte';
2
+ import { get, readable, readonly, writable } from 'svelte/store';
3
+
4
+ export const InputStoreKey = Symbol('InputStore');
5
+
6
+ /** @template T; @typedef {import("svelte/store").Readable<T>} Readable */
7
+ /** @template T; @typedef {import("svelte/store").Writable<T>} Writable */
8
+
9
+ /**
10
+ * @typedef {Object} InputValue
11
+ * @property {any} value
12
+ * @property {string} label
13
+ */
14
+
15
+ /**
16
+ * @param {unknown} v
17
+ * @returns {v is Readable<any>}
18
+ */
19
+ export const isReadable = (v) => {
20
+ if (typeof v !== 'object') return false;
21
+ if (v === null) return false;
22
+ return 'subscribe' in v;
23
+ };
24
+ /**
25
+ * @param {unknown} v
26
+ * @returns {v is Writable<any>}
27
+ */
28
+ const isWritable = (v) => {
29
+ if (!isReadable(v)) return false;
30
+ return 'set' in v && 'update' in v;
31
+ };
32
+
33
+ /**
34
+ * @param {Writable<any>} c
35
+ * @returns {Writable<any>}
36
+ */
37
+ export const ensureInputContext = (c) => {
38
+ if (!isWritable(c)) {
39
+ console.error({ InputStoreValue: c });
40
+ throw new Error('InputStore must be a writable store');
41
+ }
42
+ if (!getAllContexts().has(InputStoreKey)) {
43
+ setContext(InputStoreKey, c);
44
+ return c;
45
+ } else {
46
+ const existingValue = getContext(InputStoreKey);
47
+ existingValue.set(get(c));
48
+ return existingValue;
49
+ }
50
+ };
51
+
52
+ /**
53
+ * @returns {Writable<any>}
54
+ * @deprecated use 'getInputSetter' whenever possible
55
+ */
56
+ export const getInputContext = () => {
57
+ if (!getAllContexts().has(InputStoreKey)) {
58
+ console.warn('InputStoreKey not found in context. Did you forget to call ensureInputContext?');
59
+ return writable({});
60
+ }
61
+ return getContext(InputStoreKey);
62
+ };
63
+
64
+ /**
65
+ *
66
+ * @returns {import("svelte/store").Readable<any>}
67
+ */
68
+ export const getReadonlyInputContext = () => {
69
+ if (!getAllContexts().has(InputStoreKey)) {
70
+ console.warn('InputStoreKey not found in context. Did you forget to call ensureInputContext?');
71
+ return readable({});
72
+ }
73
+
74
+ const value = getContext(InputStoreKey);
75
+ if (isReadable(value)) {
76
+ return readonly(value);
77
+ } else {
78
+ throw new Error(`InputStoreKey is not a readable store: ${value}`);
79
+ }
80
+ };
81
+
82
+ /**
83
+ * Returns a factory function used to interact with the input store at the specified path.
84
+ * @param {string | string[]} inputKey
85
+ * @param {boolean} [toggle]
86
+ * @param {string} [defaultSqlFragment]
87
+ */
88
+ export const getInputSetter = (inputKey, toggle, defaultSqlFragment) => {
89
+ const inputs = getInputContext();
90
+ let inputPath = Array.isArray(inputKey) ? inputKey : [inputKey];
91
+ if (!inputPath.length) {
92
+ return () => {
93
+ console.warn(`Failed to update input: ${inputPath} is not a valid input path`);
94
+ };
95
+ }
96
+ /**
97
+ * @param {any} value
98
+ * @param {string} [label]
99
+ * @param {string} [sqlFragment]
100
+ * @param {any} [additional]
101
+ */
102
+ return (value, label, sqlFragment, additional) => {
103
+ inputs.update(($inputs) => {
104
+ let target = $inputs;
105
+ let finalKey = inputPath.at(-1) ?? '';
106
+ for (const p of inputPath.slice(0, -1)) {
107
+ target = target[p];
108
+ }
109
+ if (!value && !label) {
110
+ target[finalKey] = {
111
+ toString() {
112
+ return defaultSqlFragment;
113
+ }
114
+ };
115
+ return $inputs;
116
+ }
117
+ const result = {
118
+ ...additional,
119
+ value,
120
+ label,
121
+ toString() {
122
+ return sqlFragment;
123
+ }
124
+ };
125
+ if (toggle && JSON.stringify(target[finalKey]) === JSON.stringify(result)) {
126
+ target[finalKey] = {
127
+ toString() {
128
+ return defaultSqlFragment;
129
+ }
130
+ };
131
+ } else {
132
+ target[finalKey] = result;
133
+ }
134
+
135
+ return $inputs;
136
+ });
137
+ };
138
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "exclude": ["./**/*.spec.js", "./types", "./src/lib/tests"],
3
+ "include": ["./src", "./.evidence/shadow-types"],
4
+ "compilerOptions": {
5
+ "declarationMap": true,
6
+ "declarationDir": "./types",
7
+ "rootDir": "./src",
8
+ "baseUrl": "./src",
9
+ "outDir": "dist",
10
+ "target": "es2022",
11
+ "lib": ["es2022", "DOM"],
12
+ "allowJs": true,
13
+ "checkJs": true,
14
+ "declaration": true,
15
+ "esModuleInterop": true,
16
+ "strict": true,
17
+ "module": "NodeNext",
18
+ "moduleResolution": "NodeNext",
19
+ "isolatedModules": true,
20
+ "skipLibCheck": true
21
+ }
22
+ }
package/vite.config.js ADDED
@@ -0,0 +1,3 @@
1
+ import { defineConfig } from 'vite';
2
+
3
+ export default defineConfig({});
@@ -0,0 +1,15 @@
1
+ /** @type {import("vitest").UserConfig} */
2
+ export default {
3
+ plugins: [
4
+ {
5
+ load: (id) => (id === '\0$evidence/config' ? `export const config = {}` : null),
6
+ resolveId: (id) => (id === '$evidence/config' ? '\0$evidence/config' : null)
7
+ }
8
+ ],
9
+ coverage: {
10
+ // you can include other reporters, but 'json-summary' is required, json is recommended
11
+ reporter: ['json-summary', 'json', 'cobertura'],
12
+ // If you want a coverage reports even if your tests are failing, include the reportOnFailure option
13
+ reportOnFailure: true
14
+ }
15
+ };