@moondraft/import 0.3.0 → 0.5.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 (39) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +25 -0
  3. package/SOURCE.md +49 -0
  4. package/dist/adapter/convert.js +34 -1
  5. package/dist/adapter/file-components.d.ts +18 -0
  6. package/dist/adapter/file-components.js +96 -11
  7. package/dist/adapter/file-resources.d.ts +6 -1
  8. package/dist/adapter/file-resources.js +126 -28
  9. package/dist/adapter/link.d.ts +1 -1
  10. package/dist/adapter/link.js +138 -87
  11. package/dist/figma-file.d.ts +3 -2
  12. package/dist/figma-file.js +7 -2
  13. package/dist/figma-worker.d.ts +5 -0
  14. package/dist/figma-worker.js +6 -1
  15. package/dist/figma.d.ts +7 -1
  16. package/dist/figma.js +29 -10
  17. package/dist/index.d.ts +6 -1
  18. package/dist/index.js +3 -1
  19. package/dist/lazy.d.ts +111 -0
  20. package/dist/lazy.js +363 -0
  21. package/dist/report.js +6 -1
  22. package/dist/serialize.d.ts +9 -0
  23. package/dist/serialize.js +54 -0
  24. package/dist/taco/figma-import/import/carry.d.ts +11 -1
  25. package/dist/taco/figma-import/import/carry.js +8 -0
  26. package/dist/taco/figma-import/import/converters/effects.js +11 -3
  27. package/dist/taco/figma-import/import/converters/group.d.ts +1 -0
  28. package/dist/taco/figma-import/import/converters/group.js +5 -2
  29. package/dist/taco/figma-import/import/converters/section.d.ts +2 -1
  30. package/dist/taco/figma-import/import/converters/section.js +4 -1
  31. package/dist/taco/figma-import/import/converters/shared.d.ts +21 -2
  32. package/dist/taco/figma-import/import/converters/shared.js +53 -7
  33. package/dist/taco/figma-import/import/converters/text.js +39 -5
  34. package/dist/taco/figma-import/import/converters/vector.js +5 -3
  35. package/dist/taco/figma-import/import/instances.d.ts +10 -0
  36. package/dist/taco/figma-import/import/instances.js +22 -21
  37. package/dist/taco/figma-import/import/variables.js +8 -2
  38. package/dist/taco/figma-import/import/walk.js +8 -2
  39. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -42,9 +42,11 @@ export function figmaImporter(options = {}) {
42
42
  const { openFigmaFile } = await import('./figma-file.js');
43
43
  return openFigmaFile(await bytesOf(input.file), {
44
44
  signal: env.signal, progress: env.progress, ...(options.worker !== undefined ? { worker: options.worker } : {}),
45
+ ...(options.limits !== undefined ? { limits: options.limits } : {}),
45
46
  });
46
47
  },
47
48
  };
48
49
  }
49
50
  export { payloadFromSyntax } from './syntax.js';
50
- export { serializeImportDocument } from './serialize.js';
51
+ export { serializeImportDocument, serializeImportNdjson } from './serialize.js';
52
+ export { bundleFileName, componentRefsOf, createLazyBundle } from './lazy.js';
package/dist/lazy.d.ts ADDED
@@ -0,0 +1,111 @@
1
+ import type { DocumentJSON } from '@moondraft/editor/schema';
2
+ export type LazyModel = DocumentJSON['models'][number];
3
+ /** One page entry in a lazy bundle's `index.json`. `bytes` is the UTF-8 size of `pages/<id>.ndjson` (0 when empty). */
4
+ export interface LazyBundlePage {
5
+ id: string;
6
+ name: string;
7
+ order?: string;
8
+ modes?: Record<string, string>;
9
+ bytes: number;
10
+ }
11
+ /** One atomic component subtree in a lazy bundle, identified by its top-level layer ID. */
12
+ export interface LazyBundleComponent {
13
+ layers: number;
14
+ /** Index into `sccs`; also the subtree's topological rank (dependencies have smaller indices). */
15
+ scc: number;
16
+ /** Indices into `sccs` that this subtree references (always smaller than `scc`). */
17
+ deps: number[];
18
+ /** Set when this subtree lives on a public page rather than under `@components`. */
19
+ page?: string;
20
+ }
21
+ /** The manifest of a `moondraft-lazy-v2` bundle. */
22
+ export interface LazyBundleIndex {
23
+ format: 'moondraft-lazy-v2';
24
+ leading?: string;
25
+ /** Document-level metadata other than `leading` (`source`, `libraries`, `data`), when present. */
26
+ meta?: Omit<DocumentJSON, 'leading' | 'models' | 'shared' | 'assets'>;
27
+ pages: LazyBundlePage[];
28
+ /** Maps every main component and variant-set ID to the root ID of the subtree file that contains it. */
29
+ componentOwner: Record<string, string>;
30
+ components: Record<string, LazyBundleComponent>;
31
+ /** Component subtrees that live on each page, ordered by topological rank. */
32
+ pageComponents: Record<string, string[]>;
33
+ /** Strongly connected components of component subtrees in topological order (dependencies first). */
34
+ sccs: string[][];
35
+ }
36
+ /** Options for {@link createLazyBundle}. */
37
+ export interface LazyBundleOptions {
38
+ /** Folder prefix (relative to the bundle root) for data-URL assets written as separate files.
39
+ * Defaults to `'assets/'`; pass `false` to keep data URLs inline. */
40
+ assets?: string | false;
41
+ }
42
+ /** One file of a lazy bundle, ready to write under the bundle's output folder. */
43
+ export interface LazyBundleFile {
44
+ path: string;
45
+ content: string | Uint8Array;
46
+ /** Append to a previous chunk of the same path instead of replacing the file. */
47
+ append?: boolean;
48
+ }
49
+ /** A split document: its manifest plus a generator that yields each file once. */
50
+ export interface LazyBundle {
51
+ index: LazyBundleIndex;
52
+ files(): Generator<LazyBundleFile>;
53
+ }
54
+ interface ModelGroup {
55
+ rootId: string;
56
+ pageId: string | null;
57
+ underComponents: boolean;
58
+ hasMain: boolean;
59
+ models: LazyModel[];
60
+ memberIds: Set<string>;
61
+ refs: Set<string>;
62
+ }
63
+ export declare const encodeNdjsonLine: (record: unknown) => string;
64
+ export declare const isMainComponentRoot: (m: LazyModel) => boolean;
65
+ /**
66
+ * Adds every ID a layer may name as a main component to `into`: its own main, swapped mains in its overrides, the
67
+ * defaults and preferred lists of the swap properties it declares (itself or as a variant set), and the string values
68
+ * it or its overrides give component properties (a swap property's value is a main's ID). IDs that name no main are
69
+ * ignored by callers, so a text or variant value in the last group costs nothing.
70
+ * @param m - One layer record.
71
+ * @param into - The set to add to.
72
+ * @returns `into`.
73
+ */
74
+ export declare function componentRefsOf(m: LazyModel, into?: Set<string>): Set<string>;
75
+ /**
76
+ * The file name a lazy bundle gives a page or component subtree ID, without its `.ndjson` extension. It is one to one
77
+ * and contains no `%`, which servers decode in request paths: the ID is percent-encoded, then `_` becomes `_5F` and
78
+ * each `%` becomes `_`, so `12:34` is `12_3A34`.
79
+ * @param id - A page or subtree root ID.
80
+ * @returns A name safe in a URL path segment and on disk.
81
+ */
82
+ export declare const bundleFileName: (id: string) => string;
83
+ export declare function documentMetaOf(document: DocumentJSON): Omit<DocumentJSON, 'models' | 'shared' | 'assets'>;
84
+ /** Tarjan's strongly connected components over a directed graph, iterative so deep chains cannot overflow the stack.
85
+ * Returns components in topological order: every edge points from a higher index to a lower one. */
86
+ export declare function stronglyConnectedComponents(owners: readonly string[], depsOf: (owner: string) => Iterable<string>): string[][];
87
+ /** Orders the models of one component subtree so main/variant-set roots and their in-subtree ancestors come first. */
88
+ export declare function orderSubtreeForCreate(models: readonly LazyModel[]): LazyModel[];
89
+ interface PlannedDocument {
90
+ pages: LazyModel[];
91
+ componentGroups: Map<string, ModelGroup>;
92
+ componentOwner: Map<string, string>;
93
+ pageGroups: Map<string, ModelGroup[]>;
94
+ pageComponents: Map<string, string[]>;
95
+ sccs: string[][];
96
+ sccOf: Map<string, number>;
97
+ depsOf: Map<string, Set<string>>;
98
+ }
99
+ /** Groups a document into component subtrees (including mains that live on pages) and remaining page subtrees,
100
+ * and computes the topological order of component subtrees. Shared by the NDJSON and lazy bundle writers. */
101
+ export declare function planDocument(document: DocumentJSON): PlannedDocument;
102
+ /**
103
+ * Splits an imported document into a `moondraft-lazy-v2` bundle: an `index.json` manifest, `shared.ndjson`, one NDJSON
104
+ * file per component subtree under `components/`, one per non-empty page under `pages/`, and (by default) media files
105
+ * under `assets/`. A host that serves the folder opens only the shown page and the component subtrees it references.
106
+ * @param document - The plain document returned by the importer.
107
+ * @param options - Asset externalization configuration.
108
+ * @returns The bundle manifest and a generator over the bundle's files.
109
+ */
110
+ export declare function createLazyBundle(document: DocumentJSON, options?: LazyBundleOptions): LazyBundle;
111
+ export {};
package/dist/lazy.js ADDED
@@ -0,0 +1,363 @@
1
+ export const encodeNdjsonLine = (record) => JSON.stringify(record).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029') + '\n';
2
+ export const isMainComponentRoot = (m) => m.kind === 'frame' && (m.component === m.id || Boolean(m.variantSet));
3
+ const addStrings = (values, into) => {
4
+ if (values && typeof values === 'object' && !Array.isArray(values))
5
+ for (const value of Object.values(values))
6
+ if (typeof value === 'string')
7
+ into.add(value);
8
+ };
9
+ /**
10
+ * Adds every ID a layer may name as a main component to `into`: its own main, swapped mains in its overrides, the
11
+ * defaults and preferred lists of the swap properties it declares (itself or as a variant set), and the string values
12
+ * it or its overrides give component properties (a swap property's value is a main's ID). IDs that name no main are
13
+ * ignored by callers, so a text or variant value in the last group costs nothing.
14
+ * @param m - One layer record.
15
+ * @param into - The set to add to.
16
+ * @returns `into`.
17
+ */
18
+ export function componentRefsOf(m, into = new Set()) {
19
+ if (m.kind !== 'frame')
20
+ return into;
21
+ if (typeof m.component === 'string' && m.component !== m.id)
22
+ into.add(m.component);
23
+ const declared = [...(Array.isArray(m.props) ? m.props : []), ...(m.variantSet?.props ?? [])];
24
+ for (const def of declared) {
25
+ if (def.kind !== 'swap')
26
+ continue;
27
+ if (typeof def.default === 'string')
28
+ into.add(def.default);
29
+ if (Array.isArray(def.preferred))
30
+ for (const id of def.preferred)
31
+ if (typeof id === 'string')
32
+ into.add(id);
33
+ }
34
+ if (!Array.isArray(m.props))
35
+ addStrings(m.props, into);
36
+ for (const fields of Object.values(m.overrides ?? {})) {
37
+ if (!fields)
38
+ continue;
39
+ if (typeof fields.component === 'string')
40
+ into.add(fields.component);
41
+ addStrings(fields.props, into);
42
+ }
43
+ return into;
44
+ }
45
+ /**
46
+ * The file name a lazy bundle gives a page or component subtree ID, without its `.ndjson` extension. It is one to one
47
+ * and contains no `%`, which servers decode in request paths: the ID is percent-encoded, then `_` becomes `_5F` and
48
+ * each `%` becomes `_`, so `12:34` is `12_3A34`.
49
+ * @param id - A page or subtree root ID.
50
+ * @returns A name safe in a URL path segment and on disk.
51
+ */
52
+ export const bundleFileName = (id) => encodeURIComponent(id).replace(/[%_]/g, (c) => (c === '%' ? '_' : '_5F'));
53
+ export function documentMetaOf(document) {
54
+ const { models: _models, shared: _shared, assets: _assets, ...meta } = document;
55
+ return meta;
56
+ }
57
+ /**
58
+ * Splits the layers into atomic subtrees: one per child of `@components` and one per direct child of a page, each with
59
+ * its layers parent first and siblings in document order, in whatever order the document lists them.
60
+ * @throws When a layer names a parent that is neither a page, `@components` nor another layer, or parents form a cycle.
61
+ */
62
+ function groupModels(models) {
63
+ const pages = [];
64
+ const pageIds = new Set();
65
+ for (const m of models) {
66
+ if (m.kind === 'page') {
67
+ pages.push(m);
68
+ pageIds.add(m.id);
69
+ }
70
+ }
71
+ const byId = new Map(), children = new Map(), roots = [];
72
+ for (const m of models)
73
+ if (m.kind !== 'page')
74
+ byId.set(m.id, m);
75
+ for (const m of models) {
76
+ if (m.kind === 'page')
77
+ continue;
78
+ const parent = m.parent ?? '';
79
+ if (parent === '@components' || pageIds.has(parent))
80
+ roots.push(m);
81
+ else if (byId.has(parent)) {
82
+ const list = children.get(parent);
83
+ if (list)
84
+ list.push(m);
85
+ else
86
+ children.set(parent, [m]);
87
+ }
88
+ else
89
+ throw new Error(`createLazyBundle: layer ${m.id} names a missing parent ${JSON.stringify(parent)}`);
90
+ }
91
+ const groups = [];
92
+ let placed = 0;
93
+ for (const root of roots) {
94
+ const parent = root.parent ?? '';
95
+ const group = {
96
+ rootId: root.id,
97
+ pageId: pageIds.has(parent) ? parent : null,
98
+ underComponents: parent === '@components',
99
+ hasMain: false,
100
+ models: [],
101
+ memberIds: new Set(),
102
+ refs: new Set(),
103
+ };
104
+ // Depth-first preorder: a parent before its children, siblings in document order.
105
+ const stack = [root];
106
+ while (stack.length) {
107
+ const m = stack.pop();
108
+ group.memberIds.add(m.id);
109
+ group.models.push(m);
110
+ componentRefsOf(m, group.refs);
111
+ if (isMainComponentRoot(m))
112
+ group.hasMain = true;
113
+ const kids = children.get(m.id);
114
+ if (kids)
115
+ for (let i = kids.length - 1; i >= 0; i--)
116
+ stack.push(kids[i]);
117
+ }
118
+ placed += group.models.length;
119
+ groups.push(group);
120
+ }
121
+ // Every layer whose chain of parents reaches a root was placed; the rest are parents of each other.
122
+ if (placed !== byId.size) {
123
+ const placedIds = new Set(groups.flatMap((g) => [...g.memberIds]));
124
+ const stuck = [...byId.keys()].find((id) => !placedIds.has(id));
125
+ throw new Error(`createLazyBundle: layer ${stuck} is in a cycle of parents`);
126
+ }
127
+ return { pages, groups };
128
+ }
129
+ /** Tarjan's strongly connected components over a directed graph, iterative so deep chains cannot overflow the stack.
130
+ * Returns components in topological order: every edge points from a higher index to a lower one. */
131
+ export function stronglyConnectedComponents(owners, depsOf) {
132
+ const deps = new Map(owners.map((owner) => [owner, [...new Set(depsOf(owner))].filter((d) => d !== owner)]));
133
+ const index = new Map(), low = new Map(), onStack = new Set();
134
+ const stack = [], sccs = [];
135
+ let clock = 0;
136
+ for (const root of owners) {
137
+ if (index.has(root))
138
+ continue;
139
+ const work = [[root, 0]];
140
+ while (work.length) {
141
+ const frame = work[work.length - 1], node = frame[0], edges = deps.get(node) ?? [];
142
+ if (frame[1] === 0) {
143
+ index.set(node, clock);
144
+ low.set(node, clock);
145
+ clock++;
146
+ stack.push(node);
147
+ onStack.add(node);
148
+ }
149
+ if (frame[1] < edges.length) {
150
+ const next = edges[frame[1]++];
151
+ if (!index.has(next))
152
+ work.push([next, 0]);
153
+ else if (onStack.has(next))
154
+ low.set(node, Math.min(low.get(node), index.get(next)));
155
+ continue;
156
+ }
157
+ work.pop();
158
+ if (work.length) {
159
+ const parent = work[work.length - 1][0];
160
+ low.set(parent, Math.min(low.get(parent), low.get(node)));
161
+ }
162
+ if (low.get(node) === index.get(node)) {
163
+ const members = [];
164
+ for (;;) {
165
+ const member = stack.pop();
166
+ onStack.delete(member);
167
+ members.push(member);
168
+ if (member === node)
169
+ break;
170
+ }
171
+ sccs.push(members);
172
+ }
173
+ }
174
+ }
175
+ return sccs;
176
+ }
177
+ /** Orders the models of one component subtree so main/variant-set roots and their in-subtree ancestors come first. */
178
+ export function orderSubtreeForCreate(models) {
179
+ const byId = new Map(models.map((m) => [m.id, m]));
180
+ const first = new Set();
181
+ for (const m of models) {
182
+ if (!isMainComponentRoot(m))
183
+ continue;
184
+ for (let at = m; at; at = at.parent ? byId.get(at.parent) : undefined) {
185
+ if (first.has(at.id))
186
+ break;
187
+ first.add(at.id);
188
+ }
189
+ }
190
+ return first.size ? [...models.filter((m) => first.has(m.id)), ...models.filter((m) => !first.has(m.id))] : [...models];
191
+ }
192
+ const textBytes = (text) => new TextEncoder().encode(text).byteLength;
193
+ function decodeBase64(base64) {
194
+ const binary = atob(base64);
195
+ const bytes = new Uint8Array(binary.length);
196
+ for (let i = 0; i < binary.length; i++)
197
+ bytes[i] = binary.charCodeAt(i);
198
+ return bytes;
199
+ }
200
+ function externalDataUrl(value, name) {
201
+ if (typeof value !== 'string' || !value.startsWith('data:'))
202
+ return [undefined, undefined];
203
+ const comma = value.indexOf(',');
204
+ if (comma < 0 || !/;base64$/i.test(value.slice(0, comma)))
205
+ return [undefined, undefined];
206
+ return [name, decodeBase64(value.slice(comma + 1))];
207
+ }
208
+ /** Groups a document into component subtrees (including mains that live on pages) and remaining page subtrees,
209
+ * and computes the topological order of component subtrees. Shared by the NDJSON and lazy bundle writers. */
210
+ export function planDocument(document) {
211
+ const { pages, groups } = groupModels(document.models);
212
+ const componentGroups = new Map();
213
+ const componentOwner = new Map();
214
+ const pageGroups = new Map();
215
+ const pageComponents = new Map();
216
+ for (const group of groups) {
217
+ if (group.underComponents || group.hasMain) {
218
+ componentGroups.set(group.rootId, group);
219
+ for (const m of group.models)
220
+ if (isMainComponentRoot(m))
221
+ componentOwner.set(m.id, group.rootId);
222
+ if (!group.underComponents && group.pageId) {
223
+ const list = pageComponents.get(group.pageId) ?? [];
224
+ list.push(group.rootId);
225
+ pageComponents.set(group.pageId, list);
226
+ }
227
+ }
228
+ else if (group.pageId) {
229
+ const list = pageGroups.get(group.pageId) ?? [];
230
+ list.push(group);
231
+ pageGroups.set(group.pageId, list);
232
+ }
233
+ }
234
+ const owners = [...componentGroups.keys()];
235
+ const depsOf = new Map(owners.map((owner) => {
236
+ const group = componentGroups.get(owner);
237
+ const deps = new Set();
238
+ for (const ref of group.refs) {
239
+ const target = componentOwner.get(ref) ?? ref;
240
+ if (target !== owner && componentGroups.has(target))
241
+ deps.add(target);
242
+ }
243
+ return [owner, deps];
244
+ }));
245
+ const sccs = stronglyConnectedComponents(owners, (owner) => depsOf.get(owner) ?? []);
246
+ const sccOf = new Map();
247
+ sccs.forEach((members, scc) => { for (const member of members)
248
+ sccOf.set(member, scc); });
249
+ for (const list of pageComponents.values())
250
+ list.sort((a, b) => sccOf.get(a) - sccOf.get(b));
251
+ return { pages, componentGroups, componentOwner, pageGroups, pageComponents, sccs, sccOf, depsOf };
252
+ }
253
+ const encodeModels = (models) => models.map((m) => encodeNdjsonLine({ model: m })).join('');
254
+ /**
255
+ * Splits an imported document into a `moondraft-lazy-v2` bundle: an `index.json` manifest, `shared.ndjson`, one NDJSON
256
+ * file per component subtree under `components/`, one per non-empty page under `pages/`, and (by default) media files
257
+ * under `assets/`. A host that serves the folder opens only the shown page and the component subtrees it references.
258
+ * @param document - The plain document returned by the importer.
259
+ * @param options - Asset externalization configuration.
260
+ * @returns The bundle manifest and a generator over the bundle's files.
261
+ */
262
+ export function createLazyBundle(document, options = {}) {
263
+ const plan = planDocument(document);
264
+ const assetPrefix = options.assets === false ? null : (options.assets ?? 'assets/').replace(/\/?$/, '/');
265
+ const { leading, ...restMeta } = documentMetaOf(document);
266
+ const hasMeta = Object.values(restMeta).some((value) => value !== undefined);
267
+ const pageText = new Map();
268
+ const pages = plan.pages.map((p) => {
269
+ const page = p;
270
+ const text = (plan.pageGroups.get(p.id) ?? []).map((group) => encodeModels(group.models)).join('');
271
+ if (text)
272
+ pageText.set(p.id, text);
273
+ return {
274
+ id: p.id,
275
+ name: page.name ?? '',
276
+ ...(page.order !== undefined ? { order: page.order } : {}),
277
+ ...(page.modes !== undefined ? { modes: page.modes } : {}),
278
+ bytes: textBytes(text),
279
+ };
280
+ });
281
+ const components = {};
282
+ for (const [owner, group] of plan.componentGroups) {
283
+ const scc = plan.sccOf.get(owner);
284
+ const deps = [...new Set([...(plan.depsOf.get(owner) ?? [])].map((d) => plan.sccOf.get(d))
285
+ .filter((dep) => dep !== scc))].sort((a, b) => a - b);
286
+ components[owner] = {
287
+ layers: group.models.length,
288
+ scc,
289
+ deps,
290
+ ...(!group.underComponents && group.pageId ? { page: group.pageId } : {}),
291
+ };
292
+ }
293
+ const index = {
294
+ format: 'moondraft-lazy-v2',
295
+ ...(leading !== undefined ? { leading } : {}),
296
+ ...(hasMeta ? { meta: restMeta } : {}),
297
+ pages,
298
+ componentOwner: Object.fromEntries(plan.componentOwner),
299
+ components,
300
+ pageComponents: Object.fromEntries(plan.pageComponents),
301
+ sccs: plan.sccs,
302
+ };
303
+ function* files() {
304
+ yield { path: 'index.json', content: JSON.stringify(index, null, 2) + '\n' };
305
+ let shared = '', sharedStarted = false;
306
+ const flushShared = () => {
307
+ if (!shared)
308
+ return null;
309
+ const chunk = shared, append = sharedStarted;
310
+ shared = '';
311
+ sharedStarted = true;
312
+ return { path: 'shared.ndjson', content: chunk, ...(append ? { append: true } : {}) };
313
+ };
314
+ for (const record of document.shared ?? []) {
315
+ shared += encodeNdjsonLine({ shared: record });
316
+ if (shared.length >= 1024 * 1024) {
317
+ const file = flushShared();
318
+ if (file)
319
+ yield file;
320
+ }
321
+ }
322
+ const takenAssetNames = new Set();
323
+ const assetName = (id) => {
324
+ const base = id.replace(/[^A-Za-z0-9._-]/g, '_') || 'asset';
325
+ let name = base;
326
+ for (let n = 2; takenAssetNames.has(name); n++)
327
+ name = `${base}-${n}`;
328
+ takenAssetNames.add(name);
329
+ return name;
330
+ };
331
+ for (const [id, asset] of Object.entries(document.assets ?? {})) {
332
+ if (!asset)
333
+ continue;
334
+ let out = asset;
335
+ // A video's poster stays an embedded data URL: the schema accepts nothing else there, and it is one still frame.
336
+ if (assetPrefix) {
337
+ const [srcName, srcBytes] = externalDataUrl(asset.src, assetPrefix + assetName(id));
338
+ if (srcName && srcBytes) {
339
+ out = { ...asset, src: srcName };
340
+ yield { path: srcName, content: srcBytes };
341
+ }
342
+ }
343
+ shared += encodeNdjsonLine({ asset: [id, out] });
344
+ if (shared.length >= 1024 * 1024) {
345
+ const file = flushShared();
346
+ if (file)
347
+ yield file;
348
+ }
349
+ }
350
+ const tail = flushShared();
351
+ if (tail)
352
+ yield tail;
353
+ else if (!sharedStarted)
354
+ yield { path: 'shared.ndjson', content: '' };
355
+ for (const [owner, group] of plan.componentGroups) {
356
+ yield { path: `components/${bundleFileName(owner)}.ndjson`, content: encodeModels(group.models) };
357
+ }
358
+ for (const [pageId, text] of pageText) {
359
+ yield { path: `pages/${bundleFileName(pageId)}.ndjson`, content: text };
360
+ }
361
+ }
362
+ return { index, files };
363
+ }
package/dist/report.js CHANGED
@@ -64,10 +64,15 @@ export function grouped(entries) {
64
64
  had.entry.count += e.count;
65
65
  if (e.assetIds)
66
66
  (had.entry.assetIds ??= []).push(...e.assetIds);
67
+ for (const source of e.sources ?? []) {
68
+ const kept = had.entry.sources ??= [];
69
+ if (kept.length < EXAMPLE_IDS && !kept.some(({ id }) => id === source.id))
70
+ kept.push(source);
71
+ }
67
72
  had.parts?.forEach((values, i) => values.add(parts[i]));
68
73
  }
69
74
  else
70
- out.set(key, { entry: { ...e, ...(e.assetIds && { assetIds: [...e.assetIds] }) }, ids: new Set(), parts: parts && parts.map(p => new Set([p])) });
75
+ out.set(key, { entry: { ...e, ...(e.assetIds && { assetIds: [...e.assetIds] }), ...(e.sources && { sources: e.sources.slice(0, EXAMPLE_IDS) }) }, ids: new Set(), parts: parts && parts.map(p => new Set([p])) });
71
76
  const { ids } = out.get(key);
72
77
  for (const id of e.ids ?? [])
73
78
  if (ids.size < EXAMPLE_IDS)
@@ -5,3 +5,12 @@ import type { DocumentJSON } from '@moondraft/editor/schema';
5
5
  * @returns Strings in JSON.stringify order, with one layer or resource encoded at a time.
6
6
  */
7
7
  export declare function serializeImportDocument(document: DocumentJSON): Generator<string>;
8
+ /**
9
+ * Writes an imported document as newline-delimited JSON (`meta`, `shared`, `asset` and `model` records) in chunks.
10
+ * Line records keep documents larger than the JS engine's single-string limit loadable by streaming readers. Pages,
11
+ * component subtrees (including mains living on pages) in topological order, and then page layers are emitted so a
12
+ * streaming reader always creates parents and main components before the layers and instances that use them.
13
+ * @param document - The plain document returned by the importer.
14
+ * @returns Chunks of NDJSON lines.
15
+ */
16
+ export declare function serializeImportNdjson(document: DocumentJSON): Generator<string>;
package/dist/serialize.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { documentMetaOf, encodeNdjsonLine, orderSubtreeForCreate, planDocument } from './lazy.js';
1
2
  const CHUNK = 64 * 1024;
2
3
  // Keep large image URLs out of the encoder's temporary strings. Align chunk boundaries so
3
4
  // JSON.stringify leaves valid surrogate pairs together and escapes lone surrogates as usual.
@@ -77,3 +78,56 @@ export function* serializeImportDocument(document) {
77
78
  if (chunk)
78
79
  yield chunk;
79
80
  }
81
+ /**
82
+ * Writes an imported document as newline-delimited JSON (`meta`, `shared`, `asset` and `model` records) in chunks.
83
+ * Line records keep documents larger than the JS engine's single-string limit loadable by streaming readers. Pages,
84
+ * component subtrees (including mains living on pages) in topological order, and then page layers are emitted so a
85
+ * streaming reader always creates parents and main components before the layers and instances that use them.
86
+ * @param document - The plain document returned by the importer.
87
+ * @returns Chunks of NDJSON lines.
88
+ */
89
+ export function* serializeImportNdjson(document) {
90
+ const plan = planDocument(document);
91
+ let chunk = encodeNdjsonLine({ meta: { ...documentMetaOf(document), stream: true } });
92
+ const push = (line) => {
93
+ chunk += line;
94
+ if (chunk.length < CHUNK)
95
+ return null;
96
+ const out = chunk;
97
+ chunk = '';
98
+ return out;
99
+ };
100
+ for (const record of document.shared ?? []) {
101
+ const out = push(encodeNdjsonLine({ shared: record }));
102
+ if (out)
103
+ yield out;
104
+ }
105
+ for (const [id, asset] of Object.entries(document.assets ?? {})) {
106
+ if (asset === undefined)
107
+ continue;
108
+ const out = push(encodeNdjsonLine({ asset: [id, asset] }));
109
+ if (out)
110
+ yield out;
111
+ }
112
+ const emit = (models) => {
113
+ const out = [];
114
+ for (const model of models) {
115
+ const ready = push(encodeNdjsonLine({ model }));
116
+ if (ready)
117
+ out.push(ready);
118
+ }
119
+ return out;
120
+ };
121
+ for (const page of plan.pages)
122
+ yield* emit([page]);
123
+ for (const scc of plan.sccs) {
124
+ const models = scc.flatMap((owner) => plan.componentGroups.get(owner).models);
125
+ yield* emit(orderSubtreeForCreate(models));
126
+ }
127
+ for (const page of plan.pages) {
128
+ for (const group of plan.pageGroups.get(page.id) ?? [])
129
+ yield* emit(group.models);
130
+ }
131
+ if (chunk)
132
+ yield chunk;
133
+ }
@@ -17,7 +17,17 @@ export declare function withImageCrop(_key: string, value: unknown): unknown;
17
17
  /** Moves a mark to a copy of the marked object. */
18
18
  export declare function moveMark(from: object, to: object): void;
19
19
  /** Adds `data` to the layer's `metadata.figma`. */
20
- export declare function carry(node: SceneNode, data: NonNullable<SceneNode["metadata"]>): void;
20
+ export declare function carry(node: {
21
+ metadata?: SceneNode["metadata"];
22
+ }, data: NonNullable<SceneNode["metadata"]>): void;
23
+ /** Carries the shadows and blurs of a text layer or group (`metadata.figma.effects`), with their shadow marks. */
24
+ export declare function carryEffects<T extends {
25
+ metadata?: SceneNode["metadata"];
26
+ }>(node: T, effects: {
27
+ readonly shadows?: readonly object[];
28
+ readonly layerBlur?: number;
29
+ readonly backgroundBlur?: number;
30
+ }): T;
21
31
  /** Clears a layer's constraints where Figma does not apply them. */
22
32
  export declare function clearConstraints(node: SceneNode): void;
23
33
  /** Carries the marks on a converted layer's shadows and fills into its metadata. */
@@ -36,6 +36,14 @@ export function carry(node, data) {
36
36
  const had = typeof figma === "object" && figma !== null && !Array.isArray(figma) ? figma : {};
37
37
  Object.assign(node, { metadata: { ...metadata, figma: { ...had, ...data } } });
38
38
  }
39
+ /** Carries the shadows and blurs of a text layer or group (`metadata.figma.effects`), with their shadow marks. */
40
+ export function carryEffects(node, effects) {
41
+ if (Object.keys(effects).length === 0)
42
+ return node;
43
+ const behind = (effects.shadows ?? []).flatMap((shadow, index) => marks.get(shadow)?.behind === true ? [index] : []);
44
+ carry(node, { effects: JSON.parse(JSON.stringify(effects)), ...(behind.length > 0 ? { shadowBehind: behind } : {}) });
45
+ return node;
46
+ }
39
47
  /** Clears a layer's constraints where Figma does not apply them. */
40
48
  export function clearConstraints(node) {
41
49
  if ("constraints" in node)
@@ -1,6 +1,6 @@
1
1
  import { field, isObject } from "../fields.js";
2
2
  import { styleBackedList } from "../styles.js";
3
- import { blendModeOf, hexColor, readNumbers } from "./shared.js";
3
+ import { blendModeOf, hasNonFinite, hexColor, NON_FINITE, readNumbers } from "./shared.js";
4
4
  import { markShadowBehind } from "../carry.js";
5
5
  /** The renderer refuses a node with more shadows than this (`WIRE_LIMITS.shadows` in packages/render-core/src/protocol.ts). */
6
6
  const MAX_SHADOWS = 16;
@@ -42,6 +42,11 @@ export function nodeEffects(node, walk) {
42
42
  if (field(effect, "visible", "boolean", at) === false) {
43
43
  return walk.report("property-left-out", `${label} (${type}) is hidden and left out: Taco effects cannot be hidden`);
44
44
  }
45
+ // Moondraft patch 0055: a non-finite radius, spread or offset leaves out only this effect.
46
+ const offsetObject = blurKind ? undefined : effect["offset"];
47
+ if (hasNonFinite(effect, blurKind ? ["radius"] : ["radius", "spread"]) || isObject(offsetObject) && hasNonFinite(offsetObject, ["x", "y"])) {
48
+ return walk.report("property-left-out", `${label} (${type}) is left out: its ${blurKind ? "radius" : "offset, spread or radius"} has ${NON_FINITE}`);
49
+ }
45
50
  let radius = field(effect, "radius", "number", at) ?? 0;
46
51
  if (radius < 0) {
47
52
  walk.report("approximated", `${label} (${type}) radius ${String(radius)} is below 0; 0 is used`);
@@ -73,8 +78,11 @@ export function nodeEffects(node, walk) {
73
78
  const spread = field(effect, "spread", "number", at) ?? 0;
74
79
  const colorObject = field(effect, "color", "object", at);
75
80
  const color = colorObject && readNumbers(colorObject, ["r", "g", "b", "a"], `${at} color`);
76
- if (!color)
77
- return walk.report("property-left-out", `${label} (${type}) is left out: it has no complete colour`);
81
+ if (!color) {
82
+ // Moondraft patch 0055: a non-finite channel leaves out only this effect.
83
+ const why = colorObject && hasNonFinite(colorObject, ["r", "g", "b", "a"]) ? `its colour has ${NON_FINITE}` : "it has no complete colour";
84
+ return walk.report("property-left-out", `${label} (${type}) is left out: ${why}`);
85
+ }
78
86
  if (shadows.length === MAX_SHADOWS)
79
87
  return walk.report("property-left-out", `${label} (${type}) is left out: Taco draws at most ${String(MAX_SHADOWS)} shadows`);
80
88
  // Moondraft patch (../carry.ts): Moondraft knocks a drop shadow out under the node's fill, as Figma does unless
@@ -15,5 +15,6 @@ import type { FigmaNodeConverter } from "../walk.ts";
15
15
  *
16
16
  * A Taco group follows its layers' constraints (see `NodeBase.constraints`).
17
17
  * The adapter reads the group's own constraints from its Figma metadata.
18
+ * Moondraft patch: its shadows and blurs are carried there too (`carryEffects`).
18
19
  */
19
20
  export declare const convertGroup: FigmaNodeConverter;