@builder.io/sdk-svelte 0.6.4 → 0.7.1-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 (81) hide show
  1. package/lib/browser/blocks/custom-code/custom-code.svelte +35 -37
  2. package/lib/browser/components/content/components/enable-editor.svelte +86 -70
  3. package/lib/browser/components/content/components/enable-editor.svelte.d.ts +4 -4
  4. package/lib/browser/constants/sdk-version.d.ts +1 -1
  5. package/lib/browser/constants/sdk-version.js +1 -1
  6. package/lib/browser/functions/evaluate/choose-eval.d.ts +6 -0
  7. package/lib/browser/functions/evaluate/choose-eval.js +19 -0
  8. package/lib/browser/functions/evaluate/evaluate.d.ts +1 -5
  9. package/lib/browser/functions/evaluate/evaluate.js +7 -30
  10. package/lib/browser/functions/evaluate/helpers.d.ts +7 -1
  11. package/lib/browser/functions/evaluate/helpers.js +18 -0
  12. package/lib/browser/functions/evaluate/node-runtime/index.d.ts +1 -1
  13. package/lib/browser/functions/evaluate/node-runtime/index.js +1 -1
  14. package/lib/browser/functions/evaluate/node-runtime/node-runtime.d.ts +2 -0
  15. package/lib/browser/functions/evaluate/node-runtime/node-runtime.js +120 -0
  16. package/lib/browser/functions/evaluate/node-runtime/safeDynamicRequire.d.ts +13 -0
  17. package/lib/browser/functions/evaluate/node-runtime/safeDynamicRequire.js +18 -0
  18. package/lib/browser/functions/get-content/generate-content-url.js +32 -1
  19. package/lib/browser/functions/get-content/types.d.ts +94 -3
  20. package/lib/browser/functions/is-edge-runtime.js +2 -2
  21. package/lib/browser/functions/is-node-runtime.d.ts +4 -0
  22. package/lib/browser/functions/is-node-runtime.js +7 -0
  23. package/lib/edge/blocks/custom-code/custom-code.svelte +35 -37
  24. package/lib/edge/components/content/components/enable-editor.svelte +86 -70
  25. package/lib/edge/components/content/components/enable-editor.svelte.d.ts +4 -4
  26. package/lib/edge/constants/sdk-version.d.ts +1 -1
  27. package/lib/edge/constants/sdk-version.js +1 -1
  28. package/lib/edge/functions/evaluate/choose-eval.d.ts +6 -0
  29. package/lib/edge/functions/evaluate/choose-eval.js +19 -0
  30. package/lib/edge/functions/evaluate/evaluate.d.ts +1 -5
  31. package/lib/edge/functions/evaluate/evaluate.js +7 -30
  32. package/lib/edge/functions/evaluate/helpers.d.ts +7 -1
  33. package/lib/edge/functions/evaluate/helpers.js +18 -0
  34. package/lib/edge/functions/evaluate/node-runtime/index.d.ts +1 -1
  35. package/lib/edge/functions/evaluate/node-runtime/index.js +1 -1
  36. package/lib/edge/functions/evaluate/node-runtime/node-runtime.d.ts +2 -0
  37. package/lib/edge/functions/evaluate/node-runtime/node-runtime.js +120 -0
  38. package/lib/edge/functions/evaluate/node-runtime/safeDynamicRequire.d.ts +13 -0
  39. package/lib/edge/functions/evaluate/node-runtime/safeDynamicRequire.js +18 -0
  40. package/lib/edge/functions/get-content/generate-content-url.js +32 -1
  41. package/lib/edge/functions/get-content/types.d.ts +94 -3
  42. package/lib/edge/functions/is-edge-runtime.js +2 -2
  43. package/lib/edge/functions/is-node-runtime.d.ts +4 -0
  44. package/lib/edge/functions/is-node-runtime.js +7 -0
  45. package/lib/node/blocks/custom-code/custom-code.svelte +35 -37
  46. package/lib/node/components/content/components/enable-editor.svelte +86 -70
  47. package/lib/node/components/content/components/enable-editor.svelte.d.ts +4 -4
  48. package/lib/node/constants/sdk-version.d.ts +1 -1
  49. package/lib/node/constants/sdk-version.js +1 -1
  50. package/lib/node/functions/evaluate/choose-eval.d.ts +6 -0
  51. package/lib/node/functions/evaluate/choose-eval.js +19 -0
  52. package/lib/node/functions/evaluate/evaluate.d.ts +1 -5
  53. package/lib/node/functions/evaluate/evaluate.js +7 -30
  54. package/lib/node/functions/evaluate/helpers.d.ts +7 -1
  55. package/lib/node/functions/evaluate/helpers.js +18 -0
  56. package/lib/node/functions/evaluate/node-runtime/index.d.ts +1 -1
  57. package/lib/node/functions/evaluate/node-runtime/index.js +1 -1
  58. package/lib/node/functions/evaluate/node-runtime/node-runtime.d.ts +2 -0
  59. package/lib/node/functions/evaluate/node-runtime/node-runtime.js +120 -0
  60. package/lib/node/functions/evaluate/node-runtime/safeDynamicRequire.d.ts +13 -0
  61. package/lib/node/functions/evaluate/node-runtime/safeDynamicRequire.js +18 -0
  62. package/lib/node/functions/get-content/generate-content-url.js +32 -1
  63. package/lib/node/functions/get-content/types.d.ts +94 -3
  64. package/lib/node/functions/is-edge-runtime.js +2 -2
  65. package/lib/node/functions/is-node-runtime.d.ts +4 -0
  66. package/lib/node/functions/is-node-runtime.js +7 -0
  67. package/package.json +3 -1
  68. package/src/blocks/custom-code/custom-code.svelte +37 -40
  69. package/src/blocks/image/image.svelte +1 -1
  70. package/src/components/content/components/enable-editor.svelte +101 -84
  71. package/src/constants/sdk-version.ts +1 -1
  72. package/src/functions/evaluate/choose-eval.ts +22 -0
  73. package/src/functions/evaluate/evaluate.ts +8 -37
  74. package/src/functions/evaluate/helpers.ts +24 -1
  75. package/src/functions/evaluate/node-runtime/index.ts +1 -1
  76. package/src/functions/evaluate/node-runtime/node-runtime.ts +138 -0
  77. package/src/functions/evaluate/node-runtime/safeDynamicRequire.ts +18 -0
  78. package/src/functions/get-content/generate-content-url.ts +44 -2
  79. package/src/functions/get-content/types.ts +101 -3
  80. package/src/functions/is-edge-runtime.ts +2 -2
  81. package/src/functions/is-node-runtime.ts +8 -0
@@ -0,0 +1,138 @@
1
+ import type { FunctionArguments, ExecutorArgs, BuilderGlobals } from '../helpers.js';
2
+ import { getFunctionArguments } from '../helpers.js';
3
+ import { safeDynamicRequire } from './safeDynamicRequire.js';
4
+ import { fastClone } from '../../fast-clone.js';
5
+ import { set } from '../../set.js';
6
+ const ivm: typeof import('isolated-vm') = safeDynamicRequire('isolated-vm');
7
+ const getSyncValName = (key: string) => `bldr_${key}_sync`;
8
+ const BUILDER_SET_STATE_NAME = 'BUILDER_SET_STATE';
9
+ const INJECTED_IVM_GLOBAL = 'BUILDER_IVM';
10
+
11
+ // Convert all argument references to proxies, and pass `copySync` method to target object, to return a copy of the original JS object
12
+ // https://github.com/laverdet/isolated-vm#referencecopysync
13
+ const REF_TO_PROXY_FN = `
14
+ var refToProxy = (obj) => {
15
+ if (typeof obj !== 'object' || obj === null) {
16
+ return obj;
17
+ }
18
+ return new Proxy({}, {
19
+ get(target, key) {
20
+ if (key === 'copySync') {
21
+ return () => obj.copySync();
22
+ }
23
+ const val = obj.getSync(key);
24
+ if (typeof val?.getSync === 'function') {
25
+ return refToProxy(val);
26
+ }
27
+ return val;
28
+ },
29
+ set(target, key, value) {
30
+ const v = typeof value === 'object' ? new ${INJECTED_IVM_GLOBAL}.Reference(value) : value;
31
+ obj.setSync(key, v);
32
+ ${BUILDER_SET_STATE_NAME}(key, value)
33
+ },
34
+ deleteProperty(target, key) {
35
+ obj.deleteSync(key);
36
+ }
37
+ })
38
+ }
39
+ `;
40
+ const processCode = ({
41
+ code,
42
+ args
43
+ }: {
44
+ code: string;
45
+ args: FunctionArguments;
46
+ }) => {
47
+ const fnArgs = args.map(([name]) => `var ${name} = refToProxy(${getSyncValName(name)}); `).join('');
48
+
49
+ // the output is stringified and parsed back to the parent isolate if needed (when it's an `object`)
50
+ return `
51
+ ${REF_TO_PROXY_FN}
52
+ ${fnArgs}
53
+ function theFunction() {
54
+ ${code}
55
+ }
56
+
57
+ let output = theFunction()
58
+
59
+ if (typeof output === 'object' && output !== null) {
60
+ output = JSON.stringify(output.copySync ? output.copySync() : output);
61
+ }
62
+
63
+ output;
64
+ `;
65
+ };
66
+ const getIsolateContext = () => {
67
+ // if (Builder.serverContext) {
68
+ // return Builder.serverContext;
69
+ // }
70
+ // Builder.setServerContext(isolate.createContextSync());
71
+ const isolate = new ivm.Isolate({
72
+ memoryLimit: 128
73
+ });
74
+ return isolate.createContextSync();
75
+ };
76
+ export const runInNode = ({
77
+ code,
78
+ builder,
79
+ context,
80
+ event,
81
+ localState,
82
+ rootSetState,
83
+ rootState
84
+ }: ExecutorArgs) => {
85
+ const state = fastClone({
86
+ ...rootState,
87
+ ...localState
88
+ });
89
+ const args = getFunctionArguments({
90
+ builder,
91
+ context,
92
+ event,
93
+ state
94
+ });
95
+ const isolateContext = getIsolateContext();
96
+ const jail = isolateContext.global;
97
+ // This makes the global object available in the context as `global`. We use `derefInto()` here
98
+ // because otherwise `global` would actually be a Reference{} object in the new isolate.
99
+ jail.setSync('global', jail.derefInto());
100
+
101
+ // We will create a basic `log` function for the new isolate to use.
102
+ jail.setSync('log', function (...logArgs: any[]) {
103
+ console.log(...logArgs);
104
+ });
105
+
106
+ /**
107
+ * Propagate state changes back to the reactive root state.
108
+ */
109
+ jail.setSync(BUILDER_SET_STATE_NAME, function (key: string, value: any) {
110
+ // mutate the `rootState` object itself. Important for cases where we do not have `rootSetState`
111
+ // like Qwik.
112
+ set(rootState, key, value);
113
+ // call the `rootSetState` function if it exists
114
+ rootSetState?.(rootState);
115
+ });
116
+ args.forEach(([key, arg]) => {
117
+ const val = typeof arg === 'object' ? new ivm.Reference(
118
+ // workaround: methods with default values for arguments is not being cloned over
119
+ key === 'builder' ? {
120
+ ...arg,
121
+ getUserAttributes: () => (arg as BuilderGlobals).getUserAttributes()
122
+ } : arg) : null;
123
+ jail.setSync(getSyncValName(key), val);
124
+ });
125
+ jail.setSync(INJECTED_IVM_GLOBAL, ivm);
126
+ const evalStr = processCode({
127
+ code,
128
+ args
129
+ });
130
+ const resultStr = isolateContext.evalSync(evalStr);
131
+ try {
132
+ // returning objects throw errors in isolated vm, so we stringify it and parse it back
133
+ const res = JSON.parse(resultStr);
134
+ return res;
135
+ } catch (_error: any) {
136
+ return resultStr;
137
+ }
138
+ }
@@ -0,0 +1,18 @@
1
+ const noop = () => null;
2
+
3
+ /**
4
+ * Allows us to require node-specific code safely within bundlers.
5
+ *
6
+ * https://github.com/laverdet/isolated-vm/issues/423
7
+ *
8
+ * NOTE: this code should only ever run in `node`, and never in an `edge` runtime.
9
+ * This is guaranteed by the fact that each SDK has separate bundles for each runtime.
10
+ * However, it might still end up running in the `browser` if the `node` bundle is loaded in the
11
+ * browser (which happens in many apps' dev mode, and certain other scenarios like Qwik's prod mode).
12
+ */
13
+ export let safeDynamicRequire: typeof require = ((noop as unknown) as typeof require);
14
+ try {
15
+ safeDynamicRequire = eval('require');
16
+ } catch (error) {
17
+ /* empty */
18
+ }
@@ -2,18 +2,28 @@ import { flatten } from '../../helpers/flatten.js';
2
2
  import { getBuilderSearchParamsFromWindow, normalizeSearchParams } from '../get-builder-search-params/index.js';
3
3
  import type { GetContentOptions } from './types.js';
4
4
  import { DEFAULT_API_VERSION } from '../../types/api-version.js';
5
+ const isPositiveNumber = (thing: unknown) => typeof thing === 'number' && !isNaN(thing) && thing >= 0;
5
6
  export const generateContentUrl = (options: GetContentOptions): URL => {
7
+ let {
8
+ noTraverse = false
9
+ } = options;
6
10
  const {
7
11
  limit = 30,
8
12
  userAttributes,
9
13
  query,
10
- noTraverse = false,
11
14
  model,
12
15
  apiKey,
13
16
  includeRefs = true,
14
17
  enrich,
15
18
  locale,
16
- apiVersion = DEFAULT_API_VERSION
19
+ apiVersion = DEFAULT_API_VERSION,
20
+ fields,
21
+ omit,
22
+ offset,
23
+ cacheSeconds,
24
+ staleCacheSeconds,
25
+ sort,
26
+ includeUnpublished
17
27
  } = options;
18
28
  if (!apiKey) {
19
29
  throw new Error('Missing API key');
@@ -21,7 +31,39 @@ export const generateContentUrl = (options: GetContentOptions): URL => {
21
31
  if (!['v2', 'v3'].includes(apiVersion)) {
22
32
  throw new Error(`Invalid apiVersion: expected 'v2' or 'v3', received '${apiVersion}'`);
23
33
  }
34
+
35
+ // Set noTraverse=true if NOT already passed by user, for query performance
36
+ if ((options.limit === undefined || options.limit > 1) && !('noTraverse' in options)) {
37
+ noTraverse = true;
38
+ }
24
39
  const url = new URL(`https://cdn.builder.io/api/${apiVersion}/content/${model}?apiKey=${apiKey}&limit=${limit}&noTraverse=${noTraverse}&includeRefs=${includeRefs}${locale ? `&locale=${locale}` : ''}${enrich ? `&enrich=${enrich}` : ''}`);
40
+ url.searchParams.set('omit', omit || 'meta.componentsUsed');
41
+ if (fields) {
42
+ url.searchParams.set('fields', fields);
43
+ }
44
+ if (Number.isFinite(offset) && offset! > -1) {
45
+ url.searchParams.set('offset', String(Math.floor(offset!)));
46
+ }
47
+ if (typeof includeUnpublished === 'boolean') {
48
+ url.searchParams.set('includeUnpublished', String(includeUnpublished));
49
+ }
50
+ if (cacheSeconds && isPositiveNumber(cacheSeconds)) {
51
+ url.searchParams.set('cacheSeconds', String(cacheSeconds));
52
+ }
53
+ if (staleCacheSeconds && isPositiveNumber(staleCacheSeconds)) {
54
+ url.searchParams.set('staleCacheSeconds', String(staleCacheSeconds));
55
+ }
56
+ if (sort) {
57
+ const flattened = flatten({
58
+ sort
59
+ });
60
+ for (const key in flattened) {
61
+ url.searchParams.set(key, JSON.stringify((flattened as any)[key]));
62
+ }
63
+ }
64
+
65
+ // TODO: how to express 'offset' in the url - as direct queryparam or as flattened in options[key] ?
66
+
25
67
  const queryOptions = {
26
68
  ...getBuilderSearchParamsFromWindow(),
27
69
  ...normalizeSearchParams(options.options || {})
@@ -8,12 +8,44 @@ export interface GetContentOptions {
8
8
  /** Number of items to fetch. Default is 1 */
9
9
  limit?: number;
10
10
 
11
- /** User attributes to target on, such as { urlPath: '/foo', device: 'mobile', ...etc } */
11
+ /**
12
+ * Use to specify an offset for pagination of results. The default is 0.
13
+ */
14
+ offset?: number;
15
+
16
+ /**
17
+ * User attribute key value pairs to be used for targeting
18
+ * https://www.builder.io/c/docs/custom-targeting-attributes
19
+ *
20
+ * e.g.
21
+ * ```js
22
+ * userAttributes: {
23
+ * urlPath: '/',
24
+ * returnVisitor: true,
25
+ * device: 'mobile'
26
+ * }
27
+ * ```
28
+ */
12
29
  userAttributes?: (Record<string, string> & {
13
30
  urlPath?: string;
14
31
  }) | null;
15
32
 
16
- /** Custom query */
33
+ /**
34
+ * Mongodb style query of your data. E.g.:
35
+ *
36
+ * ```js
37
+ * query: {
38
+ * id: 'abc123',
39
+ * data: {
40
+ * myCustomField: { $gt: 20 },
41
+ * }
42
+ * }
43
+ * ```
44
+ *
45
+ * See more info on MongoDB's query operators and format.
46
+ *
47
+ * @see {@link https://docs.mongodb.com/manual/reference/operator/query/}
48
+ */
17
49
  query?: Record<string, any>;
18
50
 
19
51
  /**
@@ -38,7 +70,7 @@ export interface GetContentOptions {
38
70
  canTrack?: boolean;
39
71
 
40
72
  /**
41
- * Include references in the response. Defaults to `true`.
73
+ * Include content of references in the response. Defaults to `true`.
42
74
  * @deprecated use `enrich` instead
43
75
  */
44
76
  includeRefs?: boolean;
@@ -59,4 +91,70 @@ export interface GetContentOptions {
59
91
  * Defaults to `v3`.
60
92
  */
61
93
  apiVersion?: 'v2' | 'v3';
94
+
95
+ /**
96
+ * Only include these fields.
97
+ * Note: 'omit' takes precedence over 'fields'
98
+ *
99
+ * @example
100
+ * ```
101
+ * fields: 'id, name, data.customField'
102
+ * ```
103
+ */
104
+ fields?: string;
105
+
106
+ /**
107
+ * Omit only these fields.
108
+ * Note: 'omit' takes precedence over 'fields'
109
+ *
110
+ * @example
111
+ * ```
112
+ * omit: 'data.bigField,data.blocks'
113
+ * ```
114
+ */
115
+ omit?: string;
116
+
117
+ /**
118
+ * Seconds to cache content. Sets the max-age of the cache-control header
119
+ * response header.
120
+ *
121
+ * Use a higher value for better performance, lower for content that will change more frequently
122
+ *
123
+ * @see {@link https://www.builder.io/c/docs/query-api#__next:~:text=%26includeRefs%3Dtrue-,cacheSeconds,-No}
124
+ */
125
+ cacheSeconds?: number;
126
+
127
+ /**
128
+ * Builder.io uses stale-while-revalidate caching at the CDN level. This means we always serve
129
+ * from edge cache and update caches in the background for maximum possible performance. This also
130
+ * means that the more frequently content is requested, the more fresh it will be. The longest we
131
+ * will ever hold something in stale cache is 1 day by default, and you can set this to be shorter
132
+ * yourself as well. We suggest keeping this high unless you have content that must change rapidly
133
+ * and gets very little traffic.
134
+ *
135
+ * @see {@link https://www.fastly.com/blog/prevent-application-network-instability-serve-stale-content}
136
+ */
137
+ staleCacheSeconds?: number;
138
+
139
+ /**
140
+ * Property to order results by.
141
+ * Use 1 for ascending and -1 for descending.
142
+ *
143
+ * The key is what you're sorting on, so the following example sorts by createdDate
144
+ * and because the value is 1, the sort is ascending.
145
+ *
146
+ * @example
147
+ * ```
148
+ * createdDate: 1
149
+ * ```
150
+ */
151
+ sort?: {
152
+ [key: string]: 1 | -1;
153
+ };
154
+
155
+ /**
156
+ * Include content entries in a response that are still in
157
+ * draft mode and un-archived. Default is false.
158
+ */
159
+ includeUnpublished?: boolean;
62
160
  }
@@ -1,9 +1,9 @@
1
1
  import { isBrowser } from './is-browser.js';
2
+ import { isNodeRuntime } from './is-node-runtime.js';
2
3
 
3
4
  /**
4
5
  * Identifies edge runtimes (edge, workers, serverless, etc.)
5
6
  */
6
7
  export function isEdgeRuntime(): boolean {
7
- const hasNode = () => typeof process !== 'undefined' && process?.versions?.node;
8
- return !isBrowser() && !hasNode();
8
+ return !isBrowser() && !isNodeRuntime();
9
9
  }
@@ -0,0 +1,8 @@
1
+ import { checkIsDefined } from '../helpers/nullable';
2
+
3
+ /**
4
+ * Identifies node runtime
5
+ */
6
+ export function isNodeRuntime(): boolean {
7
+ return typeof process !== 'undefined' && checkIsDefined(process?.versions?.node);
8
+ }